Ejemplo n.º 1
0
 def 下载板块数据(self):
     # 获取不同分类数据
     ts.get_industry_classified().to_csv('./股票数据/基本信息/行业分类.csv')
     ts.get_concept_classified().to_csv('./股票数据/基本信息/概念分类.csv')
     ts.get_area_classified().to_csv('./股票数据/基本信息/地域分类.csv')
     ts.get_sme_classified().to_csv('./股票数据/基本信息/中小板.csv')
     ts.get_gem_classified().to_csv('./股票数据/基本信息/创业板.csv')
     ts.get_st_classified().to_csv('./股票数据/基本信息/风险警示板.csv')
     ts.get_hs300s().to_csv('./股票数据/基本信息/沪深300.csv')
     ts.get_sz50s().to_csv('./股票数据/基本信息/上证50.csv')
     ts.get_zz500s().to_csv('./股票数据/基本信息/中证500.csv')
Ejemplo n.º 2
0
 def core_function(self, func):
     self.set_data()
     mongo = MongoClient("127.0.0.1", 27017)
     if (func == "industry_classified"):
         df = ts.get_industry_classified()
     elif (func == "concept_classified"):
         df = ts.get_concept_classified()
     elif (func == "area_classified"):
         df = ts.get_area_classified()
     elif (func == "gem_classified"):
         df = ts.get_gem_classified()
     elif (func == "sme_classified"):
         df = ts.get_sme_classified()
     elif (func == "st_classified"):
         df = ts.get_st_classified()
     elif (func == "hs300s"):
         df = ts.get_hs300s()
     elif (func == "sz50s"):
         df = ts.get_sz50s()
     elif (func == "zz500s"):
         df = ts.get_zz500s()
         print(df)
     elif (func == "terminated"):
         df = ts.get_terminated()
     else:
         df = {}
     insert_string = df.to_json(orient='records')
     items = json.loads(insert_string)
     coll = mongo.classify[func]
     coll.insert(items)
Ejemplo n.º 3
0
def main_financial_statistic_process(path):
  store_path = os.path.join(path,'statistic/')
  if not os.path.exists(store_path):
      os.makedirs(store_path)
  scu = SCU(path=path)
  stock_codes = scu.stock_codes_remove_no_stock_basic()
  FFC =financail_factor_statistic(path=path)
  
  sz50 = ts.get_sz50s()
  stock_codes = sz50['code']
  
  stock_industry = ts.get_industry_classified()
  stock_codes = stock_industry[stock_industry['c_name'].isin(['房地产'])]['code']
  #stock_codes = stock_codes.pop('000527')
  
  #stock_codes = ['000001','000002','000004']
  statistic_stock_data = {}
  statistic_stock_min_len = 100
  for stock_code in stock_codes:
    print("stock:",stock_code)
    FFC.FLS.load_all_financial_one_stock(stock_code)
    FFC.FLS.load_all_processed_stock_basic_one_stock([stock_code])
    data_processed = FFC.financial_index_calc(stock_code)
    (row, colum) = data_processed.shape
    if(row<statistic_stock_min_len):
      statistic_stock_min_len = row
    statistic_stock_data[stock_code] = data_processed
    #plt.figure()
    #data_processed.plot.bar(data_processed.index)
  sum_data = statistic_stock_data[stock_codes[0]].iloc[-statistic_stock_min_len:,:]
  for stock_code in stock_codes[1:]:
    sum_data = sum_data + statistic_stock_data[stock_code].iloc[-statistic_stock_min_len:,:]
  pct_data = sum_data.pct_change(periods=4)
  pct_data.to_csv(store_path+'statistic_pct.csv');
  sum_data.to_csv(store_path+'statistic_sum.csv');
