def get_today_tick_ave(code, ave=None): try: dtick = ts.get_today_ticks(code) df = dtick if len(dtick.index) > 0: p_now = dtick['price'].values[0] * 100 ep = dtick['amount'].sum() / dtick['volume'].sum() if not ave == None: if p_now > ave and ep > ave: print ("GOLD:%s ep:%s UP:%s!!! A:%s %s !!!" % (code, ep, p_now, ave, get_now_time())) elif p_now > ave and ep < ave: print ("gold:%s ep:%s UP:%s! A:%s %s !" % (code, ep, p_now, ave, get_now_time())) elif p_now < ave and ep > ave: print ("down:%s ep:%s Dow:%s? A:%s %s ?" % (code, ep, p_now, ave, get_now_time())) else: print ("DOWN:%s ep:%s now:%s??? A:%s %s ???" % (code, ep, p_now, ave, get_now_time())) else: if ep > ave: print ("GOLD:%s ep:%s UP:%s!!! A:%s %s !!!" % (code, ep, p_now, ave, get_now_time())) else: print ("down:%s ep:%s now:%s??? A:%s %s ?" % (code, ep, p_now, ave, get_now_time())) else: df = ts.get_realtime_quotes(code) print "name:%s op:%s price:%s" % (df['name'].values[0], df['open'].values[0], df['price'].values[0]) # print df return df except (IOError, EOFError, KeyboardInterrupt) as e: print("Except:%s" % (e))
def updateData(self): self.stk_quotes = ts.get_realtime_quotes(self.stk_code) self.stk_ticks = ts.get_today_ticks(self.stk_code).sort_values(by="time") #df = df.sort("time") #df = ts.get_realtime_quotes(self.stk_code) self.setWindowTitle(str(self.stk_quotes['date'][0] + ' 分笔明细图')) self.repaint()
def get_multiday_ave_compare_silent(code, dayl='10'): dtick = ts.get_today_ticks(code) d_hist = ema.getdata_ema_trend_silent(code, dayl, 'd') # print d_hist day_t = ema.get_today() if day_t in d_hist.index: dl = d_hist.drop(day_t).index else: dl = d_hist.index # print dl # print dl ep_list = [] for da in dl.values: # print code,da td = ts.get_tick_data(code, da) # print td if not type(td) == types.NoneType: ep = td['amount'].sum() / td['volume'].sum() ep_list.append(ep) # print ("D: %s P: %s" % (da[-5:], ep)) ave = ema.less_average(ep_list) if len(dtick.index) > 0: ep = dtick['amount'].sum() / dtick['volume'].sum() p_now = dtick['price'].values[0] * 100 if p_now > ave or ep > ave: print ("GOLD:%s ep:%s UP:%s!!! A:%s %s !!!" % (code, ep, p_now, ave, get_now_time())) # elif p_now > ave and ep < ave: # print ("gold:%s ep:%s UP:%s! A:%s %s !" % (code, ep, p_now, ave, get_now_time())) # elif p_now < ave and ep > ave: # print ("down:%s ep:%s Dow:%s? A:%s %s ?" % (code, ep, p_now, ave, get_now_time())) return True else: if p_now < ave and ep < ave: print ("DOWN:%s ep:%s now:%s??? A:%s %s ???" % (code, ep, p_now, ave, get_now_time())) return False
def __init__(self,code): self.df=ts.get_today_ticks(code) #转换str为时间格式,便于下面用来比较时间的大小 self.df['time']=self.df['time'].map(lambda x:datetime.datetime.strptime(str(x),'%H:%M:%S')) print('\n') self.total= self.df['volume'].sum()
def ticktoday(code): dftick = ts.get_today_ticks(code) dftick.insert(0,'uploadtime',nowtime) dftick.insert(0,'code',code) dftick.to_sql('mkt_tick',engine,if_exists='append') counttick = cursor.execute('show columns from mkt_tick like \'tick_id\'') if counttick == 0: insertidtick()
def main(): df = ts.get_today_ticks('300104') total_vol=df['volume'].sum()*100 print('总成交股数') big_deal=df[df['volume']>=100]['volume'].sum()*100 print('大于100手的总和',big_deal) percent=float(big_deal)/total_vol*100 print('大单占比',percent) print(df['volume'].value_count())
def main(): #regression import tushare as ts df=ts.get_today_ticks('000030') xArr,yArr = loadDataSet('ex0.txt') ws = standRegres(xArr,yArr) print ws #plotStandRegres(xArr,yArr,ws) print calcCorrcoef(xArr,yArr,ws) #lwlr lwlrTestPlot(xArr,yArr,k=1)
def get_trading_records(code): try: df = ts.get_today_ticks(code) j_datas = json.loads(df.to_json(orient='records')) trading_records = [] from models import TradingRecord for j_data in j_datas: trading_records.append(TradingRecord(code, j_data)) return trading_records except IOError: pass
def realtime(self, id): # all_stock=ts.get_today_all() # print(all_stock) df = ts.get_realtime_quotes(id) # print(df[['time','name','price','bid','ask','volume']]) # print(df.head()) price_change = ts.get_today_ticks(id) print(price_change[['time', 'change', 'type', 'volume']]) big_share = ts.get_sina_dd(id, date='2016-04-01') print(big_share[['time', 'code', 'price', 'preprice', 'volume', 'type']])
def sub_process_ratio(i,q): print "Start" try: df=ts.get_today_ticks(i) #print 'len of df ',len(df) #print df if len(df)==0: print "Pause of exchange" return i,'pause' except Exception,e: print e print "ERROR" return id,'pause'
def _fill_today_bars(self): today = datetime.date.today().isoformat() if is_holiday(today): # do nothing if holiday return today_bars = {} for identifier in self.__identifiers: try: df = ts.get_today_ticks(identifier) today_bars[identifier] = get_bar_list(df, self.__frequency, None) except Exception, e: logger.error(e)
def get_info(self,id): print id try: df=ts.get_today_ticks(id) print 'len of df ',len(df) #print df if len(df)==0: print "Pause of exchange" return id,'pause' except Exception,e: print e print "ERROR" return id,'pause'
def cmp_top(ticks): if ticks is None: print 'no' return None try: today = ts.get_today_ticks(id).sort('amount', ascending=False) except: return None sticks = ticks.sort('amount', ascending=False).head(20) sticks = sticks.reset_index() today = today.reset_index() top = sticks.ix[0] top_today = today.ix[0] return [(round((top.price - top_today.price)/top.price, 3)), round(top.price, 3), round(top_today.price, 3), top.amount, top_today.amount]
def get_tick(stockCode=None, date=None): """ 根据股票列表的股票代码获取当日/指定日期历史分笔 Return -------- DataFrame """ tick_data = '' if date != None and date != '': tick_data = ts.get_tick_data(stockCode, date) else: tick_data = ts.get_today_ticks(stockCode) if not tick_data.dropna(axis=0, how='any', thresh=None).empty: tick_data.insert(0, 'code', stockCode) #插入股票代码字段 return tick_data
def get_all_hot(): try: gold = {} goldl = [] # df = ts.get_today_all() # top = df[df['changepercent'] > 6] # top = top[top['changepercent'] <11] # print "top:", len(top['code']) codes="000893,002351,000705,002451,002515,002279,002679,002761,600895,000532,002113,002438,600235,600210,600857".split(',') print codes # for code in top['code']: for code in codes: dtick = ts.get_today_ticks(code) d_hist = ema.getdata_ema_trend(code, '10', 'd') # print d_hist day_t = ema.get_today() # if len(dtick.index) == 0: # dtick=d_hist[] if day_t in d_hist.index: dl = d_hist.drop(day_t).index else: dl = d_hist.index # print dl # print dl ep_list = [] for da in dl.values: # print da td = ts.get_tick_data(code, da) # print td if len(td) > 0: ep = td['amount'].sum() / td['volume'].sum() ep_list.append(ep) # print ("D: %s P: %s"%(da,ep)) total_ave = ema.less_average(ep_list) all_max=max(ep_list) if len(dtick.index) > 0: ep = dtick['amount'].sum() / dtick['volume'].sum() if ep >= all_max: gold[code] = d_hist goldl.append(code) print ("Gold:%s ep:%s ave:%s max:%s" % (code, ep, total_ave,all_max)) except (IOError, EOFError, KeyboardInterrupt): # print "key" # print "break" print "why" return
def getBigDeal(self, code,vol): df = ts.get_today_ticks(code) t= df[df['volume']>vol] s=df[df['amount']>100000000] print('\n') if t.size!=0: print("Big volume") print(self.base[self.base['code']==str(code)]['name'].values[0]) print(t) if s.size!=0: print("Big amount: ") print(self.base[self.base['code']==str(code)]['name'].values[0]) print(s) r=df[df['volume']>vol*10] if r.size!=0: print("Super amount:") print(self.base[self.base['code']==str(code)]['name'].values[0]) print(r)
def _fill_today_bars(self): today = datetime.date.today().isoformat() if is_holiday(today): # do nothing if holiday return elif datetime.date.today().weekday() in [5, 0]: return # #James: # if datetime.datetime.now().hour * 60 + 30 < 9*60 + 30: # return today_bars = {} for identifier in self.__identifiers: try: df = ts.get_today_ticks(identifier) today_bars[identifier] = get_bar_list(df, self.__frequency, None) except Exception, e: logger.error(e)
def get_multiday_ave_compare(code, dayl='10'): dtick = ts.get_today_ticks(code) d_hist = ema.getdata_ema_trend(code, dayl, 'd') # print d_hist day_t = ema.get_today() if d_hist is not None: if day_t in d_hist.index: dl = d_hist.drop(day_t).index else: dl = d_hist.index else: return 0 # print dl # print dl ep_list = [] for da in dl.values: # print da td = ts.get_tick_data(code, da) # print td if not type(td) == types.NoneType: ep = td['amount'].sum() / td['volume'].sum() ep_list.append(ep) print("D: %s P: %s" % (da[-5:], ep)) ave = ema.less_average(ep_list) if len(dtick.index) > 0: ep = dtick['amount'].sum() / dtick['volume'].sum() p_now = dtick['price'].values[0] * 100 if p_now > ave and ep > ave: print("GOLD:%s ep:%s UP:%s!!! A:%s %s !!!" % (code, ep, p_now, ave, cct.get_now_time())) elif p_now > ave and ep < ave: print("gold:%s ep:%s UP:%s! A:%s %s !" % (code, ep, p_now, ave, cct.get_now_time())) elif p_now < ave and ep > ave: print("down:%s ep:%s Dow:%s? A:%s %s ?" % (code, ep, p_now, ave, cct.get_now_time())) else: print("DOWN:%s ep:%s now:%s??? A:%s %s ???" % (code, ep, p_now, ave, cct.get_now_time())) return ave
def get_today_tick_data(code, retry_count=RETRY_COUNT, pause=PAUSE): """获取个股以往交易历史的分笔数据明细,通过分析分笔数据,可以大致判断资金的进出情况。""" logger.info('Begin get today tick data, code is: %s, date is: %s.' % (code, today_line)) try: data_df = ts.get_today_ticks(code, retry_count, pause) except Exception as e: logger.exception( 'Error get today tick data, code is :%s, date is %s.' % (code, today_line)) else: if data_df is not None and not data_df.empty: data = data_df.values today_tick_data_queue.put((code, today_line, data)) logger.info( 'Success get today tick data, code is :%s, date is %s.' % (code, today_line)) else: logger.warn( 'Empty get today tick data, code is :%s, date is %s.' % (code, today_line))
def get_trade_data(self): if(self.trade_data_type == 'hq'): df = ts.get_hist_data(code=self.stock_code, start=self.start_date, end=self.end_date, ktype=self.stock_K_type, retry_count=self.retry_count, pause=self.pause) elif(self.trade_data_type == 'rd'): df = ts.get_h_data(code=self.stock_code, start=self.start_date, end=self.end_date, autype=self.autype, index=self.index, retry_count=self.retry_count, pause=self.pause) elif(self.trade_data_type == 'rq'): df = ts.get_today_all() elif(self.trade_data_type == 'ht'): df = ts.get_tick_data(code=self.stock_code, date=self.date, retry_count=self.retry_count, pause=self.pause) elif(self.trade_data_type == 'rt'): df = ts.get_realtime_quotes(symbols=self.stock_code) elif(self.trade_data_type == 'cht'): df = ts.get_today_ticks(code=self.stock_code, retry_count=self.retry_count, pause=self.pause) elif(self.trade_data_type == 'index'): df = ts.get_index() elif(self.trade_data_type == 'btd'): df = ts.get_sina_dd(code=self.stock_code, date=self.date, vol=self.vol, retry_count=self.retry_count, pause=self.pause) if(df is not None): return df else: return -1
def volume_calculation(code, start, end): ''' 计算某个股票的某个时间段的累计成交量 :param start: 开始日期 :param end: 结束日期 :return: 成交量,占每天比例 ''' df = ts.get_today_ticks(code) # 转换str为时间格式,便于下面用来比较时间的大小 df['time'] = df['time'].map(lambda x: datetime.datetime.strptime(str(x), '%H:%M:%S')) total = df['volume'].sum() start = datetime.datetime.strptime(start, '%H:%M:%S') end = datetime.datetime.strptime(end, '%H:%M:%S') new_df = df[(df['time'] >= start) & (df['time'] < end)] volume = new_df['volume'].sum() rate = round(volume * 1.00 / total * 100, 2) return volume, rate
def get_dangrifenbi_data(self): ''' 参数说明: code:股票代码,即6位数字代码 retry_count : int, 默认3,如遇网络等问题重复执行的次数 pause : int, 默认 0,重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题 返回值说明: time:时间 price:当前价格 pchange:涨跌幅 change:价格变动 volume:成交手 amount:成交金额(元) type:买卖类型【买盘、卖盘、中性盘】 ''' drifenbi_data = ts.get_today_ticks(code=self.code, retry_count=self.retry_count, pause=self.pause) print(drifenbi_data) return drifenbi_data
def xtick_real_downsub(xcod): ''' 中国A股,tick 历史或real实时 tick 分笔数据下载子程序 会自动将中文type,替换成 英文:中性盘:norm;买盘:buy 卖盘:sell 【输入】 xcod,股票代码 xtim,日期字符串,当xtim为空时,下载的是当天 实时 tick数据 【输出】 df,股票 tick 数据 数据列格式: time,price,change,volume,amount,type ''' xd = ts.get_today_ticks(xcod) dn = len(xd) # print('n',dn) # 跳过无数据 日期 if dn > 10: xd['type'] = xd['type'].str.replace(u'中性盘', 'norm') xd['type'] = xd['type'].str.replace(u'买盘', 'buy') xd['type'] = xd['type'].str.replace(u'卖盘', 'sell') # xd.to_csv('tmp\\'+xcod+'_'+xtim+'.csv',index=False,encoding='utf') else: xd = [] # return xd
def xtick_real_downsub(xcod): ''' 中國A股,tick 歷史或real即時 tick 分筆資料下載副程式 會自動將中文type,替換成 英文:中性盤:norm;買盤:buy 賣盤:sell 【輸入】 xcod,股票代碼 xtim,日期字串,當xtim為空時,下載的是當天 即時 tick資料 【輸出】 df,股票 tick 資料 資料列格式: time,price,change,volume,amount,type ''' xd = ts.get_today_ticks(xcod) dn = len(xd) # print('n',dn) # 跳過無數據 日期 if dn > 10: xd['type'] = xd['type'].str.replace(u'中性盤', 'norm') xd['type'] = xd['type'].str.replace(u'買盤', 'buy') xd['type'] = xd['type'].str.replace(u'賣盤', 'sell') # xd.to_csv('tmp\\'+xcod+'_'+xtim+'.csv',index=False,encoding='utf') else: xd = [] # return xd
def get_today_tick_ave(code, ave=None): try: dtick = ts.get_today_ticks(code) df = dtick if len(dtick.index) > 0: p_now = dtick['price'].values[0] * 100 ep = dtick['amount'].sum() / dtick['volume'].sum() if not ave == None: if p_now > ave and ep > ave: print("GOLD:%s ep:%s UP:%s!!! A:%s %s !!!" % (code, ep, p_now, ave, get_now_time())) elif p_now > ave and ep < ave: print("gold:%s ep:%s UP:%s! A:%s %s !" % (code, ep, p_now, ave, get_now_time())) elif p_now < ave and ep > ave: print("down:%s ep:%s Dow:%s? A:%s %s ?" % (code, ep, p_now, ave, get_now_time())) else: print("DOWN:%s ep:%s now:%s??? A:%s %s ???" % (code, ep, p_now, ave, get_now_time())) else: if ep > ave: print("GOLD:%s ep:%s UP:%s!!! A:%s %s !!!" % (code, ep, p_now, ave, get_now_time())) else: print("down:%s ep:%s now:%s??? A:%s %s ?" % (code, ep, p_now, ave, get_now_time())) else: df = ts.get_realtime_quotes(code) print "name:%s op:%s price:%s" % (df['name'].values[0], df['open'].values[0], df['price'].values[0]) # print df return df except (IOError, EOFError, KeyboardInterrupt) as e: print("Except:%s" % (e))
def ticks(code, source="spider", date=None, cons=None): """返回date日期的分笔数据 :param source: :param code: str: 股票代码,如 603655 :param date: str: 日期,如 2018-03-15 :param cons: tushare的api连接 :return: """ if not date: date = datetime.now().date().__str__() TODAY = datetime.now().date().__str__() # 统一 ticks 的输出结果 def _unify_out(ticks, date): ticks = ticks[['time', 'price', 'volume', 'type']] ticks['datetime'] = ticks['time'].apply( lambda x: datetime.strptime(date + " " + x, "%Y-%m-%d %H:%M:%S")) ticks['vol'] = ticks['volume'] type_convert = {"买盘": 0, "卖盘": 1, "中性盘": 2, "0": 2} ticks['type'] = ticks["type"].apply(lambda x: type_convert[str(x)]) ticks.drop(['time', 'volume'], axis=1, inplace=True) ticks.sort_values('datetime', inplace=True) ticks.reset_index(drop=True, inplace=True) return ticks[['datetime', 'price', 'vol', 'type']] if source == "spider" and date == TODAY: ticks = ts.get_today_ticks(code=code) ticks = _unify_out(ticks, date=TODAY) elif source == "spider" and date != TODAY: ticks = ts.get_tick_data(code=code, date=date) ticks = _unify_out(ticks, date=date) else: if not cons: cons = ts.get_apis() ticks = ts.tick(code=code, conn=cons, date=date) return ticks
def stat(code): """区间成交量统计""" df = ts.get_today_ticks(code=code, ) df['amount'] = df['price'] * df['vol'] * 100 print(df.head(100)) buy = df[df['type'] == '买入'] sale = df[df['type'] == '卖出'] s = sale.groupby(['price'])['vol'].sum() b = buy.groupby(['price'])['vol'].sum() t = df.groupby(['price'])['vol'].sum() print('买入总成交:', buy['vol'].sum(), '手') print('卖出总成交:', sale['vol'].sum(), '手') print('总买入:', buy['amount'].sum()) print('总卖出:', sale['amount'].sum()) print('净买入额:', (buy['amount'].sum() - sale['amount'].sum()) / 10000, '万') fig = subplots.make_subplots(rows=3, cols=1) traceS = go.Bar(x=list(s.to_dict().values()), y=list(s.to_dict().keys()), name='卖出', marker=dict(color='green'), orientation='h') traceB = go.Bar(x=list(b.to_dict().values()), y=list(b.to_dict().keys()), name='买入', marker=dict(color='red'), orientation='h') # traceT # = go.Bar(x = list(t.to_dict().keys()),y = list(t.to_dict().values()),name='总数',marker=dict(color='blue')) fig.append_trace(traceS, 1, 1) fig.append_trace(traceB, 2, 1) fig.add_trace(traceB, row=3, col=1) fig.add_trace(traceS, row=3, col=1) fig.update_layout(barmode='stack') fig.show()
def update_stock_tick(self,security): ''' 目前仅能更新当日的股票历史分笔数据 :param security: :return: ''' stock = self._session.query(Stock).filter(Stock.security == security).one() # 获取股票基本信息 df = ts.get_today_ticks(security) df = df.set_index('time') for time in df.index: temp = datetime.datetime.today().strftime('%Y-%m-%d')+' '+time date = datetime.datetime.strptime(temp, "%Y-%m-%d %H:%M:%S") stock_tick_item = Tick_data(id = security+'#'+temp, time = date, price = df.loc[time]['price'], change = df.loc[time]['change'], volume = df.loc[time]['volume'], amount = df.loc[time]['amount'], type = unicode(df.ix[time]['type'])) try: self._session.query(Tick_data).filter(Tick_data.id == security+'#'+temp).one() except: stock.tick_data.append(stock_tick_item) self._session.commit()
if x < 0.01: x1 = str(x) + ' ***' else: x1 = str(x) + ' ***' b.append(x1) a.P值.apply(lambda x: x[:3]) temp['P值'] = b temp.columns a = temp.drop('t 值', axis=1) a = a.set_index('参数') b = a.stack() c = pd.DataFrame({'dfdf': b}) c.to_excel('tem.xlsx') df = ts.get_today_ticks('000852') df1 = ts.get_tick_data('000852', date='2018-04-09') z = df.type == '买盘' df.time[1] df.sort_values('time', inplace=True) df.groupby('type').mean() t = df[df.volume > 400] junzhi = (df.price * df.volume).sum() / df.volume.sum() t1 = df[(df.type == '买盘') & (df.volume > 400)] junzhi1 = (t1.price * t1.volume).sum() / t1.volume.sum() import time
def generateline(stocknumber, Type, startdate, enddate, interval): startdata = startdate.encode("ascii").replace("/", "-").replace( "\n", "") #convert to tushare readable date enddata = enddate.encode("ascii").replace("/", "-").replace("\n", "") array = df() #print startdata #print enddata current_time = time.strftime("%Y/%m/%d") if Type == "分笔".decode("utf-8"): if startdate != current_time: array = ts.get_tick_data(stocknumber, date=startdata) #分笔 if array is None: return array = array.sort_values("time") date = array["time"].tolist() amount = array["amount"].tolist() atype = array["type"].tolist() price = array["price"].tolist() flag = ["bar" for i in date] for idx, val in enumerate(atype): #if卖盘,交易变成负数 if val == "卖盘": amount[idx] = -amount[idx] if val == "中性盘": #if中性盘,则忽略. Might have a problem with this part?? amount[idx] = 0 returnarray = zip(date, amount, flag, price) return returnarray else: array = ts.get_today_ticks(stocknumber) #Tushare里今日分笔和历史分笔需要分别对待 if array is None: return array = array.sort_values("time") date = array["time"].tolist() amount = array["amount"].tolist() atype = array["type"].tolist() flag = ["bar" for i in date] for idx, val in enumerate(atype): if val == "卖盘".decode("utf-8"): amount[idx] = -amount[idx] if val == "中性盘".decode("utf-8"): amount[idx] = 0 returnarray = zip(date, amount, flag) return returnarray if interval != "qfq" and interval != "hfq": #正常历史k线 if Type != "Kline": array = ts.get_k_data(stocknumber, start=startdata, end=enddata, ktype=interval) if array is None: return Type1 = firstletter(Type).encode("ascii") target = array[Type1].tolist() date = array["date"].tolist() returnarray = zip(date, target) return returnarray else: array = ts.get_k_data(stocknumber, start=startdata, end=enddata, ktype=interval) if array is None: return Date = array["date"].tolist() Open = array["open"].tolist() Close = array["close"].tolist() High = array["high"].tolist() Low = array["low"].tolist() Candlestick = zip(*[Date, Open, Close, Low, High]) return Candlestick else: if Type != "Kline": # 复权 array = ts.get_h_data(stocknumber, start=startdata, end=enddata, autype=interval) if array is None: return Type1 = firstletter(Type).encode("ascii") array = array.sort_index() target = array[Type1].tolist() date = array.index.format() returnarray = zip(date, target) return returnarray else: array = ts.get_h_data(stocknumber, start=startdata, end=enddata, autype=interval) if array is None: return array = array.sort_index() Date = array.index.format() Open = array["open"].tolist() Close = array["close"].tolist() High = array["high"].tolist() Low = array["low"].tolist() Candlestick = zip(*[Date, Open, Close, Low, High]) return Candlestick
# encoding: utf-8 import tushare as ts import pandas as pd import numpy as np if __name__ == '__main__': #当日历史分笔 #get_today_ticks(code,retry_count,pause) #返回:时间、当前价格、涨跌幅、价格变动、成交金额(元)、买卖类型 df = ts.get_today_ticks('002410',3,0.001) print df.head(100)
import tushare as ts del ts # 历史分笔 a = ts.get_tick_data('000005', date='2018-12-24') help(ts) # 当日历史分 b = ts.get_today_ticks('601333', date='2017-01-09') # 实时分笔 ts.get_realtime_quotes('000581') # 历史分笔 和 当日历史分 返回结果 time:时间 price:成交价格 pchange:涨跌幅 change:价格变动 volume:成交手 amount:成交金额(元) type:买卖类型【买盘、卖盘、中性盘】 import easyquotation import tf from urllib.request import urlretrieve f = open('SHA.csv', 'r') for line in f:
""" import tushare as ts import csv stockID = '002219' file_csv = open(stockID + 'TodayTicks.csv', 'wb+') spamwriter = csv.writer(file_csv,dialect='excel') spamwriter.writerow(['time', 'price', 'pchange', 'change', 'volume', 'amount', 'type']) fileHistory_csv = open(stockID + 'HistoryTicks.csv', 'wb+') spamwriterHistory = csv.writer(fileHistory_csv,dialect='excel') spamwriterHistory.writerow(['time', 'price', 'change', 'volume', 'amount', 'type']) df = ts.get_today_ticks('002219') dfHistory = ts.get_tick_data('002219', date='2016-08-16') total = 0 neutral = 0 for indexH, rowH in dfHistory.iterrows(): #print(rowH[5]) spamwriterHistory.writerow([rowH[0], rowH[1], rowH[2], rowH[3], rowH[4], rowH[5].decode('utf-8').encode('gb2312')]) for index, row in df.iterrows(): print(row[6]) spamwriter.writerow([row[0], row[1], row[2], row[3], row[4], row[5], row[6].encode('gbk')]) if row[6] == '买盘'.decode('utf-8'): total += row[5] if row[6] == '卖盘'.decode('utf-8'): total -= row[5] else:
# -*- coding:utf-8 -*- import tushare as ts # import sys # sys.path.append("..") # from JohhnsonUtil import commonTips as cct import pandas as pd import tables #import pandas.io.pytables code='601608' # df=ts.get_hist_data('601608') df= ts.get_today_ticks('601608') # .sort_index(ascending=True).dropna() print df[:1] store=pd.HDFStore('store.h5',mode='w',format='table', complevel=9, complib='blosc') # df.index=df.index.astype('datetime64') # store[code]=df # df.to_hdf('store.h5','sz'+code,mode='w',format='table',complevel=9, complib='blosc',data_columns=df.columns) # store=pd.HDFStore('store.h5',mode='r',format='table') store.put('sz'+code,df) # h5f = pd.HDFStore('store.h5',mode='r') dd=store.select('sz'+code) print dd[:5] import sys sys.exit(0) '''
def today_ticks_tushare(code): df = tushare.get_today_ticks('%06d' % code) df['time'] = df['time'].str.slice(start=0, stop=5) df = df.drop_duplicates('time').iloc[::-1].reset_index() return df_map(df, {'tick': 'time', 'price': 'price', 'volume': 'amount'})
def getTodayStock(request): id = request.GET.get('id') df = ts.get_today_ticks(id) df = df[::-1] df = df.to_json(orient='index') return HttpResponse(simplejson.dumps(df, ensure_ascii=False))
''' 参数说明 code:股票代码,即6位数字代码 retry_count : int, 默认3,如遇网络等问题重复执行的次数 pause : int, 默认 0,重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题 返回值说明: time:时间 price:当前价格 pchange:涨跌幅 change:价格变动 volume:成交手 amount:成交金额(元) type:买卖类型【买盘、卖盘、中性盘】 ''' df =ts.get_today_ticks('600808') print(df.head(10)) # 大盘指数行情列表 ''' code:指数代码 name:指数名称 change:涨跌幅 open:开盘点位 preclose:昨日收盘点位 close:收盘点位 high:最高点位 low:最低点位 volume:成交量(手) amount:成交金额(亿元)
# -*-coding=utf-8-*- __author__ = 'aqua' import tushare as ts import talib as ta import pandas as pd from sqlalchemy import create_engine code = '600153' df_ticket = ts.get_today_ticks(code) df_ticket = df_ticket.iloc[::-1] print(df_ticket) engine = create_engine('mysql://*****:*****@127.0.0.1/stocking?charset=utf8') df_ticket.to_sql('tickets', engine, if_exists='append')
def getDataUpdate(stock_selected, date, volume): #df = ts.get_sina_dd(stock_selected,date,vol=volume) if is_today(date): df = ts.get_today_ticks(stock_selected) else: df = ts.get_tick_data(stock_selected, date=date, src='tt') #code,name,time,volume, preprice, type #df=df_1[df_1['volume']>=volume] #print(df.head()) _time = ['9:25:0'] _volume = [0] _price = [0] all_time = [] all_volume = [] all_price = [] buy_time = [] buy_volume = [] buy_price = [] sell_time = [] sell_volume = [] sell_price = [] if df is None: length = 0 else: length = len(df.time) i = 0 idx = 0 while (idx < length): if (df.type[idx] == '买盘' and df.volume[idx] >= volume): i = i + 1 buy_time.append(df.time[idx]) buy_volume.append(df.volume[idx]) buy_price.append(df.price[idx]) _time.append(df.time[idx]) _volume.append(df.volume[idx]) _volume[i] = float(_volume[i]) + float(_volume[i - 1]) _price.append(df.price[idx]) all_time.append(df.time[idx]) all_volume.append(df.volume[idx]) all_price.append(df.price[idx]) #_buy += float(df.volume[idx])*float(df.price[idx])/10000.0 elif (df.type[idx] == '卖盘' and df.volume[idx] >= volume): i = i + 1 sell_time.append(df.time[idx]) sell_volume.append(0 - df.volume[idx]) sell_price.append(df.price[idx]) _time.append(df.time[idx]) _volume.append(0 - float(df.volume[idx])) _volume[i] = float(_volume[i]) + float(_volume[i - 1]) _price.append(df.price[idx]) all_time.append(df.time[idx]) all_volume.append(0 - float(df.volume[idx])) all_price.append(df.price[idx]) idx += 1 df1 = pd.DataFrame({'time': _time, 'volume': _volume, 'price': _price}) df2 = pd.DataFrame({ 'time': all_time, 'volume': all_volume, 'price': all_price }) #print(df2) df3 = pd.DataFrame({ 'time': buy_time, 'volume': buy_volume, 'price': buy_price }) df4 = pd.DataFrame({ 'time': sell_time, 'volume': sell_volume, 'price': sell_price }) return df1, df2, df3, df4
def getRealTimeInfor(stockCode): df = ts.get_today_ticks(stockCode) print df.groupby('type')['volume','amount'].sum() df = ts.get_realtime_quotes(stockCode) print df.loc[:,['price','pre_close','open','high','low']]
def getTodayTick(code): return ts.get_today_ticks()
import tushare import sys code = sys.argv[1] s = tushare.get_today_ticks(code) s = s.sort("amount") s.to_csv("%s.csv" % code, encoding="utf-8")
def tick_today(symbol): return ts.get_today_ticks(symbol)
def generateline(stocknumber,Type,startdate,enddate,interval): startdata = startdate.encode("ascii").replace("/","-").replace("\n","") #convert to tushare readable date enddata = enddate.encode("ascii").replace("/","-").replace("\n","") #print startdata #print enddata current_time = time.strftime("%Y/%m/%d") if Type == "分笔".decode("utf-8"): if startdate!=current_time: array = ts.get_tick_data(stocknumber, date = startdata)#分笔 if array is None: return array = array.sort_values("time") date = array["time"].tolist() amount = array["amount"].tolist() atype = array["type"].tolist() price = array["price"].tolist() flag = ["bar" for i in date] for idx,val in enumerate(atype):#if卖盘,交易变成负数 if val == "卖盘": amount[idx] = -amount[idx] if val == "中性盘":#if中性盘,则忽略. Might have a problem with this part?? amount[idx] = 0 returnarray = zip(date,amount,flag,price) return returnarray else: array = ts.get_today_ticks(stocknumber)#Tushare里今日分笔和历史分笔需要分别对待 if array is None: return array = array.sort_values("time") date = array["time"].tolist() amount = array["amount"].tolist() atype = array["type"].tolist() flag = ["bar" for i in date] for idx, val in enumerate(atype): if val == "卖盘".decode("utf-8"): amount[idx] = -amount[idx] if val == "中性盘".decode("utf-8"): amount[idx] = 0 returnarray = zip(date, amount, flag) return returnarray if Type=="季度饼图".decode("utf-8"): datestr = startdate.split("/") thisyear = datestr[0] df2 = ts.top10_holders(code=stocknumber, gdtype="1") test = df2[1]["quarter"].tolist() df_ready = df2[1] idxlist = [] for idx, val in enumerate(test): a = val.split("-") if a[0] == thisyear: # print a[0],idx idxlist.append(idx) thing = df_ready.loc[idxlist] thing = thing.sort_values(["quarter", "name"]) # print a[0],id name = thing["name"].tolist() value = thing["hold"].tolist() quarter = thing["quarter"].tolist() namearray = [name[i:i + 10] for i in xrange(0, len(name), 10)] valuearray = [value[j:j + 10] for j in xrange(0, len(value), 10)] quarterarray = [quarter[k:k + 10] for k in xrange(0, len(quarter), 10)] flag = ["pie" for i in namearray] num = [len(value) for k in namearray] returnarray = zip(namearray,valuearray,quarterarray,flag,num) return returnarray if interval!="qfq" and interval!="hfq": if interval=="1min" or interval=="5min" or interval=="15min" or interval=="30min" or interval=="60min": df = ts.get_tick_data(stocknumber, date=startdata) df.sort_values("time") a = startdata + " " + df["time"] df["time"] = a df["time"] = pd.to_datetime(a) df = df.set_index("time") price_df = df["price"].resample(interval).ohlc() price_df = price_df.dropna() vols = df["volume"].resample(interval).sum() #relevant data processing algorithm taken from Jimmy, Creator of Tushare vols = vols.dropna() vol_df = pd.DataFrame(vols, columns=["volume"]) amounts = df["amount"].resample(interval).sum() amounts = amounts.dropna() amount_df = pd.DataFrame(amounts, columns=["amount"]) newdf = price_df.merge(vol_df, left_index=True, right_index=True).merge(amount_df, left_index=True, right_index=True) if Type != "Kline": Type1 = firstletter(Type).encode("ascii") target = newdf[Type1].tolist() date = newdf.index.format() returnarray = zip(date, target) return returnarray else: Date = newdf.index.format() Open = newdf["open"].tolist() Close = newdf["close"].tolist() High = newdf["high"].tolist() Low = newdf["low"].tolist() Candlestick = zip(*[Date, Open, Close, Low, High]) return Candlestick #正常历史k线 if Type!="Kline": array = ts.get_k_data(stocknumber, start=startdata, end=enddata, ktype=interval) if array is None: return Type1 = firstletter(Type).encode("ascii") target = array[Type1].tolist() date = array["date"].tolist() returnarray = zip(date,target) return returnarray else: array = ts.get_k_data(stocknumber, start=startdata, end=enddata, ktype=interval) if array is None: return Date = array["date"].tolist() Open = array["open"].tolist() Close = array["close"].tolist() High = array["high"].tolist() Low = array["low"].tolist() Candlestick = zip(*[Date,Open,Close,Low,High]) return Candlestick else: if Type!="Kline": # 复权 array = ts.get_h_data(stocknumber, start = startdata, end = enddata, autype= interval) if array is None: return Type1 = firstletter(Type).encode("ascii") array = array.sort_index() target = array[Type1].tolist() date = array.index.format() returnarray = zip(date, target) return returnarray else : array = ts.get_h_data(stocknumber, start=startdata, end=enddata, autype=interval) if array is None: return array = array.sort_index() Date = array.index.format() Open = array["open"].tolist() Close = array["close"].tolist() High = array["high"].tolist() Low = array["low"].tolist() Candlestick = zip(*[Date, Open, Close, Low, High]) return Candlestick
def generate_stock_line(stock_id, Type, start_date, end_date, interval): start_data = start_date.replace("/", "-").replace( "\n", "") #convert to tushare readable date end_data = end_date.replace("/", "-").replace("\n", "") current_time = time.strftime("%Y/%m/%d") if Type == "分笔": if start_date != current_time: array = ts.get_tick_data(stock_id, date=start_data) #分笔 if array is None: return array = array.sort_values("time") date = array["time"].tolist() amount = array["amount"].tolist() atype = array["type"].tolist() price = array["price"].tolist() flag = ["bar" for i in date] for idx, val in enumerate(atype): #if卖盘,交易变成负数 if val == "卖盘": amount[idx] = -amount[idx] if val == "中性盘": #if中性盘,则忽略. Might have a problem with this part?? amount[idx] = 0 returnarray = zip(date, amount, flag, price) return returnarray else: array = ts.get_today_ticks(stock_id) #Tushare里今日分笔和历史分笔需要分别对待 if array is None: return array = array.sort_values("time") date = array["time"].tolist() amount = array["amount"].tolist() atype = array["type"].tolist() flag = ["bar" for i in date] for idx, val in enumerate(atype): if val == "卖盘": amount[idx] = -amount[idx] if val == "中性盘": amount[idx] = 0 returnarray = zip(date, amount, flag) return returnarray if Type == "季度饼图": datestr = start_date.split("/") thisyear = datestr[0] df2 = ts.top10_holders(code=stock_id, gdtype="1") test = df2[1]["quarter"].tolist() df_ready = df2[1] idxlist = [] for idx, val in enumerate(test): a = val.split("-") if a[0] == thisyear: # print a[0],idx idxlist.append(idx) thing = df_ready.loc[idxlist] thing = thing.sort_values(["quarter", "name"]) # print a[0],id name = thing["name"].tolist() value = thing["hold"].tolist() quarter = thing["quarter"].tolist() namearray = [name[i:i + 10] for i in xrange(0, len(name), 10)] valuearray = [value[j:j + 10] for j in xrange(0, len(value), 10)] quarterarray = [quarter[k:k + 10] for k in xrange(0, len(quarter), 10)] flag = ["pie" for i in namearray] num = [len(value) for k in namearray] returnarray = zip(namearray, valuearray, quarterarray, flag, num) return returnarray if interval != "qfq" and interval != "hfq": if interval == "1min" or interval == "5min" or interval == "15min" or interval == "30min" or interval == "60min": df = ts.get_tick_data(stock_id, date=start_data) df.sort_values("time") a = start_data + " " + df["time"] df["time"] = a df["time"] = pd.to_datetime(a) df = df.set_index("time") price_df = df["price"].resample(interval).ohlc() price_df = price_df.dropna() vols = df["volume"].resample(interval).sum( ) #relevant data processing algorithm taken from Jimmy, Creator of Tushare vols = vols.dropna() vol_df = pd.DataFrame(vols, columns=["volume"]) amounts = df["amount"].resample(interval).sum() amounts = amounts.dropna() amount_df = pd.DataFrame(amounts, columns=["amount"]) newdf = price_df.merge(vol_df, left_index=True, right_index=True).merge(amount_df, left_index=True, right_index=True) if Type != "Kline": Type1 = firstletter(Type) target = newdf[Type1].tolist() date = newdf.index.format() returnarray = zip(date, target) return returnarray else: Date = newdf.index.format() Open = newdf["open"].tolist() Close = newdf["close"].tolist() High = newdf["high"].tolist() Low = newdf["low"].tolist() Candlestick = zip(*[Date, Open, Close, Low, High]) return Candlestick #正常历史k线 if Type != "Kline": array = ts.get_k_data(stock_id, start=start_data, end=end_data, ktype=interval) if array is None: return Type1 = firstletter(Type) target = array[Type1].tolist() date = array["date"].tolist() returnarray = zip(date, target) return returnarray else: array = ts.get_k_data(stock_id, start=start_data, end=end_data, ktype=interval) if array is None: return Date = array["date"].tolist() Open = array["open"].tolist() Close = array["close"].tolist() High = array["high"].tolist() Low = array["low"].tolist() Candlestick = zip(*[Date, Open, Close, Low, High]) return Candlestick else: if Type != "Kline": # 复权 array = ts.get_h_data(stock_id, start=start_data, end=end_data, autype=interval) if array is None: return Type1 = firstletter(Type) array = array.sort_index() target = array[Type1].tolist() date = array.index.format() returnarray = zip(date, target) return returnarray else: array = ts.get_h_data(stock_id, start=start_data, end=end_data, autype=15) if array is None: return array = array.sort_index() Date = array.index.format() Open = array["open"].tolist() Close = array["close"].tolist() High = array["high"].tolist() Low = array["low"].tolist() # list_array = [Date, Open, Close, Low, High] Candlestick = zip(*[Date, Open, Close, Low, High]) return Candlestick
ts.get_hist_data('600848',ktype='60') #获取60分钟k线数据 ts.get_hist_data('sh')#获取上证指数k线数据,其它参数与个股一致,下同 ts.get_hist_data('sz')#获取深圳成指k线数据 ts.get_hist_data('hs300')#获取沪深300指数k线数据 ts.get_hist_data('sz50')#获取上证50指数k线数据 ts.get_hist_data('zxb')#获取中小板指数k线数据 ts.get_hist_data('cyb')#获取创业板指数k线数据 # 2.历史复权数据 # 可提供股票上市以来所有历史数据,默认为前复权 ts.get_h_data('002337') #前复权 ts.get_h_data('002337',autype='hfq') #后复权 ts.get_h_data('002337',autype=None) #不复权 ts.get_h_data('002337',start='2015-01-01',end='2015-03-16') #两个日期之间的前复权数据 ts.get_h_data('399106', index=True) #深圳综合指数 # 3.一次性获取当前交易所有股票的行情数据,如果是节假日,即为上一交易日 ts.get_today_all() # 4.实时交易数据 ts.get_realtime_quotes('sh') ts.get_realtime_quotes('000581') # 5.当日分笔 df = ts.get_today_ticks('601333') # 6.历史分笔 df = ts.get_tick_data('600848',date='2014-01-09') # 7.获取所有指数实时行情列表 df = ts.get_index()
import tushare as ts df = ts.get_index() print df df = ts.get_today_ticks('601333') print df.head(10)
# Load stock real-time data import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties import tushare as ts import datetime as dt print('Tushare Version ' + ts.__version__) code_num = '000636' try: rdf = ts.get_realtime_quotes(code_num) # Realtime DF print(rdf) tdf = ts.get_today_ticks(code_num) # Tick DF print(tdf) except: print('Download exception') # rdf.index = pd.to_datetime(rdf.date,format="%Y-%m-%d %H:%M") # stk_today = rdf[rdf.index.date==dt.datetime(2018,8,7).date()].copy() # tdf.index = pd.to_datetime(tdf.time,format="%H:%M:%S") tdf = tdf[tdf['time'] > '09:26:00'] tdf.index = pd.to_timedelta(tdf['time']) mdf = tdf.resample('1Min', closed='left').mean().dropna() if True: font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=16) fig, ax = plt.subplots(figsize=(20, 16)) plt.subplot(211) mdf['price'].plot(use_index=True, style='r-',
import matplotlib.pyplot as plt import pandas as pd mystock = \ '603063.SH,' \ '000993.SZ,' \ '002797.SH,' \ '002008.SZ,' \ '601519.SH' trig_volume = 209 dg = ts.get_realtime_quotes('002008') #Single stock symbol show1 = dg[['code', 'name', 'price', 'bid', 'ask', 'volume', 'amount', 'time']] # df = ts.get_tick_data('002008', date='2019-09-19',src='tt') # df = ts.get_hist_data('601519', '2019-09-12','2019-09-17') df = ts.get_today_ticks('002008') buy1 = df[(df['volume'] > trig_volume) & (df['change'] > 0)] buy2 = df[(df['type'] == '买盘') & (df['volume'] > trig_volume) & (df['change'] == 0)] buy = pd.concat([buy1, buy2]) sale1 = df[(df['volume'] > trig_volume) & (df['change'] < 0)] sale2 = df[(df['type'] == '卖盘') & (df['volume'] > trig_volume) & (df['change'] == 0)] sale = pd.concat([sale1, sale2]) buy_amount = buy.volume * buy.price buy_average_price = buy_amount.sum() / buy.volume.sum() sale_amount = sale.volume * sale.price
draw(fileName, code, name[index]) def tradeOne(fileName, code, name): df = pd.read_csv(fileName) test = test1(df, code, name) test.trade() test.test() if __name__ == '__main__': # df = getTodayAll() # df.to_excel("today.xls") code = "601398" otherStyleTime = datetime.datetime.now().strftime("%Y%m%d") df = ts.get_today_ticks(code) df.to_excel("%s-%s.xls" % (code, otherStyleTime), encoding="utf-8") # todayAll() # fileName = r"%s\todayAll\20180205154614.csv"%(dir) # data1= teststd(fileName) # test20(fileName) # data2 =ver8(fileName) # data3= pd.merge(data1, data2, on=["b"]) # print(data3) # data3.to_csv("%s3.cvs", encoding='utf-8') # jiaolongmairuList(fileName,'20180119') fileName = r"getAmt20180205161141ver8.cvs" # otherStyleTime = datetime.datetime.now().strftime("%Y%m%d") # otherStyleTime = "20180205"
# 获取个股以往交易历史的分笔数据明细,通过分析分笔数据,可以大致判断资金的进出情况。在使用过程中,对于获取股票某一阶段的历史分笔数据,需要通过加入交易日参数并append到一个DataFrame或者直接append到本地同一个文件里。历史分笔接口只能获取当前交易日之前的数据,当日分笔历史数据请调用get_today_ticks() # 接口或者在当日18点后通过本接口获取。 # 获取当日历史分笔数据:get_today_ticks() """ 参数说明: code:股票代码,即6位数字代码 retry_count : int, 默认3,如遇网络等问题重复执行的次数 pause : int, 默认 0,重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题 返回值说明: time:时间 price:当前价格 pchange:涨跌幅 change:价格变动 volume:成交手 amount:成交金额(元) type:买卖类型【买盘、卖盘、中性盘】 """ df = ts.get_today_ticks('300274') # print(df.head(10)) # 获取当前交易日(交易进行中使用)已经产生的分笔明细数据。 print("999999999") # 二、 使用finance.yahoo.com这个网站。这个网站常被用来进行金融股票数据的搜索。 import pandas_datareader as pdr alibaba = pdr.get_data_yahoo('BABA') print(alibaba.head())
import tushare as ts import logging import selenium fname = '300377' fdate = '2018-12-13' #df = ts.get_tick_data(fname,date='2018-12-12',src='tt' ) #df.head(10) #当日历史分笔 df = ts.get_today_ticks(fname) df.head(10) df.to_csv(r'D:\python学习\金融数据\get_today_ticks' + fname + '_' + fdate + '.csv', sep=',', header=True, index=True, encoding='utf_8_sig') df = ts.get_realtime_quotes(fname) df.to_csv(r'D:\python学习\金融数据\get_realtime_quotes' + fname + '_' + fdate + '.csv', sep=',', header=True, index=True, encoding='utf_8_sig') print(df)
def get_today_ticks(self, conns): self.base = Base() self.financial_data = conns['financial_data'] self.df = ts.get_today_ticks(self.code) self.base.batchwri(self.df, 'dangrilishifenbi', self.financial_data)
# -*- coding:utf-8 -*- import tushare as ts # import sys # sys.path.append("..") # from JohnsonUtil import commonTips as cct import pandas as pd import tables #import pandas.io.pytables code = '601608' # df=get_kdate_data('601608') df = ts.get_today_ticks('601608') # .sort_index(ascending=True).dropna() print(df[:1]) store = pd.HDFStore('store.h5', mode='w', format='table', complevel=9, complib='blosc') # df.index=df.index.astype('datetime64') # store[code]=df # df.to_hdf('store.h5','sz'+code,mode='w',format='table',complevel=9, complib='blosc',data_columns=df.columns) # store=pd.HDFStore('store.h5',mode='r',format='table') store.put('sz' + code, df) # h5f = pd.HDFStore('store.h5',mode='r') dd = store.select('sz' + code) print(dd[:5]) import sys sys.exit(0)
import tushare as ts import stock.emacount as ema # get now hot 10 date_top = {} # df = ts.get_today_all() # top=df[df['changepercent'] > 9.9] # for code in top['code']: tick_mean = [] for code in ["601608"]: dtick = ts.get_today_ticks(code) d_hist = ema.getdata_ema_trend(code, "10", "d") # print d_hist day_t = ema.get_today() if day_t in d_hist.index: dl = d_hist.drop(day_t).index else: dl = d_hist.index # print dl # print dl for da in dl.values: # print da td = ts.get_tick_data(code, da) # print td ep = td["amount"].sum() / td["volume"].sum() print ("D: %s P: %s" % (da, ep)) ep = dtick["amount"].sum() / dtick["volume"].sum() print "today: ", ep # print top_count
def getDailyData(stock="", date=""): if stock[0] == "2" or stock[0] == "9": print "Pass Stock" return True else: if bool(stock) == False: return{'errcode':-1,'errmsg':'need stockCode'} else: jsonDir = os.path.join(config.dataRootDailyTrade, stock) if os.path.isdir(jsonDir): pass else: os.mkdir(jsonDir) if bool(date) == False & bool(stock): #不带日期的话就检索今天的数据 jsonFile = os.path.join(config.dataRootDailyTrade, stock, dateStr + ".json") if os.path.isfile(jsonFile): size = os.path.getsize(jsonFile) #print 'There are %f K' % (size / 1024.0) if size >60000 : print(stock+" Pass") return True else: try: data = ts.get_today_ticks(stock) data.to_json(jsonFile, orient='records', force_ascii =False) print(stock) print(date) return True except: print("scan error " + stock ) else: try: data = ts.get_today_ticks(stock) data.to_json(jsonFile, orient='records', force_ascii =False) return True except: print("scan error " + stock) elif bool(date) & bool(stock): #按日期获取 isWorkDay = isTradeDay(date) if isWorkDay: jsonFile = os.path.join(config.dataRootDailyTrade, stock, date + ".json") ### 判断该日期下的文件是否大于100KB 是默认历史数据已获取,反正重新获取 if os.path.isfile(jsonFile): size = os.path.getsize(jsonFile) #print 'There are %f K' % (size / 1024.0) if size >60000 : print(stock+" Pass") return True else: try: data = ts.get_tick_data(stock, date=date) data.to_json(jsonFile, orient='records', force_ascii =False) print(stock) print(date) return True except: print("scan error " + stock + "--" + date) catchError(stock, date) else: try: data = ts.get_tick_data(stock, date=date) data.to_json(jsonFile, orient='records', force_ascii =False) print(stock) print(date) return True except: print("scan error "+stock +"--"+date) catchError(stock, date) else: print ("Weekend Pass") pass
def get_today_ticks(engine, stock_code): df = ts.get_today_ticks(stock_code) df.head(10) df.to_sql('today_ticks', engine, if_exists='append')