class SNService(object): K_NET_BASE = "http://stock.finance.sina.com.cn/usstock/api/json_v2.php/US_MinKService.getDailyK?" \ "symbol=%s&___qn=3n" TIME_OUT = (10, 60) def __init__(self): self.storeservice = MysqlService() def get_history_data(self,code,start, days): url = SNService.K_NET_BASE % code resp = requests.get(url,timeout=SNService.TIME_OUT) kl_pd = SNUSParser(code,start,resp.json()).df if kl_pd is not None and len(kl_pd) > 0: table = 'ft_kline' tindex = self.storeservice.find_tindex(code, 'hk') if tindex != -1: table += ('_' + str(tindex)) #table = 'ft_kline_1_1' lastdate = kl_pd['time_key'][len(kl_pd)-1] self.storeservice.insert_many(table, kl_pd, 'append') print(lastdate) return lastdate else: return None
def main(): #192.168.1.101 数据库 storeservice2 = MysqlService(2) #init_history_data_table(storeservice) storeservice = MysqlService() migration_table_and_data(storeservice)
def catch_all_entry_urls(): storeservice = MysqlService() mongodbutil = MongodbUtil(AppConfig.mongodb_ip, AppConfig.mongodb_port, AppConfig.mongodb_collection) sinanewshistory = SinanewsService(mongodbutil) ret_arr = storeservice.find_all_stockcodes_exclude_nodata() thread_name = 'catch all stock entry url' once_global_task(thread_name, ret_arr, storeservice, sinanewshistory)
def main(): #192.168.1.101 数据库 storeservice2 = MysqlService(2) #10.0.0.1 storeservice = MysqlService() init_history_table(storeservice, storeservice2)
class TXService(object): K_NET_BASE = "http://ifzq.gtimg.cn/appstock/app/%sfqkline/get?p=1¶m=%s,day,,,%d," \ "qfq&_appName=android&_dev=%s&_devId=%s&_mid=%s&_md5mid=%s&_appver=4.2.2&_ifChId=303&_screenW=%d" \ "&_screenH=%d&_osVer=%s&_uin=10000&_wxuin=20000&__random_suffix=%d" K_DEV_MODE_LIST = [ "A0001", "OPPOR9", "OPPOR9", "VIVOX5", "VIVOX6", "VIVOX6PLUS", "VIVOX9", "VIVOX9PLUS" ] # 预先设置模拟手机请求的os version K_OS_VERSION_LIST = ["4.3", "4.2.2", "4.4.2", "5.1.1"] def __init__(self): self.storeservice = MysqlService() def get_history_data(self, code, days): dev_mod = random_from_list(TXService.K_DEV_MODE_LIST) os_ver = random_from_list(TXService.K_OS_VERSION_LIST) width = 1080 height = 1920 market = 'us' sub_market = '.oq' symbol = 'TSLA' cuid = create_random_with_num_low(40) cuid_md5 = md5_from_binary(cuid) random_suffix = create_random_with_num(5) url = TXService.K_NET_BASE % ( \ market, market+symbol+sub_market, days, \ dev_mod, cuid, cuid, cuid_md5, width, height, os_ver, int(random_suffix, 10)) resp = requests.get(url) kl_pd = TXParser('us', code, '.oq', resp.json()).df if kl_pd is not None and len(kl_pd) > 0: table = 'ft4_kline' tindex = self.storeservice.find_tindex(code, 'hk') if tindex != -1: table += ('_' + str(tindex)) table = 'ft_kline_1_1' lastdate = kl_pd['time_key'][len(kl_pd) - 1] self.storeservice.insert_many(table, kl_pd, 'append') print(lastdate) return lastdate return None
def counter_statistics(): storeservice = MysqlService() index = 0 to_table = 234 try: for index in range(1, 250, 1): logger.info('addressing {0} ....'.format(index)) # step 1: fetch one code sql = 'select count(code) from ft_1M_{0}'.format(index) result = storeservice.executeSql(sql) print(result.cursor._result.rows[0]) except Exception as err: logger.info(err)
def scheduled_job(): logging.info('This job is run every weekday at 5pm') crawler = Crawler('##') storeservice = MysqlService() pos = 2331 while pos < 7101: print(pos) url = 'http://finviz.com/screener.ashx?v=152&r=' + str( pos ) + '&c=0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70' crawler.get_page(url) time.sleep(2 * random.random()) pos += 21 jsonArray = crawler.toJsons() table = 'fiv2_stat' df = pd.DataFrame(jsonArray, columns=crawler.propertiesList) df = df.replace('-', 0) df['P/E'] = df['P/E'].astype(float) df['Fwd P/E'] = df['Fwd P/E'].astype(float) df['PEG'] = df['PEG'].astype(float) df['P/S'] = df['P/S'].astype(float) df['P/B'] = df['P/B'].astype(float) df['P/C'] = df['P/C'].astype(float) df['P/FCF'] = df['P/FCF'].astype(float) df['EPS'] = df['EPS'].astype(float) df['Short Ratio'] = df['Short Ratio'].astype(float) df['CurrR'] = df['CurrR'].astype(float) df['Quick R'] = df['Quick R'].astype(float) df['LTDebt/Eq'] = df['LTDebt/Eq'].astype(float) df['Debt/Eq'] = df['Debt/Eq'].astype(float) df['Beta'] = df['Beta'].astype(float) df['ATR'] = df['ATR'].astype(float) df['RSI'] = df['RSI'].astype(float) df['Recom'] = df['Recom'].astype(float) df['Rel Volume'] = df['Rel Volume'].astype(float) df['Price'] = df['Price'].astype(float) df['Target Price'] = df['Target Price'].astype(float) try: storeservice.insert_many(table, df) except IOError as err: logging.error(err) else: pass
def main(): storeservice = MysqlService() kline_tables_number = 12 kline_5M_tables_number = 35 kline_1M_tables_number = 171 for index in range(1,kline_tables_number,1): sql = 'INSERT INTO sys_sharding(code, dtype, tindex) SELECT code, \'hk\' as dtype, {0} as tindex from (SELECT DISTINCT(code) FROM ft_kline_{1}) as tmp1'.format(index,index) storeservice.executeSql(sql) for index in range(1,kline_5M_tables_number,1): sql = 'INSERT INTO sys_sharding(code, dtype, tindex) SELECT code, \'hk_5m\' as dtype, {0} as tindex from (SELECT DISTINCT(code) FROM ft_5M_{1}) as tmp1'.format(index,index) storeservice.executeSql(sql) for index in range(1,kline_1M_tables_number,1): sql = 'INSERT INTO sys_sharding(code, dtype, tindex) SELECT code, \'hk_1m\' as dtype, {0} as tindex from (SELECT DISTINCT(code) FROM ft_1M_{1}) as tmp1'.format(index,index) storeservice.executeSql(sql)
def __init__(self): ''' QE Engine Init ''' config = AppConfig.get_config() self.config = config quote_ctx = ft.OpenQuoteContext(config.get('ftserver', 'host'), int(config.get('ftserver', 'port'))) self.quote_ctx = quote_ctx self.tradehk_ctx = ft.OpenHKTradeContext( config.get('ftserver', 'host'), int(config.get('ftserver', 'port'))) self.tradeus_ctx = ft.OpenUSTradeContext( config.get('ftserver', 'host'), int(config.get('ftserver', 'port'))) self.decipher = config.get('ftserver', 'decipher') total = config.get('quota', 'total') kline = config.get('quota', 'kline') tiker = config.get('quota', 'ticker') quote = config.get('quota', 'quote') order_book = config.get('quota', 'order_book') rt_data = config.get('quota', 'rt_data') broker = config.get('quota', 'broker') quote_ctx.start() self.lf = LF(quote_ctx) self.sub = Subscribe(quote_ctx, total, kline, tiker, quote, order_book, rt_data, broker) self.hf = HF(quote_ctx, self.sub) self.hktrade = Trade(self.tradehk_ctx) self.hktrade.unlock_trade(self.decipher) self.ustrade = Trade(self.tradeus_ctx) self.ustrade.unlock_trade(self.decipher) self.queryhistory = QueryHistory(quote_ctx) self.mysqlService = MysqlService()
def main(): storeservice = MysqlService() schemaArr = [ # { # "table": "ft_stat_week_probability", # "dtype": { # "id":sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "up_count": sa.types.SMALLINT, # "down_count": sa.types.SMALLINT, # "up_probability": sa.types.Float, # "down_probability": sa.types.Float, # "week_of_day": sa.types.SMALLINT, # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`)', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`week_of_day`);', # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';', # ] # }, # { # "table": "ft_stock_basicinfo", # "dtype": { # "id":sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "name": sa.types.NVARCHAR(200), # "lot_size": sa.types.BIGINT, # "stock_type": sa.types.NVARCHAR(30), # "stock_child_type": sa.types.NVARCHAR(30), # "stock_owner": sa.types.NVARCHAR(30), # "listing_date": sa.types.DATE, # "stock_id": sa.types.BIGINT # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`)', # #code not unique, # 'ALTER TABLE `{0}` ADD KEY (`name`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`stock_type`);', # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';', # 'ALTER TABLE `{0}` MODIFY COLUMN lot_size BIGINT COMMENT \'每手数量\';' # 'ALTER TABLE `{0}` MODIFY COLUMN stock_type VARCHAR(30) COMMENT \'股票类型,参见SecurityType\';' # 'ALTER TABLE `{0}` MODIFY COLUMN stock_child_type VARCHAR(30) COMMENT \'涡轮子类型,参见WrtType\';' # 'ALTER TABLE `{0}` MODIFY COLUMN stock_owner VARCHAR(30) COMMENT \'正股代码\';' # 'ALTER TABLE `{0}` MODIFY COLUMN listing_date DATE COMMENT \'上市时间\';' # 'ALTER TABLE `{0}` MODIFY COLUMN stock_id BIGINT COMMENT \'股票id\';' # ] # }, # { # "table": "ft_history_kline", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "time_key": sa.types.DATETIME, # "open": sa.types.FLOAT, # "close": sa.types.FLOAT, # "high": sa.types.FLOAT, # "low": sa.types.FLOAT, # "pe_ratio": sa.types.FLOAT, # "turnover_rate": sa.types.FLOAT, # "volume": sa.types.BIGINT, # "turnover": sa.types.FLOAT, # "change_rate": sa.types.FLOAT, # "last_close": sa.types.FLOAT # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`time_key`);' # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';', # 'ALTER TABLE `{0}` MODIFY COLUMN pe_ratio FLOAT COMMENT \'市盈率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover_rate FLOAT COMMENT \'换手率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN volume BIGINT COMMENT \'成交量\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover FLOAT COMMENT \'成交额\';' # 'ALTER TABLE `{0}` MODIFY COLUMN change_rate FLOAT COMMENT \'涨跌幅\';' # 'ALTER TABLE `{0}` MODIFY COLUMN last_close FLOAT COMMENT \'昨收价\';' # #'ALTER TABLE `{0}` ENGINE=MRG_MyISAM UNION=(ft_history_kline_1,ft_history_kline_2,ft_history_kline_3,ft_history_kline_4,ft_history_kline_5,ft_history_kline_6,ft_history_kline_7,ft_history_kline_8,ft_history_kline_9,ft_history_kline_10,ft_history_kline_11) INSERT_METHOD=LAST;' # 'ALTER TABLE `{0}` ENGINE=MyISAM;' # ] # }, # { # "table": "ft_history_kline_K_5M", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "time_key": sa.types.DATETIME, # "open": sa.types.FLOAT, # "close": sa.types.FLOAT, # "high": sa.types.FLOAT, # "low": sa.types.FLOAT, # "pe_ratio": sa.types.FLOAT, # "turnover_rate": sa.types.FLOAT, # "volume": sa.types.BIGINT, # "turnover": sa.types.FLOAT, # "change_rate": sa.types.FLOAT, # "last_close": sa.types.FLOAT # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`time_key`);' # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';', # 'ALTER TABLE `{0}` MODIFY COLUMN pe_ratio FLOAT COMMENT \'市盈率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover_rate FLOAT COMMENT \'换手率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN volume BIGINT COMMENT \'成交量\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover FLOAT COMMENT \'成交额\';' # 'ALTER TABLE `{0}` MODIFY COLUMN change_rate FLOAT COMMENT \'涨跌幅\';' # 'ALTER TABLE `{0}` MODIFY COLUMN last_close FLOAT COMMENT \'昨收价\';' # #'ALTER TABLE `{0}` ENGINE=MRG_MyISAM UNION=(ft_history_kline_K_5M_1,ft_history_kline_K_5M_2,ft_history_kline_K_5M_3,ft_history_kline_K_5M_4,ft_history_kline_K_5M_5,ft_history_kline_K_5M_6,ft_history_kline_K_5M_7,ft_history_kline_K_5M_8,ft_history_kline_K_5M_9,ft_history_kline_K_5M_10,ft_history_kline_K_5M_11) INSERT_METHOD=LAST;' # 'ALTER TABLE `{0}` ENGINE=MyISAM;' # ] # }, # { # "table": "ft_history_kline_MyISAM", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "time_key": sa.types.DATETIME, # "open": sa.types.FLOAT, # "close": sa.types.FLOAT, # "high": sa.types.FLOAT, # "low": sa.types.FLOAT, # "pe_ratio": sa.types.FLOAT, # "turnover_rate": sa.types.FLOAT, # "volume": sa.types.BIGINT, # "turnover": sa.types.FLOAT, # "change_rate": sa.types.FLOAT, # "last_close": sa.types.FLOAT # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`time_key`);' # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';', # 'ALTER TABLE `{0}` MODIFY COLUMN pe_ratio FLOAT COMMENT \'市盈率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover_rate FLOAT COMMENT \'换手率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN volume BIGINT COMMENT \'成交量\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover FLOAT COMMENT \'成交额\';' # 'ALTER TABLE `{0}` MODIFY COLUMN change_rate FLOAT COMMENT \'涨跌幅\';' # 'ALTER TABLE `{0}` MODIFY COLUMN last_close FLOAT COMMENT \'昨收价\';' # 'ALTER TABLE `{0}` ENGINE=MyISAM;' # ] # }, # { # "table": "ft_history_kline_K_5M_MyISAM", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "time_key": sa.types.DATETIME, # "open": sa.types.FLOAT, # "close": sa.types.FLOAT, # "high": sa.types.FLOAT, # "low": sa.types.FLOAT, # "pe_ratio": sa.types.FLOAT, # "turnover_rate": sa.types.FLOAT, # "volume": sa.types.BIGINT, # "turnover": sa.types.FLOAT, # "change_rate": sa.types.FLOAT, # "last_close": sa.types.FLOAT # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`time_key`);' # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';', # 'ALTER TABLE `{0}` MODIFY COLUMN pe_ratio FLOAT COMMENT \'市盈率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover_rate FLOAT COMMENT \'换手率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN volume BIGINT COMMENT \'成交量\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover FLOAT COMMENT \'成交额\';' # 'ALTER TABLE `{0}` MODIFY COLUMN change_rate FLOAT COMMENT \'涨跌幅\';' # 'ALTER TABLE `{0}` MODIFY COLUMN last_close FLOAT COMMENT \'昨收价\';' # 'ALTER TABLE `{0}` ENGINE=MyISAM;' # ] # }, # { # "table": "ft_broker", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "bid_broker_id": sa.types.BIGINT, # "bid_broker_name": sa.types.NVARCHAR(100), # "bid_broker_pos": sa.types.BIGINT, # "ask_broker_id": sa.types.BIGINT, # "ask_broker_name": sa.types.NVARCHAR(100), # "ask_broker_pos": sa.types.BIGINT # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';' # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # ] # }, # { # "table": "ft_rtdata", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "time": sa.types.DATETIME, # "is_blank": sa.types.INT, # "opened_mins": sa.types.INT, # "cur_price": sa.types.FLOAT, # "last_close": sa.types.FLOAT, # "avg_price": sa.types.FLOAT, # "turnover": sa.types.FLOAT, # "volume": sa.types.FLOAT # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`time`);' # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';' # 'ALTER TABLE `{0}` MODIFY COLUMN opened_mins INT COMMENT \'零点到当前多少分钟\';' # 'ALTER TABLE `{0}` MODIFY COLUMN cur_price FLOAT COMMENT \'当前价格\';' # 'ALTER TABLE `{0}` MODIFY COLUMN last_close FLOAT COMMENT \'昨天收盘的价格\';' # 'ALTER TABLE `{0}` MODIFY COLUMN avg_price FLOAT COMMENT \'平均价格\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover FLOAT COMMENT \'成交额\';' # 'ALTER TABLE `{0}` MODIFY COLUMN volume FLOAT COMMENT \'成交量\';' # ] # }, # { # "table": "ft_stockquote", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "data_date": sa.types.DATE, # "data_time": sa.types.TIME, # "last_price": sa.types.FLOAT, # "open_price": sa.types.FLOAT, # "high_price": sa.types.FLOAT, # "low_price": sa.types.FLOAT, # "prev_close_price": sa.types.FLOAT, # "volume": sa.types.BIGINT, # "turnover": sa.types.FLOAT, # "turnover_rate": sa.types.FLOAT, # "amplitude": sa.types.INT, # "suspension": sa.types.BOOLEAN, # "listing_date": sa.types.DATE, # "price_spread": sa.types.FLOAT, # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`data_date`);' # 'ALTER TABLE `{0}` ADD INDEX (`data_time`);' # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover FLOAT COMMENT \'成交金额\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover_rate FLOAT COMMENT \'换手率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN amplitude INT COMMENT \'振幅\';' # 'ALTER TABLE `{0}` MODIFY COLUMN suspension BOOL COMMENT \'是否停牌(True表示停牌)\';' # 'ALTER TABLE `{0}` MODIFY COLUMN listing_date DATE COMMENT \'上市日期\';' # 'ALTER TABLE `{0}` MODIFY COLUMN price_spread FLOAT COMMENT \'当前价差,亦即摆盘数据的买档或卖档的相邻档位的报价差\';' # ] # }, # { # "table": "ft_ticker", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "time": sa.types.DATETIME, # "price": sa.types.FLOAT, # "volume": sa.types.BIGINT, # "turnover": sa.types.FLOAT, # "ticker_direction": sa.types.VARCHAR(20), # "sequence": sa.types.VARCHAR(50), # "recv_time": sa.types.DATETIME, # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`time`);' # 'ALTER TABLE `{0}` ADD INDEX (`sequence`);', # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover FLOAT COMMENT \'成交金额\';', # 'ALTER TABLE `{0}` MODIFY COLUMN volume BIGINT COMMENT \'成交数量(股数)\';', # 'ALTER TABLE `{0}` MODIFY COLUMN ticker_direction VARCHAR(20) COMMENT \'逐笔方向\';', # 'ALTER TABLE `{0}` MODIFY COLUMN sequence VARCHAR(50) COMMENT \'逐笔序号\';', # ] # }, # { # "table": "ft_tradeorder", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "stock_name": sa.types.NVARCHAR(100), # "dealt_avg_price": sa.types.FLOAT, # "dealt_qty": sa.types.FLOAT, # "qty": sa.types.FLOAT, # "order_id": sa.types.NVARCHAR(50), # "order_type": sa.types.NVARCHAR(20), # "price": sa.types.FLOAT, # "order_status": sa.types.NVARCHAR(20), # "create_time": sa.types.DATETIME, # "updated_time": sa.types.DATETIME, # "trd_side": sa.types.NVARCHAR(20), # "last_err_msg": sa.types.NVARCHAR(1000), # "trd_market": sa.types.NVARCHAR(30), # "trd_env": sa.types.NVARCHAR(30), # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`stock_name`);', # 'ALTER TABLE `{0}` ADD INDEX (`create_time`);' # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';' # 'ALTER TABLE `{0}` MODIFY COLUMN dealt_avg_price FLOAT COMMENT \'成交均价,无精度限制\';', # 'ALTER TABLE `{0}` MODIFY COLUMN dealt_qty FLOAT COMMENT \'成交数量,2位精度,期权单位是”张”\';', # 'ALTER TABLE `{0}` MODIFY COLUMN qty FLOAT COMMENT \'订单数量,2位精度,期权单位是”张”\';', # ] # }, # { # "table": "ft_tradedetail", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "stock_name": sa.types.NVARCHAR(100), # "trd_env": sa.types.NVARCHAR(20), # "deal_id": sa.types.NVARCHAR(50), # "order_id": sa.types.NVARCHAR(50), # "qty": sa.types.FLOAT, # "price": sa.types.FLOAT, # "trd_side": sa.types.NVARCHAR(20), # "create_time": sa.types.DATETIME, # "counter_broker_id": sa.types.INT, # "counter_broker_name": sa.types.NVARCHAR(100), # "trd_market": sa.types.NVARCHAR(50), # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`stock_name`);' # 'ALTER TABLE `{0}` ADD INDEX (`create_time`);', # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';' # 'ALTER TABLE `{0}` MODIFY COLUMN trd_env VARCHAR(20) COMMENT \'交易环境\';', # 'ALTER TABLE `{0}` MODIFY COLUMN deal_id VARCHAR(50) COMMENT \'成交号\';', # 'ALTER TABLE `{0}` MODIFY COLUMN order_id VARCHAR(50) COMMENT \'订单号\';', # 'ALTER TABLE `{0}` MODIFY COLUMN qty FLOAT COMMENT \'成交数量,2位精度,期权单位是”张”\';', # 'ALTER TABLE `{0}` MODIFY COLUMN price FLOAT COMMENT \'成交价格,3位精度(A股2位)\';', # 'ALTER TABLE `{0}` MODIFY COLUMN trd_side VARCHAR(20) COMMENT \'交易方向\';', # 'ALTER TABLE `{0}` MODIFY COLUMN counter_broker_id INT COMMENT \'对手经纪号,港股有效\';', # 'ALTER TABLE `{0}` MODIFY COLUMN counter_broker_name VARCHAR(100) COMMENT \'对手经纪名称,港股有效\';', # 'ALTER TABLE `{0}` MODIFY COLUMN trd_market VARCHAR(50) COMMENT \'交易市场\';', # ] # }, # { # "table": "ft_autype", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "ex_div_date": sa.types.DATE, # "split_ratio": sa.types.FLOAT, # "per_cash_div": sa.types.FLOAT, # "per_share_div_ratio": sa.types.FLOAT, # "per_share_trans_ratio": sa.types.FLOAT, # "allotment_ratio": sa.types.FLOAT, # "allotment_price": sa.types.FLOAT, # "stk_spo_ratio": sa.types.FLOAT, # "stk_spo_price": sa.types.FLOAT, # "forward_adj_factorA": sa.types.FLOAT, # "forward_adj_factorB": sa.types.FLOAT, # "backward_adj_factorA": sa.types.FLOAT, # "backward_adj_factorB": sa.types.FLOAT # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`ex_div_date`);' # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';' # 'ALTER TABLE `{0}` MODIFY COLUMN ex_div_date DATE COMMENT \'除权除息日\';' # 'ALTER TABLE `{0}` MODIFY COLUMN split_ratio FLOAT COMMENT \'拆合股比例; double,例如,对于5股合1股为1/5,对于1股拆5股为5/1\';' # 'ALTER TABLE `{0}` MODIFY COLUMN per_cash_div FLOAT COMMENT \'每股派现\';' # 'ALTER TABLE `{0}` MODIFY COLUMN per_share_div_ratio FLOAT COMMENT \'每股送股比例\';' # 'ALTER TABLE `{0}` MODIFY COLUMN per_share_trans_ratio FLOAT COMMENT \'每股转增股比例\';' # 'ALTER TABLE `{0}` MODIFY COLUMN allotment_ratio FLOAT COMMENT \'每股配股比例\';' # 'ALTER TABLE `{0}` MODIFY COLUMN allotment_price FLOAT COMMENT \'配股价\';' # 'ALTER TABLE `{0}` MODIFY COLUMN stk_spo_ratio FLOAT COMMENT \'增发比例\';' # 'ALTER TABLE `{0}` MODIFY COLUMN stk_spo_price FLOAT COMMENT \'增发价格\';' # 'ALTER TABLE `{0}` MODIFY COLUMN forward_adj_factorA FLOAT COMMENT \'前复权因子A\';' # 'ALTER TABLE `{0}` MODIFY COLUMN forward_adj_factorB FLOAT COMMENT \'前复权因子B\';' # 'ALTER TABLE `{0}` MODIFY COLUMN backward_adj_factorA FLOAT COMMENT \'后复权因子A\';' # 'ALTER TABLE `{0}` MODIFY COLUMN backward_adj_factorB FLOAT COMMENT \'后复权因子B\';' # ] # }, # { # "table": "ft_market_snapshot", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "update_time": sa.types.DATETIME, # "last_price": sa.types.FLOAT, # "open_price": sa.types.FLOAT, # "high_price": sa.types.FLOAT, # "low_price": sa.types.FLOAT, # "prev_close_price": sa.types.FLOAT, # "volume": sa.types.BIGINT, # "turnover": sa.types.BIGINT, # "turnover_rate": sa.types.FLOAT, # "suspension": sa.types.INT, # "listing_date": sa.types.DATE, # "circular_market_val": sa.types.FLOAT, # "low_price": sa.types.FLOAT, # "total_market_val": sa.types.FLOAT, # "wrt_valid": sa.types.INT, # "wrt_conversion_ratio": sa.types.FLOAT, # "wrt_type": sa.types.NVARCHAR(20), # "wrt_strike_price": sa.types.FLOAT, # "wrt_maturity_date": sa.types.DATE, # "wrt_end_trade": sa.types.DATE, # "wrt_code": sa.types.NVARCHAR(50), # "wrt_recovery_price": sa.types.FLOAT, # "wrt_street_vol": sa.types.FLOAT, # "wrt_issue_vol": sa.types.FLOAT, # "wrt_street_ratio": sa.types.FLOAT, # "wrt_delta": sa.types.FLOAT, # "wrt_implied_volatility": sa.types.FLOAT, # "wrt_premium": sa.types.FLOAT, # "lot_size": sa.types.BIGINT, # "issued_Shares": sa.types.BIGINT, # "net_asset": sa.types.FLOAT, # "net_profit": sa.types.FLOAT, # "earning_per_share": sa.types.FLOAT, # "outstanding_shares": sa.types.BIGINT, # "net_asset_per_share": sa.types.FLOAT, # "ey_ratio": sa.types.FLOAT, # "pe_ratio": sa.types.FLOAT, # "pb_ratio": sa.types.FLOAT, # "price_spread": sa.types.FLOAT # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`update_time`);' # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';' # 'ALTER TABLE `{0}` MODIFY COLUMN last_price FLOAT COMMENT \'最新价格\';' # 'ALTER TABLE `{0}` MODIFY COLUMN open_price FLOAT COMMENT \'今日开盘价\';' # 'ALTER TABLE `{0}` MODIFY COLUMN high_price FLOAT COMMENT \'最高价格\';' # 'ALTER TABLE `{0}` MODIFY COLUMN low_price FLOAT COMMENT \'最低价格\';' # 'ALTER TABLE `{0}` MODIFY COLUMN prev_close_price FLOAT COMMENT \'昨收盘价格\';' # 'ALTER TABLE `{0}` MODIFY COLUMN volume BIGINT COMMENT \'成交数量\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover FLOAT COMMENT \'成交金额\';' # 'ALTER TABLE `{0}` MODIFY COLUMN turnover_rate FLOAT COMMENT \'换手率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN suspension INT COMMENT \'是否停牌(True表示停牌)\';' # 'ALTER TABLE `{0}` MODIFY COLUMN listing_date DATE COMMENT \'上市日期 (yyyy-MM-dd)\';' # 'ALTER TABLE `{0}` MODIFY COLUMN circular_market_val FLOAT COMMENT \'流通市值\';' # 'ALTER TABLE `{0}` MODIFY COLUMN total_market_val FLOAT COMMENT \'总市值\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_valid INT COMMENT \'是否是窝轮\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_conversion_ratio FLOAT COMMENT \'换股比率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_type VARCHAR(20) COMMENT \'窝轮类型;1=认购证 2=认沽证 3=牛证 4=熊证 \';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_strike_price FLOAT COMMENT \'行使价格\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_maturity_date DATE COMMENT \'格式化窝轮到期时间\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_end_trade DATE COMMENT \'格式化窝轮最后交易时间\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_code VARCHAR(50) COMMENT \'窝轮对应的正股\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_recovery_price FLOAT COMMENT \'窝轮回收价\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_street_vol FLOAT COMMENT \'窝轮街货量\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_issue_vol FLOAT COMMENT \'窝轮发行量\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_street_ratio FLOAT COMMENT \'窝轮街货占比\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_delta FLOAT COMMENT \'窝轮对冲值\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_implied_volatility FLOAT COMMENT \'窝轮引伸波幅\';' # 'ALTER TABLE `{0}` MODIFY COLUMN wrt_premium FLOAT COMMENT \'窝轮溢价\';' # 'ALTER TABLE `{0}` MODIFY COLUMN lot_size BIGINT COMMENT \'每手股数\';' # 'ALTER TABLE `{0}` MODIFY COLUMN issued_Shares BIGINT COMMENT \'发行股本\';' # 'ALTER TABLE `{0}` MODIFY COLUMN net_asset FLOAT COMMENT \'资产净值\';' # 'ALTER TABLE `{0}` MODIFY COLUMN net_profit FLOAT COMMENT \'净利润\';' # 'ALTER TABLE `{0}` MODIFY COLUMN earning_per_share FLOAT COMMENT \'每股盈利\';' # 'ALTER TABLE `{0}` MODIFY COLUMN outstanding_shares BIGINT COMMENT \'流通股本\';' # 'ALTER TABLE `{0}` MODIFY COLUMN net_asset_per_share FLOAT COMMENT \'每股净资产\';' # 'ALTER TABLE `{0}` MODIFY COLUMN ey_ratio FLOAT COMMENT \'收益率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN pe_ratio FLOAT COMMENT \'市盈率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN pb_ratio FLOAT COMMENT \'市净率\';' # 'ALTER TABLE `{0}` MODIFY COLUMN price_spread FLOAT COMMENT \'当前摆盘价差亦即摆盘数据的买档或卖档的相邻档位的报价差\';' # ] # }, # { # "table": "ft_plate_list", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "plate_name": sa.types.NVARCHAR(50), # "plate_id": sa.types.NVARCHAR(20), # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # # code aren't unique # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`plate_name`);' # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';' # 'ALTER TABLE `{0}` MODIFY COLUMN code VARCHAR(20) COMMENT \'股票代码\';' # 'ALTER TABLE `{0}` MODIFY COLUMN plate_name VARCHAR(50) COMMENT \'板块名字\';' # 'ALTER TABLE `{0}` MODIFY COLUMN plate_id VARCHAR(20) COMMENT \'板块id\';' # ] # }, # { # "table": "ft_plate_stock", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "lot_size": sa.types.BIGINT, # "stock_name": sa.types.NVARCHAR(100), # "stock_owner": sa.types.NVARCHAR(100), # "stock_child_type": sa.types.NVARCHAR(20), # "stock_type": sa.types.NVARCHAR(20), # "list_time": sa.types.DATE, # "stock_id": sa.types.BIGINT, # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` ADD INDEX (`stock_name`);' # 'ALTER TABLE `{0}` ADD INDEX (`stock_child_type`);' # 'ALTER TABLE `{0}` ADD INDEX (`stock_type`);' # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';' # 'ALTER TABLE `{0}` MODIFY COLUMN code VARCHAR(20) COMMENT \'股票代码\';' # 'ALTER TABLE `{0}` MODIFY COLUMN lot_size BIGINT COMMENT \'每手股数\';' # 'ALTER TABLE `{0}` MODIFY COLUMN stock_name VARCHAR(100) COMMENT \'股票名称\';' # 'ALTER TABLE `{0}` MODIFY COLUMN stock_owner VARCHAR(100) COMMENT \'所属正股的代码\';' # 'ALTER TABLE `{0}` MODIFY COLUMN stock_child_type VARCHAR(100) COMMENT \'股票子类型,参见WrtType\';' # 'ALTER TABLE `{0}` MODIFY COLUMN stock_type VARCHAR(20) COMMENT \'股票类型,参见SecurityType\';' # 'ALTER TABLE `{0}` MODIFY COLUMN list_time DATE COMMENT \'上市时间\';' # 'ALTER TABLE `{0}` MODIFY COLUMN stock_id BIGINT COMMENT \'股票id\';' # ] # }, # { # "table": "sys_sharding", # "dtype": { # "id": sa.types.BIGINT, # "code": sa.types.NVARCHAR(20), # "dtype": sa.types.Enum('hk','hk_5m','hk_1m'), # "tindex": sa.types.SMALLINT, # "lastdate": sa.types.DATE, # }, # "clauses": [ # 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', # 'ALTER TABLE `{0}` ADD INDEX (`code`);', # 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\';' # 'ALTER TABLE `{0}` MODIFY COLUMN code VARCHAR(20) COMMENT \'股票代码\';' # 'ALTER TABLE `{0}` MODIFY COLUMN tindex SMALLINT COMMENT \'表索引\';' # 'ALTER TABLE `{0}` MODIFY COLUMN lastdate SMALLINT COMMENT \'最后更新时间\';' # 'ALTER TABLE `{0}` ENGINE = InnoDB;' # ] # }, ] try: logging.info("int_schema, starting") for schema in schemaArr: df = pd.DataFrame(None,columns=schema['dtype'].keys()) table = schema['table'] logging.info('table:{0}'.format(table)) clauses = [] for clause in schema['clauses']: clause = clause.format(table) clauses.append(clause) storeservice.init_schema(table,df,schema['dtype'],clauses) logging.info("int_schema, end") except IOError as err: logging.error("OS|error: {0}".format(err)) else: logging.info('init schema success')
def __init__(self): self.storeservice = MysqlService()
def __init__(self, quote_ctx): self.ctx = quote_ctx self.storeservice = MysqlService()
class LF(object): def __init__(self, quote_ctx): self.ctx = quote_ctx self.storeservice = MysqlService() def is_holiday(self, market, date): ''' 判断是否为交易日,返回True or False ''' ret_code, ret_data = self.get_trading_days(market) if ret_code == RET_ERROR: print(ret_data) exit() return date not in ret_data def get_trading_days(self, market, start_date=None, end_date=None): ''' 功能: 获取交易日 Parameters: market – 市场类型,futuquant.common.constsnt.Market start_date – 起始日期 end_date – 结束日期 Returns: 成功时返回(RET_OK, data),data是字符串数组;失败时返回(RET_ERROR, data),其中data是错误描述字符串 ''' ret_code, ret_data = self.ctx.get_trading_days(market=market) if ret_code == RET_ERROR: print(ret_data) exit() # print("TRADING DAYS") # for x in ret_data: # print(x) return ret_code, ret_data def get_stock_basicinfo(self, market, stock_type=SecurityType.STOCK): ''' 功能: 获取指定市场中特定类型的股票基本信息 Parameters: market – 市场类型,futuquant.common.constsnt.Market stock_type – 股票类型, futuquant.common.constsnt.SecurityType Returns: (ret_code, content) ret_code 等于RET_OK时, content为Pandas.DataFrame数据, 否则为错误原因字符串, 数据列格式如下 参数 类型 说明 code str 股票代码 name str 名字 lot_size int 每手数量 stock_type str 股票类型,参见SecurityType stock_child_type str 涡轮子类型,参见WrtType stock_owner str 正股代码 listing_date str 上市时间 stock_id int 股票id ''' ret_code, ret_data = self.ctx.get_stock_basicinfo(market, stock_type) if ret_code == RET_ERROR: print(ret_data) exit() table = 'ft_stock_basicinfo' self.storeservice.insert_many(table, ret_data, 'append') return ret_code, ret_data def get_multiple_history_kline(self, codelist=[], start=None, end=None, ktype=KLType.K_DAY, autype=AuType.QFQ): """ 功能: 获取多只股票的历史k线数据 Parameters: codelist – 股票代码列表,list或str。例如:[‘HK.00700’, ‘HK.00001’],’HK.00700,SZ.399001’ start – 起始时间 end – 结束时间 ktype – k线类型,参见KLType autype – 复权类型,参见AuType Returns: 成功时返回(RET_OK, [data]),data是DataFrame数据, 数据列格式如下 参数 类型 说明 code str 股票代码 time_key str k线时间 open float 开盘价 close float 收盘价 high float 最高价 low float 最低价 pe_ratio float 市盈率 turnover_rate float 换手率 volume int 成交量 turnover float 成交额 change_rate float 涨跌幅 last_close float 昨收价 失败时返回(RET_ERROR, data),其中data是错误描述字符串 """ ret_code, ret_data = self.ctx.get_multiple_history_kline( codelist, start, end, ktype, autype) print(ret_data) if ret_code == RET_ERROR: print(ret_data) #exit() # print(ret_data) table = 'ft_kline' for item in ret_data: self.storeservice.insert_many(table, item, 'append') return ret_code, ret_data def get_history_kline(self, code, tindex=None, start=None, end=None, ktype=KLType.K_DAY, autype=AuType.QFQ, fields=KL_FIELD.ALL): ''' 获取历史K线 :param code: 股票代码 :param start: 开始时间,string; YYYY-MM-DD;为空时取去当前时间; :param end: 结束时间,string; YYYY-MM-DD;为空时取当前时间; :param ktype: k线类型,默认为日K :param autype: 复权类型,string;”qfq”-前复权,”hfq”-后复权,None-不复权,默认为”qfq” fields: 单个或多个K线字段类型,指定需要返回的数据 KL_FIELD.ALL or [KL_FIELD.DATE_TIME, KL_FIELD.OPEN],默认为KL_FIELD.ALL 开始结束时间按照闭区间查询,时间查询以k线时间time_key作为比较标准。即满足 start<=Time_key<=end条件的k线作为返回内容,k线时间time_key的设定标准在返回值中说明 :return: ret_code失败时,ret_data返回为错误描述字符串; 客户端无符合条件数据时,ret_code为成功,返回None; 正常情况下返回K线数据为一个DataFrame包含: code: 股票代码;string time_key: K线时间 string “YYYY-MM-DD HH:mm:ss” open: 开盘价;double high: 最高价;double close: 收盘价;double low: 最低价;double pe_ratio: 市盈率;double turnover_rate: 换手率;double volume: 成交量;long turnover : 成交额;double change_rate: 涨跌幅;double last_close float 昨收价 对于日K线,time_key为当日时间具体到日,比如说2016-12-23日的日K,K线时间为”2016-12-23 00:00:00” 对于周K线,12月19日到12月25日的周K线,K线时间time_key为” 2016-12-19 00:00:00” 对于月K线,12月的月K线时间time_key为” 2016-12-01 00:00:00”,即为当月1日时间 对于分K线,time_key为当日时间具体到分,例如, 分K类型 覆盖时间举例 1分K 覆盖9:35:00到9:35:59的分K,time_key为”2016-12-23 09:36:00” 5分K 覆盖10:05:00到10:09:59的分K,time_key为”2016-12-23 10:10:00” 15分K 覆盖10:00:00到10:14:59的分K,time_key为”2016-12-23 10:15:00” 30分K 覆盖10:00:00到10:29:59的分K,time_key为”2016-12-23 10:30:00” 60分K 覆盖10:00:00到10:59:59的分K,time_key为”2016-12-23 11:00:00” 失败情况: 股票代码不合法 PLS接口返回错误 US.AAPL返回为空,需要订阅吗? ''' ret_code, ret_data = self.ctx.get_history_kline( code, start, end, ktype, autype, fields) if ret_code == RET_ERROR: print(ret_data) #exit() #print(ret_data) lastdate = None if not isinstance(ret_data, str): if len(ret_data) > 0: if tindex == None: if ktype == KLType.K_DAY: table = 'ft_kline' tindex = self.storeservice.find_tindex(code, 'hk') if tindex != -1: table += ('_' + str(tindex)) elif ktype == KLType.K_5M: table = 'ft_5M' if ktype == KLType.K_5M: tindex = self.storeservice.find_tindex( code, 'hk_5m') if tindex != -1: table += ('_' + str(tindex)) else: table = 'ft_1M' if ktype == KLType.K_1M: tindex = self.storeservice.find_tindex( code, 'hk_1m') if tindex != -1: table += ('_' + str(tindex)) else: if ktype == KLType.K_DAY: table = 'ft_kline' table += ('_' + str(tindex)) elif ktype == KLType.K_5M: table = 'ft_5M' table += ('_' + str(tindex)) else: table = 'ft_1M' table += ('_' + str(tindex)) lastdate = ret_data['time_key'][len(ret_data) - 1] self.storeservice.insert_many(table, ret_data, 'append') return ret_code, ret_data, lastdate def get_autype_list(self, code_list): '''获取复权因子 :param code_list: 股票代码列表,例如,HK.00700,US.AAPL :return: ret_code失败时,ret_data返回为错误描述字符串; 客户端无符合条件数据时,ret_code为成功,ret_data返回None; 正常情况下,ret_data为一个dataframe,其中包括: code:股票代码;string,例如: ”HK.00700”,“US.AAPL” ex_div_date:除权除息日;string,格式YYYY-MM-DD split_ratio:拆合股比例; double,例如,对于5股合1股为1/5,对于1股拆5股为5/1 per_cash_div:每股派现;double per_share_div_ratio:每股送股比例; double per_share_trans_ratio:每股转增股比例; double allotment_ratio:每股配股比例;double allotment_price:配股价;double stk_spo_ratio:增发比例;double stk_spo_price :增发价格;double forward_adj_factorA:前复权因子A;double forward_adj_factorB:前复权因子B;double backward_adj_factorA:后复权因子A;double backward_adj_factorB:后复权因子B;double 返回数据中不一定包含所有codelist中的代码,调用方自己需要检查,哪些股票代码是没有返回复权数据的,未返回复权数据的股票说明没有找到相关信息。 复权价格 = 复权因子A * 价格 + 复权因子B 失败情况: 1. Codelist中股票代码不合法 2. 客户端内部或网络错误 ''' ret_code, ret_data = self.ctx.get_autype_list(code_list) if ret_code == RET_ERROR: print(ret_data) #exit() #print(ret_data) table = 'ft_autype' self.storeservice.insert_many(table, ret_data, 'append') return ret_code, ret_data @rate_limit(FREQ.GET_MARKET_SNAPSHOT) def get_market_snapshot(self, code_list): ''' 功能:获取市场快照 :param code_list: 股票列表,限制最多200只股票 :return: ret_code失败时,ret_data返回为错误描述字符串; 客户端无符合条件数据时,ret_code为成功,ret_data返回None; 正常情况下,ret_data为一个dataframe,其中包括: code :股票代码;string update_time: 更新时间(yyyy-MM-dd HH:mm:ss);string last_price : 最新价格;float open_price: 今日开盘价;float high_price: 最高价格;float low_price: 最低价格;float prev_close_price: 昨收盘价格;float volume: 成交数量; long turnover: 成交金额;float turnover_rate: 换手率;float suspension: 是否停牌(True表示停牌);bool listing_date : 上市日期 (yyyy-MM-dd);string circular_market_val: 流通市值;float total_market_val: 总市值;float wrt_valid: 是否是窝轮;bool wrt_conversion_ratio: 换股比率;float wrt_type: 窝轮类型;1=认购证 2=认沽证 3=牛证 4=熊证 string wrt_strike_price: 行使价格;float wrt_maturity_date: 格式化窝轮到期时间; string wrt_end_trade: 格式化窝轮最后交易时间;string wrt_code: 窝轮对应的正股;string wrt_recovery_price: 窝轮回收价;float wrt_street_vol: 窝轮街货量;float wrt_issue_vol: 窝轮发行量;float wrt_street_ratio: 窝轮街货占比;float wrt_delta: 窝轮对冲值;float wrt_implied_volatility: 窝轮引伸波幅;float wrt_premium: 窝轮溢价;float lot_size:每手股数;int issued_Shares:发行股本;int net_asset:资产净值;int net_profit:净利润;int earning_per_share: 每股盈利;float outstanding_shares:流通股本;int net_asset_per_share:每股净资产;float ey_ratio:收益率;float pe_ratio:市盈率;float pb_ratio:市净率;float price_spread : 当前摆盘价差亦即摆盘数据的买档或卖档的相邻档位的报价差;float 返回DataFrame,包含上述字段 窝轮类型 wrt_type,(字符串类型): 窝轮类型 标识 “CALL” 认购证 “PUT” 认沽证 “BULL” 牛证 “BEAR” 熊证 “N/A” 未知或服务器没相关数据 返回数据量不一定与codelist长度相等, 用户需要自己判断 调用频率限制: 5s一次 失败情况: Codelist中股票代码不合法 Codelist长度超过规定数量 客户端内部或网络错误 ''' ret_code, ret_data = self.ctx.get_market_snapshot(code_list) if ret_code == RET_ERROR: print(ret_data) exit() #print(ret_data) table = 'ft_market_snapshot' self.storeservice.insert_many(table, ret_data, 'append') return ret_code, ret_data @rate_limit(FREQ.GET_PLATE_STOCK) def get_plate_stock(self, plate_code): ''' 功能: 获取板块下的股票列表 :param plate_code: 板块代码, string, 例如,”SH.BK0001”,”SH.BK0002”,先利用获取子版块列表函数获取子版块代码 :return: ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下 ret != RET_OK 返回错误字符串 参数 类型 说明 code str 股票代码 lot_size int 每手股数 stock_name str 股票名称 stock_owner str 所属正股的代码 stock_child_type str 股票子类型,参见WrtType stock_type str 股票类型,参见SecurityType list_time str 上市时间 stock_id int 股票id ''' ret_code, ret_data = self.ctx.get_plate_stock(plate_code) if ret_code == RET_ERROR: print(ret_data) exit() # print(ret_data) table = 'ft_plate_stock' self.storeservice.insert_many(table, ret_data, 'append') return ret_code, ret_data @rate_limit(FREQ.GET_PLATE_LIST) def get_plate_list(self, market, plate_class=Plate.ALL): ''' 功能: 获取板块集合下的子板块列表 :param market: 市场标识,注意这里不区分沪,深,输入沪或者深都会返回沪深市场的子板块(这个是和客户端保持一致的) :param plate_class: 板块分类, string; 例如,”ALL”, “INDUSTRY” 板块分类类型 ,(字符串类型): 板块分类 标识 “ALL” 所有板块 “INDUSTRY” 行业分类 “REGION” 地域分类 “CONCEPT” 概念分类 :return: ret == RET_OK 返回pd Dataframe数据,数据列格式如下 ret != RET_OK 返回错误字符串 参数 类型 说明 code str 股票代码 plate_name str 板块名字 plate_id str 板块id ''' ret_code, ret_data = self.ctx.get_plate_list(market, plate_class) if ret_code == RET_ERROR: print(ret_data) exit() #print(ret_data) table = 'ft_plate_list' self.storeservice.insert_many(table, ret_data, 'append') return ret_code, ret_data def get_global_state(self): ''' 功能:获取牛牛程序全局状态 :return: 返回: (ret, data) ret == RET_OK data为包含全局状态的字典,含义如下 ret != RET_OK data为错误描述字符串 key value类型 说明 market_sz str 深圳市场状态,参见MarketState market_us str 美国市场状态,参见MarketState market_sh str 上海市场状态,参见MarketState market_hk str 香港市场状态,参见MarketState market_hkfuture str 香港期货市场状态,参见MarketState server_ver str FutuOpenD版本号 trd_logined str ‘1’:已登录交易服务器,‘0’: 未登录交易服务器 qot_logined str ‘1’:已登录行情服务器,‘0’: 未登录行情服务器 timestamp str 当前格林威治时间戳 ''' ret_code, ret_data = self.ctx.get_global_state() if ret_code == RET_ERROR: print(ret_data) exit() return ret_code, ret_data @clock() def get_multi_points_history_kline(self, code_list, dates, fields=KL_FIELD.ALL, ktype=KLType.K_DAY): ''' 功能: 获取多支股票多个时间点的指定数据列 Parameters: code_list – 单个或多个股票 ‘HK.00700’ or [‘HK.00700’, ‘HK.00001’] dates – 单个或多个日期 ‘2017-01-01’ or [‘2017-01-01’, ‘2017-01-02’],最多5个时间点 fields – 单个或多个数据列 KL_FIELD.ALL or [KL_FIELD.DATE_TIME, KL_FIELD.OPEN] ktype – K线类型 autype – 复权类型 no_data_mode – 指定时间为非交易日时,对应的k线数据取值模式,参见KLNoDataMode Returns: (ret, data) ret == RET_OK 返回pd dataframe数据,固定表头包括’code’(代码) ‘time_point’(指定的日期) ‘data_status’ (KLDataStatus)。数据列格式如下 ret != RET_OK 返回错误字符串 参数 类型 说明 code str 股票代码 time_point str 请求的时间 data_status str 数据点是否有效,参见KLDataStatus time_key str k线时间 open float 开盘价 close float 收盘价 high float 最高价 low float 最低价 pe_ratio float 市盈率 turnover_rate float 换手率 volume int 成交量 turnover float 成交额 change_rate float 涨跌幅 last_close float 昨收价 ''' ret_code, ret_data = self.ctx.get_multi_points_history_kline( code_list, dates, fields, ktype) if ret_code == RET_ERROR: print(ret_data) exit() print(ret_data) return ret_code, ret_data
# -*- coding: UTF-8 -*-
def main(): storeservice = MysqlService() deal_1m(storeservice)
def main(): storeservice = MysqlService() kline_5m_tables_number = 35 schemaArr = [ { "table": "ft_5M_{0}", "dtype": { "id": sa.types.BIGINT, "code": sa.types.NVARCHAR(20), "time_key": sa.types.DATETIME, "open": sa.types.FLOAT, "close": sa.types.FLOAT, "high": sa.types.FLOAT, "low": sa.types.FLOAT, "pe_ratio": sa.types.FLOAT, "turnover_rate": sa.types.FLOAT, "volume": sa.types.BIGINT, "turnover": sa.types.FLOAT, "change_rate": sa.types.FLOAT, "last_close": sa.types.FLOAT }, "clauses": [ 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', 'ALTER TABLE `{0}` ADD INDEX (`code`);', 'ALTER TABLE `{0}` ADD INDEX (`time_key`);', 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\'', 'ALTER TABLE `{0}` MODIFY COLUMN pe_ratio FLOAT COMMENT \'市盈率\';', 'ALTER TABLE `{0}` MODIFY COLUMN turnover_rate FLOAT COMMENT \'换手率\';', 'ALTER TABLE `{0}` MODIFY COLUMN volume BIGINT COMMENT \'成交量\';', 'ALTER TABLE `{0}` MODIFY COLUMN turnover FLOAT COMMENT \'成交额\';', 'ALTER TABLE `{0}` MODIFY COLUMN change_rate FLOAT COMMENT \'涨跌幅\';', 'ALTER TABLE `{0}` MODIFY COLUMN last_close FLOAT COMMENT \'昨收价\';', 'ALTER TABLE `{0}` ENGINE=MyISAM;' ] }, ] try: logging.info("create sub kline 5m schema, starting") for index in range(1,kline_5m_tables_number,1): for schema in schemaArr: df = pd.DataFrame(None, columns=schema['dtype'].keys()) table = schema['table'].format(index) logging.info(table) logging.info('table:{0}'.format(table)) clauses = [] for clause in schema['clauses']: clause = clause.format(table) clauses.append(clause) storeservice.init_schema(table, df, schema['dtype'], clauses) logging.info("create sub kline 5m, end") except IOError as err: logging.error("OS|error: {0}".format(err)) else: logging.info('create sub kline success') union_table = [('ft_5M_{0}'.format(table)) for table in range(1, kline_5m_tables_number, 1)] mrg_kline_claus = 'ALTER TABLE `{0}` ENGINE = MRG_MyISAM UNION = ({1}) INSERT_METHOD = LAST;'.format({0}, ','.join(union_table)) schemaArr = [ { "table": "ft_5m", "dtype": { "id": sa.types.BIGINT, "code": sa.types.NVARCHAR(20), "time_key": sa.types.DATETIME, "open": sa.types.FLOAT, "close": sa.types.FLOAT, "high": sa.types.FLOAT, "low": sa.types.FLOAT, "pe_ratio": sa.types.FLOAT, "turnover_rate": sa.types.FLOAT, "volume": sa.types.BIGINT, "turnover": sa.types.FLOAT, "change_rate": sa.types.FLOAT, "last_close": sa.types.FLOAT }, "clauses": [ 'ALTER TABLE `{0}` ADD PRIMARY KEY (`id`);', 'ALTER TABLE `{0}` ADD INDEX (`code`);', 'ALTER TABLE `{0}` ADD INDEX (`time_key`);', 'ALTER TABLE `{0}` MODIFY COLUMN id BIGINT NOT NULL AUTO_INCREMENT COMMENT \'id\'', 'ALTER TABLE `{0}` MODIFY COLUMN pe_ratio FLOAT COMMENT \'市盈率\';', 'ALTER TABLE `{0}` MODIFY COLUMN turnover_rate FLOAT COMMENT \'换手率\';', 'ALTER TABLE `{0}` MODIFY COLUMN volume BIGINT COMMENT \'成交量\';', 'ALTER TABLE `{0}` MODIFY COLUMN turnover FLOAT COMMENT \'成交额\';', 'ALTER TABLE `{0}` MODIFY COLUMN change_rate FLOAT COMMENT \'涨跌幅\';', 'ALTER TABLE `{0}` MODIFY COLUMN last_close FLOAT COMMENT \'昨收价\';', mrg_kline_claus ] } ] try: logging.info("create kline 5m schema, starting") for schema in schemaArr: df = pd.DataFrame(None, columns=schema['dtype'].keys()) table = schema['table'] logging.info(table) logging.info('table:{0}'.format(table)) clauses = [] for clause in schema['clauses']: clause = clause.format(table) clauses.append(clause) storeservice.init_schema(table, df, schema['dtype'], clauses) logging.info("create kline 5m, end") except IOError as err: logging.error("OS|error: {0}".format(err)) else: logging.info('create kline 5m success')
def __init__(self): self.tushare_version = ts.__version__ setup_logging() self.storeservice = MysqlService() print('tushare_versin', self.tushare_version)
class TUShare_service(object): def __init__(self): self.tushare_version = ts.__version__ setup_logging() self.storeservice = MysqlService() print('tushare_versin', self.tushare_version) @tick.clock() def get_hist_data(self,code,start=None,end=None,ktype='D',retry_count=3,pause=0): ''' 功能: 获取个股历史交易数据(包括均线数据),可以通过参数设置获取日k线、周k线、月k线,以及5分钟、15分钟、30分钟和60分钟k线数据。本接口只能获取近3年的日线数据,适合搭配均线数据进行选股和分析,如果需要全部历史数据,请调用下一个接口get_h_data()。 参数说明: code:股票代码,即6位数字代码,或者指数代码(sh=上证指数 sz=深圳成指 hs300=沪深300指数 sz50=上证50 zxb=中小板 cyb=创业板) start:开始日期,格式YYYY-MM-DD end:结束日期,格式YYYY-MM-DD ktype:数据类型,D=日k线 W=周 M=月 5=5分钟 15=15分钟 30=30分钟 60=60分钟,默认为D retry_count:当网络异常后重试次数,默认为3 pause:重试时停顿秒数,默认为0 返回值说明: date:日期 open:开盘价 high:最高价 close:收盘价 low:最低价 volume:成交量 price_change:价格变动 p_change:涨跌幅 ma5:5日均价 ma10:10日均价 ma20:20日均价 v_ma5:5日均量 v_ma10:10日均量 v_ma20:20日均量 turnover:换手率[注:指数无此项] ''' try: df = ts.get_hist_data(code,start, end, ktype,retry_count, pause) print(df) if df is None: return df = df.reset_index(level=[0]) df['code'] = code if ktype == 'D': table = 'ts2_hist_data' else: table = 'ts2_hist_data_' + ktype self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err : logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_h_data(self, code, start=None, end=None, autype='qfq', index=False,retry_count=3, pause=1): ''' 功能: 获取历史复权数据,分为前复权和后复权数据,接口提供股票上市以来所有历史数据,默认为前复权。如果不设定开始和结束日期,则返回近一年的复权数据,从性能上考虑,推荐设定开始日期和结束日期,而且最好不要超过三年以上,获取全部历史数据,请分年段分步获取,取到数据后,请及时在本地存储。获取个股首个上市日期,请参考以下方法 参数说明: code:string,股票代码 e.g. 600848 start:string,开始日期 format:YYYY-MM-DD 为空时取当前日期 end:string,结束日期 format:YYYY-MM-DD 为空时取去年今日 autype:string,复权类型,qfq-前复权 hfq-后复权 None-不复权,默认为qfq index:Boolean,是否是大盘指数,默认为False retry_count : int, 默认3,如遇网络等问题重复执行的次数 pause : int, 默认 0,重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题 返回值说明: date : 交易日期 (index) open : 开盘价 high : 最高价 close : 收盘价 low : 最低价 volume : 成交量 amount : 成交金额 ''' try: df = ts.get_h_data(code, start, end, autype, index, retry_count, pause) if df is None: return df['code'] = code df = df.reset_index(level=[0]) table = 'ts2_h_data' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_today_all(self): ''' 功能: 一次性获取当前交易所有股票的行情数据(如果是节假日,即为上一交易日,结果显示速度取决于网速) 返回值说明: code:代码 name:名称 changepercent:涨跌幅 trade:现价 open:开盘价 high:最高价 low:最低价 settlement:昨日收盘价 volume:成交量 turnoverratio:换手率 amount:成交量 per:市盈率 pb:市净率 mktcap:总市值 nmc:流通市值 ''' try: df = ts.get_today_all() if df is None: return date = time.strftime('%Y-%m-%d', time.localtime()) df['date'] = date df = df.reset_index(level=[0]) del df['index'] table = 'ts2_today_all' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_tick_data(self,code, date=None, retry_count=3, pause=1): ''' 功能: 获取个股以往交易历史的分笔数据明细,通过分析分笔数据,可以大致判断资金的进出情况。在使用过程中,对于获取股票某一阶段的历史分笔数据,需要通过参入交易日参数并append到一个DataFrame或者直接append到本地同一个文件里。历史分笔接口只能获取当前交易日之前的数据,当日分笔历史数据请调用get_today_ticks()接口或者在当日18点后通过本接口获取。 参数说明: code:股票代码,即6位数字代码 date:日期,格式YYYY-MM-DD retry_count : int, 默认3,如遇网络等问题重复执行的次数 pause : int, 默认 0,重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题 返回值说明: time:时间 price:成交价格 change:价格变动 volume:成交手 amount:成交金额(元) type:买卖类型【买盘、卖盘、中性盘】 ''' try: df = ts.get_tick_data(code,date,retry_count, pause) if df is None: return df = df.replace('--', 0) df['change'] = df['change'].astype(float) df['date'] = DateUtil.getTodayStr() df['code'] = code df = df.reset_index(level=[0]) del df['index'] self.storeservice.insert_many('ts2_tick_data', df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_realtime_quotes(self,codes): ''' 功能: 获取实时分笔数据,可以实时取得股票当前报价和成交信息,其中一种场景是,写一个python定时程序来调用本接口(可两三秒执行一次,性能与行情软件基本一致),然后通过DataFrame的矩阵计算实现交易监控,可实时监测交易量和价格的变化。 参数说明: symbols:6位数字股票代码,或者指数代码(sh=上证指数 sz=深圳成指 hs300=沪深300指数 sz50=上证50 zxb=中小板 cyb=创业板) 可输入的类型:str、list、set或者pandas的Series对象 返回值说明: 0:name,股票名字 1:open,今日开盘价 2:pre_close,昨日收盘价 3:price,当前价格 4:high,今日最高价 5:low,今日最低价 6:bid,竞买价,即“买一”报价 7:ask,竞卖价,即“卖一”报价 8:volume,成交量 maybe you need do volume/100 9:amount,成交金额(元 CNY) 10:b1_v,委买一(笔数 bid volume) 11:b1_p,委买一(价格 bid price) 12:b2_v,“买二” 13:b2_p,“买二” 14:b3_v,“买三” 15:b3_p,“买三” 16:b4_v,“买四” 17:b4_p,“买四” 18:b5_v,“买五” 19:b5_p,“买五” 20:a1_v,委卖一(笔数 ask volume) 21:a1_p,委卖一(价格 ask price) ... 30:date,日期; 31:time,时间; ''' try: df = ts.get_realtime_quotes(codes) if df is None: return df = df.replace('--', 0) df = df.replace('', 0) df['b1_v'] = df['b1_v'].astype(int) df['b2_v'] = df['b2_v'].astype(int) df['b3_v'] = df['b3_v'].astype(int) df['b4_v'] = df['b4_v'].astype(int) df['b5_v'] = df['b5_v'].astype(int) df['a1_v'] = df['a1_v'].astype(int) df['a2_v'] = df['a2_v'].astype(int) df['a3_v'] = df['a3_v'].astype(int) df['a4_v'] = df['a4_v'].astype(int) df['a5_v'] = df['a5_v'].astype(int) df['date'] = DateUtil.getTodayStr() df = df.reset_index(level=[0]) del df['index'] table = 'ts2_realtime_quotes' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_today_ticks(self,code,retry_count=3,pause=0): ''' 功能: 获取当前交易日(交易进行中使用)已经产生的分笔明细数据。 参数说明: code:股票代码,即6位数字代码 retry_count : int, 默认3,如遇网络等问题重复执行的次数 pause : int, 默认 0,重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题 返回值说明: time:时间 price:当前价格 pchange:涨跌幅 change:价格变动 volume:成交手 amount:成交金额(元) type:买卖类型【买盘、卖盘、中性盘】 ''' try: df = ts.get_today_ticks(code,retry_count,pause) if df is None: return df = df.replace('--', 0) df['pchange'] = df['pchange'].astype(float) df['date'] = DateUtil.getTodayStr() df['code'] = code df = df.reset_index(level=[0]) del df['index'] table = 'ts2_today_ticks' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_index(self): ''' 功能: 获取大盘指数行情 返回值说明: code:指数代码 name:指数名称 change:涨跌幅 open:开盘点位 preclose:昨日收盘点位 close:收盘点位 high:最高点位 low:最低点位 volume:成交量(手) amount:成交金额(亿元) ''' try: df = ts.get_index() if df is None: return df['date'] = DateUtil.getTodayStr() df = df.reset_index(level=[0]) del df['index'] table = 'ts2_index' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_sina_dd(self,code,date='2018-06-13',vol=400,retry_count=3,pause=0): ''' 功能: 获取大单交易数据,默认为大于等于400手,数据来源于新浪财经。 参数说明: code:股票代码,即6位数字代码 date:日期,格式YYYY-MM-DD vol:手数,默认为400手,输入数值型参数 retry_count : int, 默认3,如遇网络等问题重复执行的次数 pause : int, 默认 0,重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题 返回值说明: code:代码 name:名称 time:时间 price:当前价格 volume:成交手 preprice :上一笔价格 type:买卖类型【买盘、卖盘、中性盘】 ''' try: df = ts.get_sina_dd(code,date,vol,retry_count,pause) if df is None: return df['date'] = date table = 'ts2_sina_dd' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def forecast_data(self,year=2018,quarter=1): ''' 功能: 按年度、季度获取业绩预告数据,接口提供从1998年以后每年的业绩预告数据,需指定年度、季度两个参数。数据在获取的过程中,会打印进度信息(下同)。 参数说明: year:int 年度 e.g:2014 quarter:int 季度 :1、2、3、4,只能输入这4个季度 结果返回的数据属性说明如下: code,代码 name,名称 type,业绩变动类型【预增、预亏等】 report_date,发布日期 pre_eps,上年同期每股收益 range,业绩变动范围 ''' try: df = ts.forecast_data(year, quarter) if df is None: return df['year'] = year df['quarter'] = quarter table = 'ts2_forecast_data' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def xsg_data(self,year=2018,month=None,retry_count=3,pause=0): ''' 功能: 以月的形式返回限售股解禁情况,通过了解解禁股本的大小,判断股票上行的压力。可通过设定年份和月份参数获取不同时段的数据。 参数说明: year:年份,默认为当前年 month:解禁月份,默认为当前月 retry_count:当网络异常后重试次数,默认为3 pause:重试时停顿秒数,默认为0 结果返回的数据属性说明如下: code:股票代码 name:股票名称 date:解禁日期 count:解禁数量(万股) ratio:占总盘比率 ''' try: df = ts.xsg_data(year,month,retry_count,pause) if df is None: return table = 'ts2_xsg_data' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def fund_holdings(self,year=2018,quarter=1,retry_count=3,pause=0): ''' 功能: 获取每个季度基金持有上市公司股票的数据。 参数说明: year:年份,默认为当前年 quarter:季度(只能输入1,2,3,4这个四个数字) retry_count:当网络异常后重试次数,默认为3 pause:重试时停顿秒数,默认为0 结果返回的数据属性说明如下: code:股票代码 name:股票名称 date:报告日期 nums:基金家数 nlast:与上期相比(增加或减少了) count:基金持股数(万股) clast:与上期相比 amount:基金持股市值 ratio:占流通盘比率 ''' try: df = ts.fund_holdings(year,quarter,retry_count,pause) if df is None: return df['year'] = year df['quarter'] = quarter table = 'ts2_fund_holdings' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def new_stocks(self,retry_count=3,pause=0): ''' 功能: 获取IPO发行和上市的时间列表,包括发行数量、网上发行数量、发行价格已经中签率信息等。 参数说明: retry_count:当网络异常后重试次数,默认为3 pause:重试时停顿秒数,默认为0 结果返回的数据属性说明如下: code:股票代码 name:股票名称 ipo_date:上网发行日期 issue_date:上市日期 amount:发行数量(万股) markets:上网发行数量(万股) price:发行价格(元) pe:发行市盈率 limit:个人申购上限(万股) funds:募集资金(亿元) ballot:网上中签率(%) ''' try: df = ts.new_stocks(retry_count,pause) if df is None: return table = 'ts2_new_stocks' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_industry_classified(self): ''' 功能: 在现实交易中,经常会按行业统计股票的涨跌幅或资金进出,本接口按照sina财经对沪深股票进行的行业分类,返回所有股票所属行业的信息。考虑到是一次性在线获取数据,调用接口时会有一定的延时,请在数据返回后自行将数据进行及时存储。sina财经提供的行业分类信息大致如下图所示: 参数说明: 结果返回的数据属性说明如下: code:股票代码 name:股票名称 c_name:行业名称 ''' try: df = ts.get_industry_classified() if df is None: return table='ts2_industry_classified' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_concept_classified(self): ''' 功能: 返回股票概念的分类数据,现实的二级市场交易中,经常会以”概念”来炒作,在数据分析过程中,可根据概念分类监测资金等信息的变动情况。本接口是一次性在线获取数据,调用接口时会有一定的延时,请在数据返回后自行将数据进行及时存储。sina财经提供的概念分类信息大致如下图所示: 参数说明: 结果返回的数据属性说明如下: code:股票代码 name:股票名称 c_name:行业名称 ''' try: df = ts.get_concept_classified() if df is None: return table = 'ts2_concept_classified' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_area_classified(self,file_path=None): ''' 功能: 按地域对股票进行分类,即查找出哪些股票属于哪个省份。 参数说明: file_path:文件路径,默认为None即由TuShare提供,可以设定自己的股票文件路径 结果返回的数据属性说明如下: code:股票代码 name:股票名称 c_name:行业名称 ''' try: df = ts.get_area_classified() if df is None: return table = 'ts2_area_classified' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_sme_classified(self,file_path=None): ''' 功能: 获取中小板股票数据,即查找所有002开头的股票 参数说明: file_path:文件路径,默认为None即由TuShare提供,可以设定自己的股票文件路径 结果返回的数据属性说明如下: code:股票代码 name:股票名称 ''' try: df = ts.get_sme_classified() if df is None: return table = 'ts2_sme_classified' self.storeservice.insert_many(table, df,'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_gem_classified(self,file_path=None): ''' 功能: 获取创业板股票数据,即查找所有300开头的股票 参数说明: file_path:文件路径,默认为None即由TuShare提供,可以设定自己的股票文件路径 结果返回的数据属性说明如下: code:股票代码 name:股票名称 ''' try: df = ts.get_gem_classified() if df is None: return table = 'ts2_gem_classified' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_st_classified(self, file_path=None): ''' 功能: 获取风险警示板股票数据,即查找所有st股票 参数说明: file_path:文件路径,默认为None即由TuShare提供,可以设定自己的股票文件路径 结果返回的数据属性说明如下: code:股票代码 name:股票名称 ''' try: df = ts.get_st_classified() if df is None: return table = 'ts2_st_classified' self.storeservice.insert_many(table, df,'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_hs300s(self, file_path=None): ''' 功能: 获取沪深300当前成份股及所占权重 参数说明: 结果返回的数据属性说明如下: code :股票代码 name :股票名称 date :日期 weight:权重 ''' try: df = ts.get_hs300s() if df is None: return table = 'ts2_hs300s' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_sz50s(self, file_path=None): ''' 功能: 获取上证50成份股 参数说明: 结果返回的数据属性说明如下: code :股票代码 name :股票名称 ''' try: df = ts.get_sz50s() if df is None: return table = 'ts2_sz50s' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_zz500s(self, file_path=None): ''' 功能: 获取中证500成份股 参数说明: 结果返回的数据属性说明如下: code :股票代码 name :股票名称 ''' try: df = ts.get_zz500s() if df is None: return table = 'ts2_zz500s' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_terminated(self, file_path=None): ''' Forbidden 功能: 获取已经被终止上市的股票列表,数据从上交所获取,目前只有在上海证券交易所交易被终止的股票。 参数说明: 结果返回的数据属性说明如下: code:股票代码 name:股票名称 oDate:上市日期 tDate:终止上市日期 ''' return ts.get_terminated() @tick.clock() def get_suspended(self, file_path=None): ''' Forbidden 功能: 获取被暂停上市的股票列表,数据从上交所获取,目前只有在上海证券交易所交易被终止的股票。 参数说明: 结果返回的数据属性说明如下: code:股票代码 name:股票名称 oDate:上市日期 tDate:终止上市日期 ''' return ts.get_suspended() @tick.clock() def get_stock_basics(self, file_path=None): ''' 功能: 获取沪深上市公司基本情况。属性包括: 参数说明: 结果返回的数据属性说明如下: code,代码 name,名称 industry,所属行业 area,地区 pe,市盈率 outstanding,流通股本(亿) totals,总股本(亿) totalAssets,总资产(万) liquidAssets,流动资产 fixedAssets,固定资产 reserved,公积金 reservedPerShare,每股公积金 esp,每股收益 bvps,每股净资 pb,市净率 timeToMarket,上市日期 undp,未分利润 perundp, 每股未分配 rev,收入同比(%) profit,利润同比(%) gpr,毛利率(%) npr,净利润率(%) holders,股东人数 ''' try: df = ts.get_stock_basics() if df is None: return table = 'ts2_stock_basics' # replace will fail #self.storeservice.insert_many(table, df, 'append', True, 'code') self.storeservice.insert_many(table, df, 'replace') return df except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_report_data(self, year=2018, quarter=1): ''' 功能: 按年度、季度获取业绩报表数据。数据获取需要一定的时间,网速取决于您的网速,请耐心等待。结果返回的数据属性说明如下: 参数说明: 结果返回的数据属性说明如下: code,代码 name,名称 esp,每股收益 eps_yoy,每股收益同比(%) bvps,每股净资产 roe,净资产收益率(%) epcf,每股现金流量(元) net_profits,净利润(万元) profits_yoy,净利润同比(%) distrib,分配方案 report_date,发布日期 ''' try: df = ts.get_report_data(year,quarter) if df is None: return df['year'] = year df['quarter'] = quarter table = 'ts2_report_data' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_profit_data(self, year=2018, quarter=1): ''' 功能: 按年度、季度获取盈利能力数据,结果返回的数据属性说明如下: 参数说明: 结果返回的数据属性说明如下: code,代码 name,名称 roe,净资产收益率(%) net_profit_ratio,净利率(%) gross_profit_rate,毛利率(%) net_profits,净利润(万元) esp,每股收益 business_income,营业收入(百万元) bips,每股主营业务收入(元) ''' try: df = ts.get_profit_data(year, quarter) if df is None: return df['year'] = year df['quarter'] = quarter table = 'ts2_profit_data' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def profit_data(self, year=2018, top=25, retry_count=3, pause=0): ''' 功能: 每到季报、年报公布的时段,就经常会有上市公司利润分配预案发布,而一些高送转高分红的股票往往会成为市场炒作的热点。及时获取和统计高送转预案的股票是参与热点炒作的关键,TuShare提供了简洁的接口,能返回股票的送转和分红预案情况。 参数说明: year : 预案公布的年份,默认为2014 top :取最新n条数据,默认取最近公布的25条 retry_count:当网络异常后重试次数,默认为3 pause:重试时停顿秒数,默认为0 返回值说明: code:股票代码 name:股票名称 year:分配年份 report_date:公布日期 divi:分红金额(每10股) shares:转增和送股数(每10股) ''' try: df = ts.profit_data(year, top=100) if df is None: return df['year'] = year table = 'ts2_pre_profit_data' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_operation_data(self, year=2018, quarter=1): ''' 功能: 按年度、季度获取营运能力数据,结果返回的数据属性说明如下: 参数说明: 结果返回的数据属性说明如下: code,代码 name,名称 arturnover,应收账款周转率(次) arturndays,应收账款周转天数(天) inventory_turnover,存货周转率(次) inventory_days,存货周转天数(天) currentasset_turnover,流动资产周转率(次) currentasset_days,流动资产周转天数(天) ''' try: df = ts.get_operation_data(year, quarter) if df is None: return df['year'] = year df['quarter'] = quarter table = 'ts2_operation_data' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_growth_data(self, year=2018, quarter=1): ''' 功能: 按年度、季度获取成长能力数据,结果返回的数据属性说明如下: 参数说明: 结果返回的数据属性说明如下: code,代码 name,名称 mbrg,主营业务收入增长率(%) nprg,净利润增长率(%) nav,净资产增长率 targ,总资产增长率 epsg,每股收益增长率 seg,股东权益增长率 ''' try: df = ts.get_growth_data(year, quarter) if df is None: return df['year'] = year df['quarter'] = quarter table = 'ts2_growth_data' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_debtpaying_data(self, year=2018, quarter=1): ''' 功能: 按年度、季度获取偿债能力数据,结果返回的数据属性说明如下 参数说明: 结果返回的数据属性说明如下: code,代码 name,名称 currentratio,流动比率 quickratio,速动比率 cashratio,现金比率 icratio,利息支付倍数 sheqratio,股东权益比率 adratio,股东权益增长率 ''' try: df = ts.get_debtpaying_data(year, quarter) if df is None: return df = df.replace('--', 0) df['currentratio'] = df['currentratio'].astype(float) df['quickratio'] = df['quickratio'].astype(float) df['cashratio'] = df['cashratio'].astype(float) df['icratio'] = df['icratio'].astype(float) df['sheqratio'] = df['sheqratio'].astype(float) df['adratio'] = df['adratio'].astype(float) df['year'] = year df['quarter'] = quarter table = 'ts2_debtpaying_data' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_cashflow_data(self, year=2018, quarter=1): ''' 功能: 按年度、季度获取现金流量数据,结果返回的数据属性说明如下: 参数说明: 结果返回的数据属性说明如下: code,代码 name,名称 cf_sales,经营现金净流量对销售收入比率 rateofreturn,资产的经营现金流量回报率 cf_nm,经营现金净流量与净利润的比率 cf_liabilities,经营现金净流量对负债比率 cashflowratio,现金流量比率 ''' try: df = ts.get_cashflow_data(year, quarter) if df is None: return df['year'] = year df['quarter'] = quarter table = 'ts2_cashflow_data' self.storeservice.insert_many(table, df) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_deposit_rate(self): ''' 功能: 存款利率 参数说明: 结果返回的数据属性说明如下: date :变动日期 deposit_type :存款种类 rate:利率(%) ''' try: df = ts.get_deposit_rate() if df is None: return df = df.replace('--', 0) df['rate'] = df['rate'].astype(float) table = 'ts2_deposit_rate' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_loan_rate(self): ''' 功能: 贷款利率 参数说明: 结果返回的数据属性说明如下: date :执行日期 loan_type :存款种类 rate:利率(%) ''' try: df = ts.get_loan_rate() if df is None: return df = df.replace('--', 0) df['rate'] = df['rate'].astype(float) table = 'ts2_loan_rate' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_rrr(self): ''' 功能: 存款准备金率 参数说明: 结果返回的数据属性说明如下: date :变动日期 before :调整前存款准备金率(%) now:调整后存款准备金率(%) changed:调整幅度(%) ''' try: df = ts.get_rrr() if df is None: return df = df.replace('--', 0) df['changed'] = df['changed'].astype(float) table = 'ts2_rrr' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_money_supply(self): ''' 功能: 货币供应量 参数说明: 结果返回的数据属性说明如下: month :统计时间 m2 :货币和准货币(广义货币M2)(亿元) m2_yoy:货币和准货币(广义货币M2)同比增长(%) m1:货币(狭义货币M1)(亿元) m1_yoy:货币(狭义货币M1)同比增长(%) m0:流通中现金(M0)(亿元) m0_yoy:流通中现金(M0)同比增长(%) cd:活期存款(亿元) cd_yoy:活期存款同比增长(%) qm:准货币(亿元) qm_yoy:准货币同比增长(%) ftd:定期存款(亿元) ftd_yoy:定期存款同比增长(%) sd:储蓄存款(亿元) sd_yoy:储蓄存款同比增长(%) rests:其他存款(亿元) rests_yoy:其他存款同比增长(%) ''' try: df = ts.get_money_supply() if df is None: return df = df.replace('--', 0) df['m2'] = df['m2'].astype(float) df['m2_yoy'] = df['m2_yoy'].astype(float) df['m1'] = df['m1'].astype(float) df['m1_yoy'] = df['m1_yoy'].astype(float) df['m0'] = df['m0'].astype(float) df['m0_yoy'] = df['m0_yoy'].astype(float) df['cd'] = df['cd'].astype(float) df['cd_yoy'] = df['cd_yoy'].astype(float) df['qm'] = df['qm'].astype(float) df['qm_yoy'] = df['qm_yoy'].astype(float) df['ftd'] = df['ftd'].astype(float) df['ftd_yoy'] = df['ftd_yoy'].astype(float) df['sd'] = df['sd'].astype(float) df['sd_yoy'] = df['sd_yoy'].astype(float) df['rests'] = df['rests'].astype(float) df['rests_yoy'] = df['rests_yoy'].astype(float) table = 'ts2_money_supply' self.storeservice.insert_many(table, df,'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_money_supply_bal(self): ''' 功能: 货币供应量(年底余额) 参数说明: 结果返回的数据属性说明如下: year :统计年度 m2 :货币和准货币(亿元) m1:货币(亿元) m0:流通中现金(亿元) cd:活期存款(亿元) qm:准货币(亿元) ftd:定期存款(亿元) sd:储蓄存款(亿元) rests:其他存款(亿元) ''' try: df = ts.get_money_supply_bal() if df is None: return df = df.replace('--', 0) df['m2'] = df['m2'].astype(float) df['m1'] = df['m1'].astype(float) df['m0'] = df['m0'].astype(float) df['cd'] = df['cd'].astype(float) df['qm'] = df['qm'].astype(float) df['ftd'] = df['ftd'].astype(float) df['sd'] = df['sd'].astype(float) df['rests'] = df['rests'].astype(float) table = 'ts2_money_supply_bal' self.storeservice.insert_many(table, df,'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_gdp_year(self): ''' 功能: 国内生产总值(年度) 参数说明: 结果返回的数据属性说明如下: year :统计年度 gdp :国内生产总值(亿元) pc_gdp :人均国内生产总值(元) gnp :国民生产总值(亿元) pi :第一产业(亿元) si :第二产业(亿元) industry :工业(亿元) cons_industry :建筑业(亿元) ti :第三产业(亿元) trans_industry :交通运输仓储邮电通信业(亿元) lbdy :批发零售贸易及餐饮业(亿元) ''' try: df = ts.get_gdp_year() if df is None: return table = 'ts2_gdp_year' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_gdp_quarter(self): ''' 功能: 国内生产总值(年度) 参数说明: 结果返回的数据属性说明如下: quarter :季度 gdp :国内生产总值(亿元) gdp_yoy :国内生产总值同比增长(%) pi :第一产业增加值(亿元) pi_yoy:第一产业增加值同比增长(%) si :第二产业增加值(亿元) si_yoy :第二产业增加值同比增长(%) ti :第三产业增加值(亿元) ti_yoy :第三产业增加值同比增长(%) ''' try: df = ts.get_gdp_quarter() if df is None: return table = 'ts2_gdp_quarter' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_gdp_for(self): ''' 功能: 三大需求对GDP贡献 参数说明: 结果返回的数据属性说明如下: year :统计年度 end_for :最终消费支出贡献率(%) for_rate :最终消费支出拉动(百分点) asset_for :资本形成总额贡献率(%) asset_rate:资本形成总额拉动(百分点) goods_for :货物和服务净出口贡献率(%) goods_rate :货物和服务净出口拉动(百分点) ''' try: df = ts.get_gdp_for() if df is None: return table = 'ts2_gdp_for' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_gdp_pull(self): ''' 功能: 三大产业对GDP拉动 参数说明: 结果返回的数据属性说明如下: year :统计年度 gdp_yoy :国内生产总值同比增长(%) pi :第一产业拉动率(%) si :第二产业拉动率(%) industry:其中工业拉动(%) ti :第三产业拉动率(%) ''' try: df = ts.get_gdp_pull() if df is None: return table = 'ts2_gdp_pull' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_gdp_contrib(self): ''' 功能: 三大产业贡献率 参数说明: 结果返回的数据属性说明如下: year :统计年度 gdp_yoy :国内生产总值 pi :第一产业献率(%) si :第二产业献率(%) industry:其中工业献率(%) ti :第三产业献率(%) ''' try: df = ts.get_gdp_contrib() if df is None: return table = 'ts2_gdp_contrib' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_cpi(self): ''' 功能: 居民消费价格指数¶ 参数说明: 结果返回的数据属性说明如下: month :统计月份 cpi :价格指数 ''' try: df = ts.get_cpi() if df is None: return table = 'ts2_cpi' self.storeservice.insert_many(table, df, 'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_ppi(self): ''' 功能: 工业品出厂价格指数 参数说明: 结果返回的数据属性说明如下: month :统计月份 ppiip :工业品出厂价格指数 ppi :生产资料价格指数 qm:采掘工业价格指数 rmi:原材料工业价格指数 pi:加工工业价格指数 cg:生活资料价格指数 food:食品类价格指数 clothing:衣着类价格指数 roeu:一般日用品价格指数 dcg:耐用消费品价格指数 ''' try: df = ts.get_ppi() if df is None: return table = 'ts2_ppi' self.storeservice.insert_many(table, df,'replace') except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass @tick.clock() def get_latest_news(self,top=5, show_content=True): ''' 功能: 即时新闻 参数说明: top:int,显示最新消息的条数,默认为80条 show_content:boolean,是否显示新闻内容,默认False 结果返回的数据属性说明如下: classify :新闻类别 title :新闻标题 time :发布时间 url :新闻链接 content:新闻内容(在show_content为True的情况下出现) ''' df = None try: if time.time() - AppConfig.latest_news_pulltime > 1000: top = 80 df = ts.get_latest_news(top, show_content) if df is None: logging.info('df is None') return table = 'ts2_latest_news' latest_pulltime = None pulltime = None dropindex = -1 df.sort_values(by="time", ascending=False) for i in range(0,len(df)): pulltime = df.iloc[i]['time'] pulltime = DateUtil.string_toTimestamp(DateUtil.format_date(pulltime)) if i == 0: latest_pulltime = pulltime if pulltime <= AppConfig.latest_news_pulltime: #remove dropindex = i print('dropindex:',dropindex) break if dropindex != -1: df = df.drop(range(dropindex,len(df),1)) if len(df) > 0 : self.storeservice.insert_many(table, df) AppConfig.write_news_pulltime(latest_pulltime,True) except IOError as err: logging.error("OS|error: {0}".format(err)) except OperationalError as err: logging.error("OS|error: {0}".format(err)) else: pass def get_notices(self,code='600000', date='2018-06-15'): ''' 功能: 信息地雷 参数说明: code:股票代码 date:信息公布日期 结果返回的数据属性说明如下: title:信息标题 type:信息类型 date:公告日期 url:信息内容URL ''' return ts.get_notices() def get_guba_sina(self,show_content=False): ''' 功能: 新浪股吧 参数说明: show_content:boolean,是否显示内容,默认False 结果返回的数据属性说明如下: title, 消息标题 content, 消息内容(show_content=True的情况下) ptime, 发布时间 rcounts,阅读次数 ''' return ts.guba_sina(show_content) def get_top_list(self,date='2018-06-15',retry_count=3, pause=0): ''' 功能: 每日龙虎榜列表 参数说明: date:日期,格式YYYY-MM-DD retry_count:当网络异常后重试次数,默认为3 pause:重试时停顿秒数,默认为0 结果返回的数据属性说明如下: title, 消息标题 content, 消息内容(show_content=True的情况下) ptime, 发布时间 rcounts,阅读次数 ''' return ts.top_list(date,retry_count,pause) def get_cap_tops(self,days=5,retry_count=3, pause=0): ''' 功能: 个股上榜统计 获取近5、10、30、60日个股上榜统计数据,包括上榜次数、累积购买额、累积卖出额、净额、买入席位数和卖出席位数。 参数说明: days:统计周期5、10、30和60日,默认为5日 retry_count:当网络异常后重试次数,默认为3 pause:重试时停顿秒数,默认为0 结果返回的数据属性说明如下: code:代码 name:名称 count:上榜次数 bamount:累积购买额(万) samount:累积卖出额(万) net:净额(万) bcount:买入席位数 scount:卖出席位数 ''' return ts.cap_tops(days,retry_count,pause) def get_broker_tops(self,days=5,retry_count=3, pause=0): ''' 功能: 营业部上榜统计 获取营业部近5、10、30、60日上榜次数、累积买卖等情况。 参数说明: days:统计周期5、10、30和60日,默认为5日 retry_count:当网络异常后重试次数,默认为3 pause:重试时停顿秒数,默认为0 结果返回的数据属性说明如下: broker:营业部名称 count:上榜次数 bamount:累积购买额(万) bcount:买入席位数 samount:累积卖出额(万) scount:卖出席位数 top3:买入前三股票 ''' return ts.broker_tops(days,retry_count,pause) def get_inst_tops(self,days=5,retry_count=3, pause=0): ''' 功能: 个股上榜统计 获取近5、10、30、60日个股上榜统计数据,包括上榜次数、累积购买额、累积卖出额、净额、买入席位数和卖出席位数。 参数说明: days:统计周期5、10、30和60日,默认为5日 retry_count:当网络异常后重试次数,默认为3 pause:重试时停顿秒数,默认为0 结果返回的数据属性说明如下: code:代码 name:名称 bamount:累积买入额(万) bcount:买入次数 samount:累积卖出额(万) scount:卖出次数 net:净额(万) ''' return ts.inst_tops(days,retry_count,pause) def get_inst_detail(self,retry_count=3, pause=0): ''' 功能: 个股上榜统计 获取近5、10、30、60日个股上榜统计数据,包括上榜次数、累积购买额、累积卖出额、净额、买入席位数和卖出席位数。 参数说明: retry_count:当网络异常后重试次数,默认为3 pause:重试时停顿秒数,默认为0 结果返回的数据属性说明如下: code:代码 name:名称 date:交易日期 bamount:机构席位买入额(万) samount:机构席位卖出额(万) type:类型 ''' return ts.inst_detail(retry_count,pause)
tfn.start() def appender_calendar_task(thread_name,arr,store,futunewsshistory): tfn = MyThread2(thread_name,job_calendar_appender,store,arr,futunewsshistory) tfn.start() def once_individuals_task(thread_name,arr,store,futunewsshistory): tfn = MyThread2(thread_name,job_once_individuals,store,arr,futunewsshistory) tfn.start() storeservice = MysqlService() mongodbutil = MongodbUtil(AppConfig.mongodb_ip, AppConfig.mongodb_port, AppConfig.mongodb_collection) mongodbutil_futunnlive = MongodbUtil(AppConfig.mongodb_ip, AppConfig.mongodb_port, AppConfig.mongodb_collection_futunnlive) mongodbutil_calendar = MongodbUtil(AppConfig.mongodb_ip, AppConfig.mongodb_port, AppConfig.mongodb_collection_calendar) mongodbutil_cash = MongodbUtil(AppConfig.mongodb_ip, AppConfig.mongodb_port, AppConfig.mongodb_collection_cash) mongodbutil_balancesheet = MongodbUtil(AppConfig.mongodb_ip, AppConfig.mongodb_port, AppConfig.mongodb_collection_balancesheet) mongodbutil_income = MongodbUtil(AppConfig.mongodb_ip, AppConfig.mongodb_port, AppConfig.mongodb_collection_income) mongodbutil_companyinfo = MongodbUtil(AppConfig.mongodb_ip, AppConfig.mongodb_port, AppConfig.mongodb_collection_companyinfo) mongodbutil_dividend = MongodbUtil(AppConfig.mongodb_ip, AppConfig.mongodb_port, AppConfig.mongodb_collection_dividend) futunews = FutunnService(mongodbutil,mongodbutil_futunnlive,mongodbutil_calendar, mongodbutil_cash,mongodbutil_balancesheet,mongodbutil_income, mongodbutil_companyinfo,mongodbutil_dividend) ret_arr = storeservice.find_all_stockcodes_exclude_nodata()
def setUpClass(cls): cls.storeservice = MysqlService()