예제 #1
0
def get_xsg(f):
    """
    获取限售股解禁
    """
    for year in range(2010, datetime.today().year + 1):
        for month in range(1, 13):
            if month in range(1, 10):
                dset_name = str(year) + "0" + str(month)
            else:
                dset_name = str(year) + str(month)

            if f.get(dset_name) is not None:
                count.inc_by_index(conf.HDF5_COUNT_PASS)
                continue

            try:
                df = ts.xsg_data(year=year,
                                 month=month,
                                 pause=conf.REQUEST_BLANK)
                df = df.drop("name", axis=1)
                df = df.sort_values(by=[conf.HDF5_SHARE_DATE_INDEX])
                tool.create_df_dataset(f, dset_name, df)
                console.write_exec()
                count.inc_by_index(conf.HDF5_COUNT_GET)
            except Exception as er:
                print(str(er))
    time.sleep(conf.REQUEST_BLANK)
    return
예제 #2
0
 def get_xsg_monthly(self):
     try:
         df = ts.xsg_data()
         df.drop_duplicates(inplace=True)
         date = np.array(df['date'])
         code = np.array(df['code'])
         count = np.array(df['count'])
         ratio = np.array(df['ratio'])
         arrays = [date, code]
         tuples = list(zip(*arrays))
         index = pd.MultiIndex.from_tuples(tuples, names=['date', 'code'])
         s = pd.Series(count, index=index)
         f = s.to_frame()
         f.rename(index=str, columns={0: "count"}, inplace=True)
         f['ratio'] = ratio
         f.to_sql('stock_xsg_data',
                  mysqlEngine,
                  if_exists='append',
                  index=True,
                  index_label=['date', 'code'],
                  dtype={
                      'code': mysql.NVARCHAR(6),
                      'date': mysql.DATE
                  })
         """
      mh = MysqlHandle()
      DFToSQLOneByOne(mh.session,f,'Report')
      """
     except Exception, e:
         print e
예제 #3
0
def banshare(request, year, month):
    #       code    name        date         count  ratio
    # 0    002032   苏泊尔     2019-08-30      8.29   0.01
    # today = datetime.date.today()
    # year = today.strftime("%Y")
    # month = today.strftime("%m")
    month_total = stock_ban.objects.filter(month=month).count()
    if month_total == 0:
        df = ts.xsg_data(year=year, month=month)
        id_list = df.index.tolist()
        for id in id_list:
            code1 = df.loc[id, 'code']
            name1 = df.loc[id, 'name']
            date1 = df.loc[id, 'date']
            count1 = df.loc[id, 'count']
            ratio1 = df.loc[id, 'ratio']
            sb = stock_ban(code=code1,
                           name=name1,
                           date=date1,
                           count=count1,
                           ratio=ratio1,
                           month=month)
            sb.save()
            return HttpResponse("{} banshare Done".format(month))
    else:
        return HttpResponse("{} have synced".format(month))
예제 #4
0
 def restrict_share(self):
     data = ts.xsg_data()
     ratio = list(data.ratio)
     restrict_code = list(data.code)
     for index in range(len(ratio)):
         if ratio[index] > 5 and restrict_code[index] in self.valid_code:
             self.restrict_code.append(restrict_code[index])
             self.valid_code.remove(restrict_code[index])
예제 #5
0
def xsg_data():
    year=[i+2010 for i in range(7)]
    DTS=[]
    for y in year:
        preDTS=ts.xsg_data(year=y)
        DTS.append(preDTS)

    DTS=pd.concat(DTS)
    DTS.to_csv('D:\\ts\\tzck\\xsg_data.csv',encoding='gbk')
예제 #6
0
def get_stock_xsgjj(nd, yf):
    """
        获取限售股解禁
    """
    try:
        res = ts.xsg_data(nd, yf)
        return res
    except:
        return None