Ejemplo n.º 4
0
def classification(class_types):
    if class_types == 'industry':
        industry_classified = ts.get_industry_classified()
        industry_classified.to_csv('D:\\ts\\classification\\industry_classified.csv', encoding='gbk')
    elif class_types == 'concept':
        concept_classified = ts.get_concept_classified()
        concept_classified.to_csv('D:\\ts\\classification\\concept_classified.csv', encoding='gbk')
    elif class_types == 'area':
        area_classified = ts.get_area_classified()
        area_classified.to_csv('D:\\ts\\classification\\area_classified.csv', encoding='gbk')
    elif class_types == 'sme':
        sme_classified = ts.get_sme_classified()
        sme_classified.to_csv('D:\\ts\\classification\\sme_classified.csv', encoding='gbk')
    elif class_types == 'gem':
        gem_classified = ts.get_gem_classified()
        gem_classified.to_csv('D:\\ts\\classification\\gem_classified.csv', encoding='gbk')
    elif class_types == 'st':
        st_classified = ts.get_st_classified()
        st_classified.to_csv('D:\\ts\\classification\\st_classified.csv', encoding='gbk')
    elif class_types == 'hs300':
        hs300s = ts.get_hs300s()
        hs300s.to_csv('D:\\ts\\classification\\hs300s.csv', encoding='gbk')
    elif class_types == 'sz50':
        sz50s = ts.get_sz50s()
        sz50s.to_csv('D:\\ts\\classification\\sz50s.csv', encoding='gbk')
    elif class_types == 'zz500':
        zz500s = ts.get_zz500s()
        zz500s.to_csv('D:\\ts\\classification\\zz500s.csv', encoding='gbk')
    elif class_types == 'terminated':
        terminated = ts.get_terminated()
        terminated.to_csv('D:\\ts\\classification\\terminated.csv', encoding='gbk')
    elif class_types == 'suspended':
        suspended = ts.get_suspended()
        suspended.to_csv('D:\\ts\\classification\\suspended.csv', encoding='gbk')
Ejemplo n.º 5
0
def mk_list():
    sz50 = tushare.get_sz50s()
    hs300 = tushare.get_hs300s()
    
    y = datetime.datetime.now().year
    m = datetime.datetime.now().month
    d = datetime.datetime.now().day
    path ='StockCodeList\\' + str(y) + '_' + str(m) + '_' + str(d) #本地日期作为目录名
    isExists=os.path.exists(path)
   
    if not isExists: #如果该目录不存在,创建目录并保存数据
        os.makedirs(path) 
        
    stocks = sz50,hs300
    for i in stocks:
        stock_list = []
        #print(i)
        for j in i.code:
            if (j[0] == '0') or (j[0] == '3'):
                j = 'SZ' + j
            elif j[0] == '6':
                j = 'SH' + j
            stock_list.append(j)
        #保存当天获取的sz50证券池代码用于核对
        fss = path +'\\' + 'list' + str(len(i.code)) + '.txt'
        f = open(fss,'w')
        for j in stock_list:
            f.write(j)
            f.write('\n')
        f.close()
Ejemplo n.º 6
0
def classify_info_to_sql():
    create_classify_table()    
    
    a = ts.get_industry_classified()
    a.columns = ['code', 'name', 'industry']
    b = ts.get_area_classified()
    c = ts.get_sz50s()
    c = c.iloc[:,1::]
    c['sz50'] = '1'
    d = ts.get_hs300s()
    d = d.iloc[:,1::]
    d.columns = ['code','name','hs300_weight']
    e = ts.get_zz500s()
    e = e.iloc[:,1::]
    e.columns = ['code','name','zz500_weight']
    result = pd.merge(a, b, how='left', on=None, left_on=None, right_on=None,
             left_index=False, right_index=False, sort=True,
             suffixes=('_x', '_y'), copy=True, indicator=False)
    result = pd.merge(result, c, how='left', on=None, left_on=None, right_on=None,
             left_index=False, right_index=False, sort=True,
             suffixes=('_x', '_y'), copy=True, indicator=False)
    result = pd.merge(result, d, how='left', on=None, left_on=None, right_on=None,
             left_index=False, right_index=False, sort=True,
             suffixes=('_x', '_y'), copy=True, indicator=False)
    result = pd.merge(result, e, how='left', on=None, left_on=None, right_on=None,
             left_index=False, right_index=False, sort=True,
             suffixes=('_x', '_y'), copy=True, indicator=False)
    df_to_mysql('anack_classify',result)
Ejemplo n.º 7
0
 def __get_code_list__(self):
     if self.data_source == 'zz500':
         return [i for i in ts.get_zz500s()['code']]
     elif self.data_source == 'sz50':
         return [i for i in ts.get_sz50s()['code']]
     elif self.data_source == 'hs300':
         return [i for i in ts.get_hs300s()['code']]
Ejemplo n.º 8
0
    def refresh_stock_list(self):
        engine = self.__db.get_engine()

        logging.info('fetching stock_basics')
        df = ts.get_stock_basics()
        df.to_sql('stock_basics', engine, if_exists='replace', index=True,
                  dtype={'code': String(10)})

        logging.info('fetching class_list_gem')
        gem = ts.get_gem_classified()
        gem.to_sql('class_list_gem', engine, if_exists='replace', index=True,
                   dtype={'code': String(10)})

        logging.info('fetching class_list_hs300')
        hs300 = ts.get_hs300s()
        hs300.to_sql('class_list_hs300', engine, if_exists='replace', index=True,
                     dtype={'code': String(10)})

        logging.info('fetching class_list_sz50')
        sz50 = ts.get_sz50s()
        sz50.to_sql('class_list_sz50', engine, if_exists='replace', index=True,
                    dtype={'code': String(10)})

        logging.info('fetching class_list_zz500')
        zz500 = ts.get_zz500s()
        zz500.to_sql('class_list_zz500', engine, if_exists='replace', index=True,
                     dtype={'code': String(10)})

        self.__db.update_log_time('stock_list_fetch_time')
Ejemplo n.º 9
0
def get_codes(num):
    df = ts.get_sz50s()["code"]
    codes = df.values
    np.random.shuffle(codes)
    codes = codes[0:num]
    codes = [cc + ".SZ" if cc[0] == '0' else cc + ".SH" for cc in codes]
    return list(codes)
Ejemplo n.º 10
0
def get_sz50s():
    try:
        df = ts.get_sz50s();
        engine = create_engine('mysql://*****:*****@127.0.0.1/stock?charset=utf8')
        # df.insert(0,'code','600848')
        df.to_sql('sz50s', engine, if_exists='append')
    except Exception, e:
        e.message
Ejemplo n.º 11
0
 def getZZ50(self):
     print("...reading ZZ50 ...")
     df1 = ts.get_sz50s()
     writer = pd.ExcelWriter(ZZ50)
     df = df1.sort_values(by=['code'])
     df.to_excel(writer, sheet_name='ZZ50')
     writer.save()
     print("...saved ZZ50 ...")
Ejemplo n.º 12
0
Archivo: basic.py Proyecto: lssbq/mirai
def __get_sh50() -> pd.DataFrame:
    """获取 上证50 成分股, 最新日期"""
    try:
        return ts.get_sz50s().reindex(['code', 'name', 'date'], axis=1)
    except Exception as err:
        log.error("Could not fetch SH50 data")
        log.error(err)
        raise err
Ejemplo n.º 13
0
def zw_stk_down_50():
    #上证50成份股,上证规模大、流动性好的50只股票,优质大盘企业
    #上证50,指数代码000016
    rss = "d:\\tmp\\"
    fss = rss + 'stk_sz50.csv'
    print(fss)
    dat = ts.get_sz50s()
    dat.to_csv(fss, index=False, encoding='gbk')
Ejemplo n.º 14
0
def is_in_sz50():
    codes = get_codes(ts.get_sz50s())

    def _aux(stock):
        """Stock in SZ50"""
        return stock.code in codes

    return _aux
Ejemplo n.º 15
0
def getSz50():
    '''
    获取上证50成份股
    返回值说明:
    code:股票代码
    name:股票名称
    '''
    return ts.get_sz50s()
Ejemplo n.º 16
0
def get_stockcodes(stocktype):  #stocktype 股票类型:sh 上证 sz 深证 cyb 创业板
    if(stocktype=='cyb'): #创业板
        codes=ts.get_gem_classified().code.tolist()
    elif (stocktype=='sz'): #深证
        codes=ts.get_sme_classified().code.tolist()
    elif(stocktype=='sh'): #上证
        codes=ts.get_sz50s().code.tolist() #目前只调用了上证50
    return codes #返回的股票代码列表