예제 #7
0
    def download_xsg_data(self):
        """
        """
        #print('downloading the xsg_data info...')

        try:
            data_2017_1 = ts.xsg_data(2017, 1)
            filename = 'xsg_data_2017_1'
            data_2017_1.to_excel(self.working_folder + filename + '.xlsx',
                                 encoding='GBK')
        except:
            print('download xsg_data_2017_1 failed')

        try:
            data_2017_2 = ts.xsg_data(2017, 2)
            filename = 'xsg_data_2017_2'
            data_2017_2.to_excel(self.working_folder + filename + '.xlsx',
                                 encoding='GBK')
        except:
            print('download xsg_data_2017_2 failed')

        try:
            data_2017_3 = ts.xsg_data(2017, 3)
            filename = 'xsg_data_2017_3'
            data_2017_3.to_excel(self.working_folder + filename + '.xlsx',
                                 encoding='GBK')
        except:
            print('download xsg_data_2017_3 failed')

        try:
            data_2017_4 = ts.xsg_data(2017, 4)
            filename = 'xsg_data_2017_4'
            data_2017_4.to_excel(self.working_folder + filename + '.xlsx',
                                 encoding='GBK')
        except:
            print('download xsg_data_2017_4 failed')

        data = data_2017_3.append(data_2017_2).append(data_2017_1)
        data.drop_duplicates(subset=['code'], keep='first', inplace=True)
        filename = 'xsg_data'
        data.to_excel(self.working_folder + filename + '.xlsx', encoding='GBK')
        return
예제 #8
0
def getvrdata(isinit='no'):
    mylogger = getmylogger()
    curday = datetime.date.today()
    print(curday)
    curyear = curday.year
    curmonth = curday.month
    quarter = (curmonth - 1) // 3 + 1
    # prdict = {'profitdivi': '分配预案', 'forecast': '业绩预告', 'xsg': '限售股解禁', 'fundholdings': '基金持股', 'newstocks': '新股'}
    prdict = {'fundholdings': '基金持股'}
    for dv in prdict:
        vrtbname = dv
        vrinfo = prdict[vrtbname]
        try:
            if dv == "profitdivi":
                df = ts.profit_data(year=curyear, top=100)
                if isinit == 'no' and df is not None:
                    df = df[df['report_date'] >= str(curday)]
            elif dv == "forecast":
                df = ts.forecast_data(curyear, quarter)
                if isinit == 'no' and df is not None:
                    # print(df[df['report_date'].isin(['2019-12-28'])])
                    df = df[df['report_date'] >= str(curday)]
            elif dv == "xsg":
                df = ts.xsg_data()
                if isinit == 'no' and df is not None:
                    curym = datetime.date.today().strftime("%Y-%m")
                    df = df[df['date'].str.contains(curym)]
            elif dv == "fundholdings":
                if quarter == 1:
                    quarter = 4
                    curyear -= 1
                else:
                    quarter -= 1
                df = ts.fund_holdings(curyear, quarter)
                if isinit == 'no' and df is not None:
                    lastyq = str(curyear) + '-' + str(quarter)
                    df = df[df['date'].str.contains(lastyq)]
                if df is not None:
                    newcolumns = ['nums', 'count', 'nlast', 'name', 'amount', 'date', 'ratio', 'code', 'clast']
                    df.columns = newcolumns
            elif dv == "newstocks":
                df = ts.new_stocks()
                if isinit == 'no' and df is not None:
                    df = df[df['ipo_date'] >= str(curday)]
            else:
                mylogger.info("没有执行命令。")
            if df is not None:
                tosql(df, vrtbname, "append", vrinfo, mylogger)
            else:
                mylogger.info("没有%s数据。" % vrinfo)
        except Exception:
            tracelog = traceback.format_exc()
            mylogger.info("获取数据异常。")
            mylogger.info(tracelog)
예제 #9
0
 def get_ban_shares(self, context):
     curr_year = context.now.year
     curr_month = context.now.month
     jj_range = [
         ((curr_year * 12 + curr_month + i - 1) / 12, curr_year * 12 +
          curr_month + i - (curr_year * 12 + curr_month + i - 1) / 12 * 12)
         for i in range(-1, 1)
     ]  #range 可指定解禁股的时间范围,单位为月
     df_jj = functools.reduce(
         lambda x, y: pd.concat([x, y], axis=0),
         [ts.xsg_data(year=y, month=m) for (y, m) in jj_range])
     return df_jj.code.values
예제 #10
0
파일: invest.py 프로젝트: cnslyq/ts
def lifted(engine, year, month):
    # tsu.to_sql(engine, 'invest_lifted', plist=[year, month])
    tbl = "invest_lifted"
    tsl.log(tbl + " start...")
    try:
        df = ts.xsg_data(year, month)
        df = df.set_index('code', drop='true')
        df.to_sql(tbl, engine, if_exists='append')
        tsl.log(tbl + " done")
    except BaseException, e:
        print
        print e
        tsl.log(tbl + " error")