Ejemplo n.º 17
0
def get_sz50s():
    try:
        logger.info('get sz50s data starting...')
        df = ts.get_sz50s()
        logger.info('get sz50s data end...')
    except:
        logger.exception('some errors between get sz50s data end...')
    return df
Ejemplo n.º 18
0
    def test_strategy(self):
        data = ts.get_sz50s()
        code_set = code_muning(data)
        cal_pair_stocks(code_set)

    # def test_cal_p_value(self):
    #     pair_set = set()
    #     pair_set.add(('600519', '000858'))
    #     cal_pair_stocks(pair_set)
Ejemplo n.º 19
0
 def get_chengfenggu(self, writeable=False):
     s50 = ts.get_sz50s()
     if writeable == True:
         s50.to_excel('sz50.xls')
     list_s50 = s50['code'].values.tolist()
     # print(type(s50))
     # print(type(list_s50))
     # 返回list类型
     return list_s50
Ejemplo n.º 20
0
 def get_chengfenggu(self,writeable=False):
     s50=ts.get_sz50s()
     if writeable==True:
         s50.to_excel('sz50.xls')
     list_s50=s50['code'].values.tolist()
     #print type(s50)
     #print type(list_s50)
     #返回list类型
     return list_s50
Ejemplo n.º 21
0
def list_component_stock(component_name):
    if 'hs300' == component_name:
        return ts.get_hs300s()

    if 'zz500' == component_name:
        return ts.get_zz500s()

    if 'sz50' == component_name:
        return ts.get_sz50s()
Ejemplo n.º 22
0
 def get_sz50s_classified(self):
     """
     'sz50s',##获取上证50成份股
     """
     sz50s = ts.get_sz50s()
     sz50s['sz50sName'] = 1
     sz50s = sz50s[['code','sz50sName']]
     
     sz50s.columns = ['code','sz50sName']
     self.data = pd.merge(self.data,sz50s,on=['code'],how='outer')    
Ejemplo n.º 23
0
def test():
    ts.get_sz50s()
    ts.get_hs300s()
    ts.get_zz500s()
    ts.realtime_boxoffice()
    ts.get_latest_news()
    ts.get_notices(tk)
    ts.guba_sina()
    ts.get_cpi()
    ts.get_ppi()
    ts.get_stock_basics()
    ts.get_concept_classified()
    ts.get_money_supply()
    ts.get_gold_and_foreign_reserves()
    ts.top_list()  #每日龙虎榜列表
    ts.cap_tops()  #个股上榜统计
    ts.broker_tops()  #营业部上榜统计
    ts.inst_tops()  # 获取机构席位追踪统计数据
    ts.inst_detail()
Ejemplo n.º 24
0
def get_sz50s():
    df = ts.get_sz50s()
    if df is None:
        logging.info("get sz50 return none.")
        return {}
    records_dict = df.to_dict(orient='records')
    ret = {}
    for data in records_dict:
        ret[data['code']] = data['name']
    return ret
Ejemplo n.º 25
0
def sz50_cluster():
    instruments = ts.get_sz50s()

    instruments.set_index('code', inplace=True)

    #clusters = compute_cluster(instruments, config.RESULT_PATH, config.DAY_FILE_PATH, 'sz50')
    #clusters = cluster_by_ap(instruments, config.RESULT_PATH, config.DAY_FILE_PATH, 'sz50')
    clusters = cluster_by_ap_new(instruments, config.INDEX_FILE_PATH, '000016',
                                 config.DAY_FILE_PATH)

    write_to_db(clusters=clusters, section='sz50')
Ejemplo n.º 26
0
async def main():
    # In[0]: 输入
    ori_df = read()
    # In[1]: 沪深 300
    result = pd.DataFrame([
        await transaction(ori_df, ts.get_hs300s(), 'IF', 300), await
        transaction(ori_df, ts.get_sz50s(), 'IH',
                    300), await transaction(ori_df, ts.get_zz500s(), 'IC', 200)
    ])
    result.columns = ['代码', '现货总市值', '合约市值', '合约数']
    print(result)