예제 #11
0
def xsg_data(request):
    try:
        year = request.POST.get('year', '')  # 必填
        month = request.POST.get('month', '')  # 必填
        data = ts.xsg_data(year, month)
        res = {
            'columns': ['code', 'name', 'date', 'count', 'ratio'],
            'data': json.loads(json.dumps(data.values, cls=DateEncoder))
        }
    except (BaseException):
        return HttpResponse(BaseException)
    else:
        return HttpResponse(json.dumps(res), content_type="application/json")
예제 #12
0
def updateXsgData(con, year: int, month: int):
    import share.model.dao.reference.XsgData as Model
    dateString = "{year:04d}-{month:02d}".format(year=year, month=month)
    logging.debug("Updating month XsgData of {}".format(dateString))
    df = ts.xsg_data(year=year, month=month, retry_count=16)
    res = []
    for _, row in df.iterrows():
        obj = Model.rowToORM(row, year=year, month=month)
        if obj is not None:
            res.append(obj)
    Base.metadata.create_all(con.engine)
    con.save_all(res)
    return
예제 #13
0
def get_restricted_stock(year=None,
                         month=None,
                         retry_count=RETRY_COUNT,
                         pause=PAUSE):
    """
    获取限售股解禁数据
    Args
        year:年份,默认为当前年
        month:解禁月份,默认为当前月
        retry_count : int, 默认 3
                     如遇网络等问题重复执行的次数 
        pause : int, 默认 0
    Returns:
        字典的列表
    """
    year = util.get_year() if year is None else year
    month = util.get_month() if month is None else month
    logger.info(
        'Begin get restricted stock data, the year is: %s, month is: %s' %
        (year, month))
    try:
        data_df = ts.xsg_data(year=year,
                              month=month,
                              retry_count=retry_count,
                              pause=pause)
    except Exception as e:
        logging.exception(
            'Error get restricted stock data, the year is: %s, month is: %s' %
            (year, month))
        return None
    else:
        data_dicts = []
        if data_df is not None and not data_df.empty:
            data_dicts = [{
                'code': row[0],
                'name': row[1],
                'year': year,
                'month': month,
                'date': row[2],
                'count': row[3],
                'ratio': row[4],
                'insert_date': today_line
            } for row in data_df.values]
            logger.info(
                'Success get restricted stock data, the year is: %s, month is: %s'
                % (year, month))
        else:
            logger.warn(
                'Empty get restricted stock data, the year is: %s, month is: %s'
                % (year, month))
        return data_dicts
예제 #14
0
def get_data_date(year,month):
    cmd='''delete  from %s where `year`=%s and `month`=%s '''%(table_name,year,month)
    print cmd
    run_mysql_cmd(cmd=cmd,conn=conn) #删除指定年和月的数据
    try:
        rs=ts.xsg_data(year=year,month=month)
        rs['year']=year
        rs['month']=month
        rs=rs.drop_duplicates() #去除重复的数据,没想到还有重复的,心塞塞,这个api不咋地啊,挖地兔
        pd.DataFrame.to_sql(rs, table_name, con=conn , flavor='mysql', if_exists='append',index=False)
        return rs
    except:
        print("this year has no records")
        return None
예제 #15
0
파일: xsjj.py 프로젝트: jianghang/stockout
def dump_xsjj(year, month):
    df = ts.xsg_data(year=year, month=month)
    if df is None:
        return

    list = []
    for index, row in df.iterrows():
        xsjj_data = xsjj_model(code=row['code'],
                               name=row['name'],
                               date=row['date'])
        xsjj_data.count = row['count']
        xsjj_data.ratio = float(row['ratio'])
        list.append(xsjj_data)
    save_list(list)
예제 #16
0
파일: quotes.py 프로젝트: hicode/autotrade
def reference(year_to_start=2010):
    def profit_data(year):
        profit_data = ts.profit_data(year=year, top=100)
        profit_data.sort('shares', ascending=False)
        if profit_data is not None:
            profit_data.to_sql('reference_profit_data',
                               engine,
                               flavor='mysql',
                               if_exists='append')

    def forecast_data(year):
        for i in range(4):
            predts = ts.forecast_data(year, i + 1)
            if predts is not None:
                predts.to_sql('reference_forecast_data',
                              engine,
                              flavor='mysql',
                              if_exists='append')

    def fund_holdings(year):
        for i in range(4):
            predts = ts.fund_holdings(year, i + 1)
            if predts is not None:
                predts.to_sql('reference_fund_holdings',
                              engine,
                              flavor='mysql',
                              if_exists='append')

    starttime = datetime.datetime.today()
    year = [
        year_to_start + i for i in range(starttime.year - year_to_start + 1)
    ]
    thread_pool.map(profit_data, year)
    thread_pool.map(forecast_data, year)
    thread_pool.map(fund_holdings, year)
    thread_pool.join()

    xsg_data = ts.xsg_data()
    if xsg_data is not None:
        xsg_data.to_sql('reference_xsg_data',
                        engine,
                        flavor='mysql',
                        if_exists='replace')

    new_stocks = ts.new_stocks()
    if new_stocks is not None:
        new_stocks.to_sql('reference_new_stocks',
                          engine,
                          flavor='mysql',
                          if_exists='replace')
예제 #17
0
 def setXsgData(self,year=None,month=None, number = 1, isSave = False,tableName = REFERENCE_XSG_DATA):
     [year, month] = getYearMonth(year, month)
     for i in range(0,number):
         try:
             df = ts.xsg_data(year, month)
             if month<10:
                 df['date'] =str(year) +'0'+ str(month)
             else:
                 df['date'] = str(year) + str(month)
             if isSave is True:
                 df.to_sql(tableName,self.engine_sql, if_exists='append')
                 month = month - 1
             if month < 1:
                 month = 12
                 year = year - 1
         except IOError,e:
             print e
예제 #18
0
 def lift_ban_stock(self, interval=6):
     '''
         取即将解禁的股票,默认取半年的
     '''
     raw_data = None
     start_month = int(datetime.strftime(datetime.now(), '%m'))
     start_year = int(datetime.strftime(datetime.now(), '%Y'))
     for month in xrange(start_month, start_month + interval):
         foot = month / 13
         month = month % 12
         if month == 0:
             month = 12
         print 'get {0} {1} 解禁数据'.format(start_year + foot, month)
         data = ts.xsg_data(year=(start_year + foot), month=month)
         raw_data = pd.concat([raw_data, data], axis=0)
     raw_data.index = raw_data['code']
     return raw_data
예제 #19
0
def get_ref_xsg(year=None, month=None):
    """
    投资参考 系列
    以月的形式返回限售股解禁情况,通过了解解禁股本的大小,判断股票上行的压力。
    可通过设定年份和月份参数获取不同时段的数据
    """
    df = ts.xsg_data(year, month)
    print(df)
    if df is not None:
        if len(df) > 0:
            df.insert(0, 'year', year)
            df.insert(1, 'month', month)
        res = df.to_sql(invest_stock_ref_xsg, engine, if_exists='replace')
        msg = 'ok' if res is None else res
        print('获取业绩预告数据: {0} {1}: {2}'.format(year, month, msg) + '\n')
    else:
        print('获取业绩预告数据: {0} {1}: {2}'.format(year, month, 'None') + '\n')
예제 #20
0
def job_2():
    try:
        print("I'm working......投资参考数据")
        # 分配预案
        profit_data = ts.profit_data(year, top=1000)
        data = pd.DataFrame(profit_data)
        data.to_sql('profit_data',engine,index=True,if_exists='replace')
        print("分配预案......done")

        # 业绩预告
        forecast_data = ts.forecast_data(year,1)
        data = pd.DataFrame(forecast_data)
        data.to_sql('forecast_data',engine,index=True,if_exists='replace')
        print("业绩预告......done")

        # 限售股解禁
        xsg_data = ts.xsg_data()
        data = pd.DataFrame(xsg_data)
        data.to_sql('xsg_data',engine,index=True,if_exists='replace')
        print("限售股解禁......done")

        # 基金持股
        fund_holdings = ts.fund_holdings(year, 1)
        data = pd.DataFrame(fund_holdings)
        data.to_sql('fund_holdings',engine,index=True,if_exists='replace')
        print("基金持股......done")
    
        # 新股数据
        new_stocks = ts.new_stocks()
        data = pd.DataFrame(new_stocks)
        data.to_sql('new_stocks',engine,index=True,if_exists='replace')
        print("新股数据......done")

        # 融资融券(沪市)
        sh_margins = ts.sh_margins()
        data = pd.DataFrame(sh_margins)
        data.to_sql('sh_margins',engine,index=True,if_exists='replace')
        print("融资融券(沪市)......done")

        # 融资融券(深市)
        sz_margins = ts.sz_margins()
        data = pd.DataFrame(sz_margins)
        data.to_sql('sz_margins',engine,index=True,if_exists='replace')
        print("融资融券(深市)......done")
    except Exception as e:
        print(e)