Ejemplo n.º 27
0
def getstockclassifieddata():
    mylogger = getmylogger()
    print("start")
    scdict = {
        'industry': '行业分类',
        'concept': '概念分类',
        'area': '地域分类',
        'sme': '中小板分类',
        'gem': '创业板分类',
        'st': '风险警示板分类',
        'hs300s': '沪深300成份及权重',
        'sz50s': '上证50成份股',
        'zz500s': '中证500成份股',
        'terminated': '终止上市股票列表',
        'suspended': '暂停上市股票列表'
    }

    for sc in scdict:
        sctbname = sc
        scinfo = scdict[sctbname]
        try:
            if sc == "industry":
                df = ts.get_industry_classified()
            elif sc == "concept":
                df = ts.get_concept_classified()
            elif sc == "area":
                df = ts.get_area_classified()
            elif sc == "sme":
                df = ts.get_sme_classified()
            elif sc == "gem":
                df = ts.get_gem_classified()
            elif sc == "st":
                df = ts.get_st_classified()
            elif sc == "hs300s":
                df = ts.get_hs300s()
            elif sc == "zz500s":
                df = ts.get_zz500s()
            elif sc == "sz50s":
                df = ts.get_sz50s()
            elif sc == "terminated":
                df = ts.get_terminated()
            elif sc == "suspended":
                df = ts.get_suspended()
            else:
                mylogger.info("没有执行命令。")
            if df is not None:
                tosql(df, sctbname, "replace", scinfo, mylogger)
            else:
                mylogger.info("没有%s数据。" % scinfo)
        except Exception:
            tracelog = traceback.format_exc()
            mylogger.info("获取数据异常。")
            mylogger.info(tracelog)
Ejemplo n.º 28
0
 def storagepool(self):
     #storage zz500
     df=ts.get_zz500s()
     self.pool['zz500'].insert_many(json.loads(df.to_json(orient='records')))
     #hs300
     df=ts.get_hs300s()
     self.pool['hz300'].insert_many(json.loads(df.to_json(orient='records')))
     #zh50
     df=ts.get_sz50s()
     self.pool['sz'].insert_many(json.loads(df.to_json(orient='records')))
     #st
     df=ts.get_st_classified()
     self.pool['st'].insert_many(json.loads(df.to_json(orient='records')))
Ejemplo n.º 29
0
def load_data():
    #下载公司基本信息,包括股票代码、pe、市盈率等数据
    try:
        rs = ts.get_sz50s()
        pd.DataFrame.to_sql(rs,
                            table_name,
                            con=conn,
                            flavor='mysql',
                            if_exists='replace',
                            index=True)
    except Exception as e:
        print(e.message)
        print("公司基本分类信息数据出错")
Ejemplo n.º 30
0
    def tech_jincha(self):
        # 站上5日线
        def zs5(his):
            ma_n = pd.rolling_mean(his, 5)
            temp = his - ma_n
            # temp_s包含了前一天站上五日线的股票代码
            temp_s = list(temp[temp > 0].iloc[-1, :].dropna().index)
            return temp_s

        # 站上10日线
        def zs10(his):
            ma_n = pd.rolling_mean(his, 10)
            temp = his - ma_n
            temp_s = list(temp[temp > 0].iloc[-1, :].dropna().index)
            return temp_s

        # 金叉突破
        def jc(his):
            mas = pd.rolling_mean(his, 5)
            mal = pd.rolling_mean(his, 10)
            temp = mas - mal
            # temp_jc昨天大于0股票代码
            # temp_r前天大于0股票代码​
            temp_jc = list(temp[temp > 0].iloc[-1, :].dropna().index)
            temp_r = list(temp[temp > 0].iloc[-2, :].dropna().index)
            temp = []
            for stock in temp_jc:
                if stock not in temp_r:
                    temp.append(stock)
            return temp

        # 确定时间范围
        end_date = datetime.datetime.now().strftime('%Y-%m-%d')
        start_date = datetime.datetime.now() - datetime.timedelta(days=5)
        start_date = start_date.strftime('%Y-%m-%d')
        # 得到需要遍历的股票列表
        #base_df = ts.get_concept_classified()
        base_df = ts.get_sz50s()
        stock_list = numpy.array(base_df['code'])
        his = pd.DataFrame()
        for stock in stock_list:
            each_his = ts.get_hist_data(stock, start=start_date, end=end_date)
            his.append(each_his)
        # 求三种条件下的股票代码交集
        con1 = zs5(his)
        con2 = zs10(his)
        con3 = jc(his)
        result_stock_list = list(
            set(con1).intersection(set(con2)).intersection(set(con3)))

        return result_stock_list