예제 #21
0
 def lift_ban_stock(self, interval=6):
     '''
         取即将解禁的股票,默认取半年的
     '''
     raw_data = None
     start_month = int(datetime.strftime(datetime.now(), '%m'))
     start_year = int(datetime.strftime(datetime.now(), '%Y'))
     for month in xrange(start_month, start_month+interval):
         foot = month / 13
         month = month%12
         if month == 0:
             month = 12
         print 'get {0} {1} 解禁数据'.format(start_year+foot, month)
         data = ts.xsg_data(year=(start_year+foot),month=month)
         raw_data = pd.concat([raw_data, data], axis=0)
     raw_data.index = raw_data['code']
     return raw_data
예제 #22
0
	def update_restrict_stock_data( self, extend_years = 3 ):
		
		if not os.path.exists( self.__restrict_stock_file_name ):
			list_date_quarter = Utils.parse_date_to_ymd( self.__date )
			df_restrict_stock_data = pd.DataFrame()
			
			for year in range( 2010, int( list_date_quarter[0] ) + extend_years + 1 ):
				for month in range( 1, 13 ):
					try:
						df_tmp = ts.xsg_data( year, month )
					except:
						ERROR( 'exception occurs when update restrict stock data of year {0} month {1}'.format( year, month ) )
					else:
						df_restrict_stock_data = df_restrict_stock_data.append( df_tmp )
						LOG( 'update restrict stock data of year {0} month {1}'.format( year, month ) )
					if year == int( list_date_quarter[0] ) + extend_years  and month == int( list_date_quarter[1] ):		
						break
			Utils.save_data( df_restrict_stock_data, self.__restrict_stock_file_name, 'restrict stock' )
예제 #23
0
def getXsg(cursor):
    for i in range(1992, 2017 + 1):
        for j in range(1, 12 + 1):
            try:
                print(i, j)
                df = ts.xsg_data(year=i, month=j)

                # 处理缺失值
                df = df.stack().replace('--', '0').unstack()
                print(df)

                dfLen = len(df)
                # print(dfLen)
                uuidList = []  # 添加uuid
                yearList = []  # 添加年份
                monthList = []  # 添加月份
                for l in range(0, dfLen):
                    uuidList.append(uuid.uuid1())
                    yearList.append(str(i))
                    monthList.append(str(j))
                df['uuid'] = uuidList
                df['year'] = yearList
                df['month'] = monthList

                for k in range(0, dfLen):
                    df2 = df[k:k + 1]

                    print(df2)

                    cursor.execute(
                        "insert into stock_xsg(uuid, code, name, lift_date, count, ratio, year, month) "
                        "values(:uuid, :code, :name, to_date(:lift_date, 'yyyy-MM-dd'), :count, :ratio, :year, :month)",
                        (str(list(df2['uuid'])[0]), str(list(df2['code'])[0]),
                         str(list(df2['name'])[0]), str(list(
                             df2['date'])[0]), round(float(df2['count']), 4),
                         round(float(
                             df2['ratio']), 4), str(list(
                                 df2['year'])[0]), str(list(df2['month'])[0])))
                cursor.execute("commit")
            except Exception:
                pass
예제 #24
0
def dump_xsjj(year, month):
    logging.info("开始获取数据 %s %s", year, month)
    df = ts.xsg_data(year=year, month=month)
    logging.info("获取数据完成 %s %s", year, month)
    if df is None:
        return

    list = []

    for index, row in df.iterrows():
        code = row['code']
        name = row['name']
        date = row['date']
        xsjj_data = get_xsjj_by_code_date(code, date)
        if xsjj_data is not None:
            logging.info("%s %s %s 数据已dump", code, name, date)
        xsjj_data = xsjj_model(code=code, name=name, date=date)
        xsjj_data.count = row['count']
        xsjj_data.ratio = float(row['ratio'])
        list.append(xsjj_data)
    session.add_all(list)
예제 #25
0
    def restricted_stcok(self, durting=None):
        """
        检查为未来一年的限售股信息

        Parameters
        ----------
        durting 默认值为 12  往后查询多少个月

        Returns
        -------

        """
        if durting is None:
            durting = 6
        else:
            pass
        _month = int(self.month)
        _year = int(self.year)
        rsd = pandas.DataFrame()  #rsd => Restricted Stock Datas
        for i in tqdm.tqdm(range(0, durting)):
            if _month > 12:
                _year += 1
                _month = 1

            else:
                pass
            try:
                rs_m = ts.xsg_data(year=_year, month=_month)
                print(_month, _year)
                rsd = rsd.append(rs_m, ignore_index=True)
            except:
                print('this month data error')
                pass
            _month += 1
        _path = '../report/restricted_stock_%s.csv' % (self.year)
        return rsd
예제 #26
0
    def update_unblocked(self, during=12):
        self.during = during
        logger.info(get_time)
        logger.info('update unblocked stock %s months' % self.during)
        month = int(time.strftime("%m", time.localtime()))
        year = int(time.strftime("%Y", time.localtime()))
        df = pd.DataFrame()

        for i in range(0, self.during):
            if month > 12:
                year += 1
                month = 1

            logger.debug('search the %s-%s datas' % (year, month))
            try:
                temp = ts.xsg_data(year=year, month=month)
                df = df.append(temp, ignore_index=True)
            except:
                logger.error('this month data error')
                pass
            month += 1
        #df=df.reset_index()
        logger.info('downloading_completed')
        return df
예제 #27
0
 def xsg_data(self, conns):
     self.base = Base()
     self.financial_data = conns['financial_data']
     self.df = ts.xsg_data()
     self.base.batchwri(self.df, 'xianshougujiejin', self.financial_data)
예제 #28
0
 def get_classified_stock(self, year=None, month=None):
     df = ts.xsg_data(year, month)
     filename = '{}-{}-classified_stock.xls'.format(year, month)
     self.save_to_excel(df, filename)
예제 #29
0
import tushare as ts

# 获取分配预案数据
df = ts.profit_data(top=60)

# 业绩预告
# 按年度、季度获取业绩预告数据,接口提供从1998年以后每年的业绩预告数据,需指定年度、季度两个参数。
fd = ts.forecast_data(2014, 2)
print(fd)

# 限售股解禁
# 以月的形式返回限售股解禁情况,通过了解解禁股本的大小,判断股票上行的压力。可通过设定年份和月份参数获取不同时段的数据。
xsg = ts.xsg_data()

# 基金持股
# 获取每个季度基金持有上市公司股票的数据。
fh = ts.fund_holdings(2014, 4)
print(fh)

# 新股数据
ns = ts.new_stocks()
print(ns)

# 融资融券(沪市)
# 沪市的融资融券数据从上海证券交易所网站直接获取,提供了有记录以来的全部汇总和明细数据。根据上交所网站提示:数据根据券商申报的数据汇总,由券商保证数据的真实、完整、准确。
sm = ts.sh_margins(start='2015-01-01', end='2015-04-19')
print(sm)

# 融资融券(深市)
ts.sz_margins(start='2015-01-01', end='2015-04-19')
예제 #30
0
파일: xsg.py 프로젝트: jjhua/tushare_study
import tushare as ts
import pymongo
import json

# 600547:山东黄金
# 600362:江西铜业
# 600312:平高电气
# 600499:科达洁能
# 603993:洛阳钼业
db = "InvestInfos"
coll = "XSG_jiejin"
year = 2017
month = 12

conn = pymongo.MongoClient('127.0.0.1', port=27017)
df = ts.xsg_data()
# index data columns(X columns)
dicIndex = json.loads(df.to_json(orient='split'))
for i, ind in enumerate(dicIndex['index']):
    jsonstr = {
        '_id': dicIndex['data'][i][2] + "-" + dicIndex['data'][i][0],
        'year': year,
        'month': month,
        dicIndex['columns'][0]: dicIndex['data'][i][0],
        dicIndex['columns'][1]: dicIndex['data'][i][1],
        dicIndex['columns'][2]: dicIndex['data'][i][2],
        dicIndex['columns'][3]: dicIndex['data'][i][3],
        dicIndex['columns'][4]: dicIndex['data'][i][4]
    }
    try:
        conn[db][coll].insert(jsonstr)