Ejemplo n.º 31
0
    def update_sz50_list(cls):
        # update hs300(沪深300) list:
        tbl_sz50_list = 'sz50_list'
        # get the list from Tushare
        # TODO: API has issue
        sz50_list = ts.get_sz50s()
        print('get sz50_list data ok!')
        print(sz50_list)
        # insert list
        cls.insert_to_db_no_duplicate(sz50_list, tbl_sz50_list, cls.engine)
        print("Insert sz50_list data ok!")

        # close the engine pool
        cls.engine.dispose()
Ejemplo n.º 32
0
def getSZ50CodeList():
    df_sz50 = None
    try:
        df_sz50 = pd.read_sql_table('sz50', con=engine)
    except:
        pass
    if df_sz50 is None or df_sz50.empty:
        df_sz50 = ts.get_sz50s()
        df_sz50.to_sql('sz50',
                       con=engine,
                       if_exists='replace',
                       index=False,
                       index_label='code')
    return df_sz50['code'].tolist()
Ejemplo n.º 33
0
def save_sz50s():
    """上证50成分股"""
    logger.info('Begin get and save sz50 clssified.')
    try:
        data_df = ts.get_sz50s()
        if data_df is not None and not data_df.empty:
            data = data_df.values
            data_dicts = [{'code': row[0], 'name': row[1]} for row in data]
            Sz50.insert_many(data_dicts).execute()
            logger.info('Success get and save sz50 classified.')
        else:
            logger.warn('Empty get and save sz50 classified.')
    except Exception as e:
        logger.exception('Error get and save sz50 classified.')
Ejemplo n.º 34
0
 def list(self, stock_block_type):
     stock_block = None
     if stock_block_type == self.industry:
         stock_block = db.get(STOCK_BLOCK_INDUSTRY)
         if stock_block is None:
             stock_block = ts.get_industry_classified()
             db.save(STOCK_BLOCK_INDUSTRY, stock_block)
     elif stock_block_type == self.concept:
         stock_block = db.get(STOCK_BLOCK_CONCEPT)
         if stock_block is None:
             stock_block = ts.get_concept_classified()
             db.save(STOCK_BLOCK_CONCEPT, stock_block)
     elif stock_block_type == self.area:
         stock_block = db.get(STOCK_BLOCK_AREA)
         if stock_block is None:
             stock_block = ts.get_area_classified()
             db.save(STOCK_BLOCK_AREA, stock_block)
     elif stock_block_type == self.sme:
         stock_block = db.get(STOCK_BLOCK_SME)
         if stock_block is None:
             stock_block = ts.get_sme_classified()
             db.save(STOCK_BLOCK_SME, stock_block)
     elif stock_block_type == self.gem:
         stock_block = db.get(STOCK_BLOCK_GEM)
         if stock_block is None:
             stock_block = ts.get_gem_classified()
             db.save(STOCK_BLOCK_GEM, stock_block)
     elif stock_block_type == self.st:
         stock_block = db.get(STOCK_BLOCK_ST)
         if stock_block is None:
             stock_block = ts.get_st_classified()
             db.save(STOCK_BLOCK_ST, stock_block)
     elif stock_block_type == self.hs300s:
         stock_block = db.get(STOCK_BLOCK_HS300S)
         if stock_block is None:
             stock_block = ts.get_hs300s()
             db.save(STOCK_BLOCK_HS300S, stock_block)
     elif stock_block_type == self.sz50s:
         stock_block = db.get(STOCK_BLOCK_SZ50S)
         if stock_block is None:
             stock_block = ts.get_sz50s()
             db.save(STOCK_BLOCK_SZ50S, stock_block)
     elif stock_block_type == self.zz500s:
         stock_block = db.get(STOCK_BLOCK_ZZ500S)
         if stock_block is None:
             stock_block = ts.get_zz500s()
             db.save(STOCK_BLOCK_ZZ500S, stock_block)
     else:
         return None
     return stock_block
Ejemplo n.º 35
0
 def preload():
     stock_block = ts.get_industry_classified()
     db.save(STOCK_BLOCK_INDUSTRY, stock_block)
     stock_block = ts.get_concept_classified()
     db.save(STOCK_BLOCK_CONCEPT, stock_block)
     stock_block = ts.get_area_classified()
     db.save(STOCK_BLOCK_AREA, stock_block)
     stock_block = ts.get_sme_classified()
     db.save(STOCK_BLOCK_SME, stock_block)
     stock_block = ts.get_gem_classified()
     db.save(STOCK_BLOCK_GEM, stock_block)
     stock_block = ts.get_st_classified()
     db.save(STOCK_BLOCK_ST, stock_block)
     stock_block = ts.get_hs300s()
     db.save(STOCK_BLOCK_HS300S, stock_block)
     stock_block = ts.get_sz50s()
     db.save(STOCK_BLOCK_SZ50S, stock_block)
     stock_block = ts.get_zz500s()
     db.save(STOCK_BLOCK_ZZ500S, stock_block)
Ejemplo n.º 36
0
def syncSZ50S():
    sz50s_df = ts.get_sz50s()
    sz50s_df.to_csv(config.SZ50_CodePath, encoding="utf-8")
    saveDataFileByCode(sz50s_df)
    print("sync and save SZ50 done!")
Ejemplo n.º 37
0
# Growth Enterprise Market
GEM = ts.get_gem_classified()
GEM.to_csv('./ASHR/DATA/GEM.csv', index = False)

# ST Enterprise
ST = ts.get_st_classified()
ST.to_csv('./ASHR/DATA/ST.csv', index = False)

ts.get_h_data()

# HS 300
HS300S = ts.get_hs300s()
HS300S.to_csv('./ASHR/DATA/HS300S.csv', index = False)

# SZ 50
SZ50S = ts.get_sz50s()
SZ50S.to_csv('./ASHR/DATA/SZ50S.csv', index = False)

# ZZ 500
ZZ500S = ts.get_zz500s()
ZZ500S.to_csv('./ASHR/DATA/ZZ500S.csv', index = False)

#################
# Fund Holdings #
#################

# TODO Data is available quarterly
FundHolding = ts.fund_holdings(CURRENT.year, np.floor((CURRENT.month+2)/3))