예제 #31
0
def XsgJj():
	df=ts.xsg_data()
	df['ratio']=df['ratio'].astype(float)
	df=df.sort_values('ratio',ascending=False)
	return [u"限售股解禁:",df[df.ratio>10]]
예제 #32
0
 def get_classified_stock(self,year=None,month=None):
     df=ts.xsg_data(year,month)
     filename='{}-{}-classified_stock.xls'.format(year,month)
     self.save_to_excel(df,filename)
예제 #33
0
import tushare as ts
import rqalpha as rq

if __name__ == '__main__':
    stock_list = ts.get_stock_basics()
    stock_list.loc[:, 'name_3'] = stock_list.apply(lambda x: x['name'][0:3],
                                                   axis=1)
    ST_list = stock_list[stock_list.name_3 == '*ST']
    ST_list.drop(['name_3'], inplace=True, axis=1, errors='ignore')
    ST_list.loc[:, '5日涨幅'] = 0
    ST_list.loc[:, '10日涨幅'] = 0
    ST_list.loc[:, '20日涨幅'] = 0
    ST_list.loc[:, '最新价格'] = 0
    ST_list.loc[:, '最新价格'] = 0
    ST_list.loc[:, '限售股解禁'] = "N"
    xsg1 = ts.xsg_data(month='02')  #限售股解禁
    xsg2 = ts.xsg_data(month='03')  #限售股解禁
    xsg3 = ts.xsg_data(month='04')  #限售股解禁
    for stk in ST_list.index:
        # 20日涨幅
        hist = ts.get_hist_data(stk, start='2017-02-08',
                                end='2017-03-07').sort_index(ascending=False)
        if len(hist) > 0:
            start_price = hist.tail(1).iloc[0, 0]
            end_price = hist.head(1).iloc[0, 0]
            percentage = 100 * (end_price - start_price) / start_price
            ST_list.loc[stk, '20日涨幅'] = percentage

            # 最新价格
            ST_list.loc[stk, '最新价格'] = end_price
예제 #34
0
holding=stock.values
len(holding)
first=holding[0][0]
sec=holding[1][0]
he=first+sec

ho=re.split('\s+',he)

import pandas as pd
import tushare as ts
stock=ts.get_stock_basics()
s=stock.name
code=stock.index
#解禁股,st股,亏损股
m1=ts.xsg_data(month=11,year=2017)
m2=ts.xsg_data(month=12,year=2017)
m3=ts.xsg_data(month=1,year=2018)
m4=ts.xsg_data(month=2,year=2018)
st=ts.get_st_classified()
nianbao=ts.get_report_data(2016,4)
kui=nianbao.code[nianbao.eps<=0]
hei=pd.concat([m1.code,m2.code,m3.code,st.code,kui],axis=0)
hei.to_excel('hei.xls')
hq.loc[:,:28]=hq.loc[:,:28].astype('float64')
ts.get_concept_classified?? #显示源码

#m3=ts.xsg_data(month=1)
#st股
#实时5+1day
m=ts.get_k_data('399101', ktype='5')
예제 #35
0
#coding=utf-8
'''
Created on 2015年6月4日

@author: Administrator
'''
import tushare as ts

# 分配预案
#每到季报、年报公布的时段,就经常会有上市公司利润分配预案发布,而一些高送转高分红的股票往往会成为市场炒作的热点。
df = ts.profit_data(top=60)
df.sort('shares',ascending=False)
df[df.shares>=10]#选择每10股送转在10以上的

# 业绩预告
ts.forecast_data(2014,2)#获取2014年中报的业绩预告数据

# 限售股解禁
# 以月的形式返回限售股解禁情况,通过了解解禁股本的大小,判断股票上行的压力。可通过设定年份和月份参数获取不同时段的数据。
ts.xsg_data()

# 新股数据
ts.new_stocks()

# 融资融券
ts.sh_margins(start='2015-01-01', end='2015-04-19')
ts.sz_margins(start='2015-01-01', end='2015-04-19')
#如果不设symbol参数或者开始和结束日期时段设置过长,数据获取可能会比较慢,建议分段分步获取,比如一年为一个周期
ts.sh_margin_details(start='2015-01-01', end='2015-04-19', symbol='601989')
ts.sz_margin_details('2015-04-20')