####################
Ejemplo n.º 38
0
print("#0", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23')
print("#1", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='W')
print("#2", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='M')
print("#3", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='5')
print("#4", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='15')
print("#5", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='30')
print("#6", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='60')
print("#7", df)

df = ts.get_index()
printD("ts.get_index", df)

df = ts.get_suspended()
printD("ts.get_suspended()", df)

df = ts.get_sz50s()
printD("ts.get_sz50s", df)

df = ts.get_terminated()
printD("ts.get_terminated", df)

df = ts.get_zz500s()
printD("ts.get_zz500s", df)
Ejemplo n.º 39
0
def get_sz50s_info(file_path):
    sz50s_info = ts.get_sz50s()
    sz50s_info.to_csv(file_path, encoding='utf-8')
    print '\ndownload sz50s info finished\n'
Ejemplo n.º 40
0
Created on 2015年6月4日

@author: Administrator
'''
import tushare as ts
# 行业分类
ts.get_industry_classified()

# 概念分类
ts.get_concept_classified()

# 地域分类
ts.get_area_classified()

# 获取沪深300当前成份股及所占权重
ts.get_hs300s()

# 获取中小板股票数据,即查找所有002开头的股票
ts.get_sme_classified()

# 获取创业板股票数据,即查找所有300开头的股票
ts.get_gem_classified()

# 获取风险警示板股票数据,即查找所有st股票
ts.get_st_classified()

# 获取上证50成份股
ts.get_sz50s()

# 获取中证500成份股
ts.get_zz500s()
Ejemplo n.º 41
0
def get_sz50s_history():
    szs = ts.get_sz50s()
    return get_data_by_column(szs)
Ejemplo n.º 42
0
def load_company_industry_info(): 
    #下载加载行业分类数据
    try:
        rs=ts.get_industry_classified()
        sql.write_frame(rs, "company_industry_classified", con=conn_company_classified , flavor='mysql', if_exists='replace',index=True)
        print("下载公司行业分类信息ok")
    except:
        print("下载公司行业分类信息出错")
    #下载加载概念分类数据
    try:
        rs=ts.get_concept_classified()
        sql.write_frame(rs, "company_concept_classified", con=conn_company_classified , flavor='mysql', if_exists='replace',index=True)
        print("载公司概念分类信息ok")
    except:
        print("下载公司概念分类信息出错")
    #下载加载地域分类数据
    try:
        rs=ts.get_area_classified()
        sql.write_frame(rs, "company_area_classified", con=conn_company_classified , flavor='mysql', if_exists='replace',index=True)
        print("下载公司区域分类信息ok")
    except:
        print("下载公司区域分类信息出错")
    #下载加载中小板分类数据
    try:
        rs=ts.get_sme_classified()
        sql.write_frame(rs, "company_sme_classified", con=conn_company_classified , flavor='mysql', if_exists='replace',index=True)
        print("下载中小板分类数据ok")
    except:
        print("下载中小板分类数据出错")
    #下载加载创业板分类数据
    try:
        rs=ts.get_gem_classified()
        sql.write_frame(rs, "company_gem_classified", con=conn_company_classified , flavor='mysql', if_exists='replace',index=True)
        print("下载创业板分类数据ok")
    except:
        print("下载创业板分类数据出错")
    #下载加载st板分类数据
    try:
        rs=ts.get_st_classified()
        sql.write_frame(rs, "company_st_classified", con=conn_company_classified , flavor='mysql', if_exists='replace',index=True)
        print("下载st板分类数据ok")
    except:
        print("下载st板分类数据出错")
    #下载加载沪深300板分类数据
    try:
        rs=ts.get_hs300s()
        sql.write_frame(rs, "company_hs300_classified", con=conn_company_classified , flavor='mysql', if_exists='replace',index=True)
        print("下载加载沪深300板分类数据ok")
    except:
        print("下载加载沪深300板分类数据出错")
    #下载加载上证50板分类数据
    try:
        rs=ts.get_sz50s()
        sql.write_frame(rs, "company_sz50_classified", con=conn_company_classified , flavor='mysql', if_exists='replace',index=True)
        print("下载加载上证50板分类数据ok")
    except:
        print("下载加载上证50板分类数据出错")
    #下载加载中证500板分类数据
    try:
        rs=ts.get_zz500s()
        sql.write_frame(rs, "company_zz500_classified", con=conn_company_classified , flavor='mysql', if_exists='replace',index=True)
        print("下载加载中证500板分类数据ok")
    except:
        print("下载加载中证500板分类数据出错")
    #下载加载终止上市分类数据
    try:
        rs=ts.get_terminated()
        sql.write_frame(rs, "company_terminated_classified", con=conn_company_classified , flavor='mysql', if_exists='replace',index=True)
        print("下载加载终止上市分类数据ok")
    except:
        print("下载加载终止上市分类数据出错")
    #下载加载暂停上市分类数据
    try:
        rs=ts.get_suspended()
        sql.write_frame(rs, "company_suspended_classified", con=conn_company_classified , flavor='mysql', if_exists='replace',index=True)
        print("下载加载暂停上市分类数据ok")
    except:
        print("下载加载暂停上市分类数据出错")
Ejemplo n.º 43
0
 def get_stock_chengfeng(self):
     df = ts.get_sz50s()
     # print(df)
     terminal_stock = ts.get_terminated()
     print(terminal_stock)
Ejemplo n.º 44
0
time.sleep(1)
# 创业版
news = ts.get_gem_classified()

time.sleep(1)
# st版块
sts = ts.get_st_classified()

time.sleep(1)
# 沪深300
hss = ts.get_hs300s()

time.sleep(1)
# 上证50
szs = ts.get_sz50s()

time.sleep(1)
# 中证500
zzs = ts.get_zz500s()

time.sleep(1)
# 终止上市
tss = ts.get_terminated()

time.sleep(1)
# 暂停上市
ss = ts.get_terminated()

time.sleep(1)
# 股本