def get_quote_apis(): client_config = get_client_config() quote_client = QuoteClient(client_config) quote_client.get_market_status(Market.US) quote_client.get_briefs(symbols=['AAPL', '00700', '600519'], include_ask_bid=True, right=QuoteRight.BR) quote_client.get_timeline(['AAPL'], period=TimelinePeriod.DAY, include_hour_trading=True) quote_client.get_bars(['AAPL'])
def get_quote(begin_time=None, Symbol=None): client_config = get_client_config() quote_client = QuoteClient(client_config) #timeArray = time.strptime("2000-01-01 00:00:00","%Y-%m-%d %H:%M:%S") #begin_time=int(time.mktime(timeArray))*10**3 return quote_client.get_bars('600570', period=BarPeriod.ONE_MINUTE, begin_time=begintimestamp)
def get_quote(): client_config = get_client_config() quote_client = QuoteClient(client_config) # return quote_client.get_market_status(Market.ALL) #股市开市情况 return quote_client.get_briefs(symbols=['AAPL', '00700', '600519'], include_ask_bid=True, right=QuoteRight.BR) #return quote_client.get_briefs(symbols=['00700', '600519'], include_ask_bid=True, right=QuoteRight.BR) # return quote_client.get_timeline('AAPL', period=TimelinePeriod.DAY, include_hour_trading=True) return quote_client.get_bars('600570')
def get_quote(): client_config = get_client_config() quote_client = QuoteClient(client_config) #quote_client.get_market_status(Market.ALL) #quote_client.get_briefs(symbols=['AAPL', '00700', '600519'], include_ask_bid=True, right=QuoteRight.BR) #quote_client.get_briefs(symbols=['00700', '600519'], include_ask_bid=True, right=QuoteRight.BR) #quote_client.get_timeline('AAPL', period=TimelinePeriod.5MIN, begin_time='20181213', include_hour_trading=True) # today_time = time.strftime('%Y-%m-%d 00:00:00',time.localtime(time.time())) timeArray = time.strptime("2000-01-01 00:00:00", "%Y-%m-%d %H:%M:%S") begin_time = int(time.mktime(timeArray)) * 10**3 return quote_client.get_bars('600570', period=BarPeriod.ONE_MINUTE, begin_time=begin_time)
def get_bars_from_cache(quote_client: QuoteClient, symbols, period=BarPeriod.DAY, begin_time=-1, end_time=-1, right=QuoteRight.BR, limit=10000, lang=None): """ 走文件缓存,加快多次访问速度 :param quote_client: :param symbols: :param period: :param begin_time: :param end_time: :param right: :param limit: :param lang: :return: """ md5 = tuple_2_md5( [symbols, period, begin_time, end_time, right, limit, lang]) # 从文件缓存获取数据 data = read_pd_from_cache(md5) if data is not None: return data # 调用API获取 if data is None: data = quote_client.get_bars(symbols=symbols, period=period, begin_time=begin_time, end_time=end_time, limit=limit) if not data.empty: write_pd_2_cache(data, md5) # data = offset_by_date(data) return data
def get_quote(): client_config = get_client_config() quote_client = QuoteClient(client_config) return quote_client.get_bars('600570')
class RqdataClient: """ Client for querying history data from RQData. """ def __init__(self): """""" logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s', filemode='a', ) logger = logging.getLogger('TigerOpenApi') client_config = get_client_config() self.openapi_client = QuoteClient(client_config, logger=logger) self.inited = False self.symbols = set() def init(self, username="", password=""): """""" if self.inited: return True self.__init__() self.inited = True return True def to_rq_symbol(self, symbol: str, exchange: Exchange): return symbol def get_data(self, symbol, period=BarPeriod.ONE_MINUTE, limit=1300, begin=-1, end=-1): return self.openapi_client.get_bars(symbols=[symbol], period=period, limit=limit, begin_time=begin, end_time=end) def query_history(self, req: HistoryRequest): """ Query history bar data from RQData. """ symbol = req.symbol exchange = req.exchange interval = req.interval start = req.start end = req.end # rq_symbol = self.to_rq_symbol(symbol, exchange) # if rq_symbol not in self.symbols: # return None rq_interval = INTERVAL_VT2RQ.get(interval) if not rq_interval: return None # For adjust timestamp from bar close point (RQData) to open point (VN Trader) adjustment = INTERVAL_ADJUSTMENT_MAP[interval] # For querying night trading period data end += adjustment final = end.timestamp() calendar_name = EXCHANGE_CALENDAR[exchange] calendar = get_calendar(calendar_name) schedule = calendar.schedule(start, end) df = None for _,s in schedule.iterrows(): df_data = self.openapi_client.get_bars([symbol], period=rq_interval, limit=5000, begin_time=s.market_open.to_pydatetime().timestamp() * 1000, end_time=s.market_close.to_pydatetime().timestamp() * 1000) if df_data.__len__() > 0: print("query_history:symbol={0},从{1}到{2},一共获取到{3}条数据".format( symbol, datetime.fromtimestamp(df_data['time'].iloc[0]/1000), datetime.fromtimestamp(df_data['time'].iloc[-1]/1000), df_data.__len__())) if df is None: df = df_data else: df = pd.concat([df, df_data]) if df is None: return [] if df.__len__() > 0: print("query_history:symbol={0},从{1}到{2},一共获取到{3}条数据".format( symbol, datetime.fromtimestamp(df['time'].iloc[0]/1000), datetime.fromtimestamp(df['time'].iloc[-1]/1000), df.__len__())) # 获取总时间间隔 # interval_total = end - start # unix_start = start.timestamp() * 1000 # unix_end = end.timestamp() * 1000 # bars_start = start.timestamp() # bars_end = bars_start + timedelta(3).total_seconds() # bars_end = bars_end if bars_end < final else final # df = None # while bars_start < final: # df_data = self.openapi_client.get_bars([symbol], # period=rq_interval, # limit=5000, # begin_time=bars_start * 1000, # end_time=bars_end * 1000) # if df_data.__len__() > 0: # print("query_history:symbol={0},从{1}到{2},一共获取到{3}条数据".format( # symbol, # datetime.fromtimestamp(df_data['time'].iloc[0]/1000), # datetime.fromtimestamp(df_data['time'].iloc[-1]/1000), # df_data.__len__())) # bars_start = bars_end # bars_end = bars_end + timedelta(3).total_seconds() # bars_end = bars_end if bars_end < final else final # if df_data.empty: # continue # if df is None: # df = df_data # else: # df = pd.concat([df, df_data]) # print(df) # if df is None: # return [] # if df.__len__() > 0: # print("query_history:symbol={0},从{1}到{2},一共获取到{3}条数据".format( # symbol, # datetime.fromtimestamp(df['time'].iloc[0]/1000), # datetime.fromtimestamp(df['time'].iloc[-1]/1000), # df.__len__())) # df = rqdata_get_price( # rq_symbol, # frequency=rq_interval, # fields=["open", "high", "low", "close", "volume"], # start_date=start, # end_date=end, # adjust_type="none" # ) data: List[BarData] = [] if df is not None: for ix, row in df.iterrows(): bar = BarData( symbol=symbol, exchange=exchange, interval=interval, datetime=datetime.fromtimestamp(row.time / 1000), open_price=row["open"], high_price=row["high"], low_price=row["low"], close_price=row["close"], volume=row["volume"], gateway_name="RQ" ) data.append(bar) return data
color_arr = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ] color = "" for i in range(6): color += color_arr[random.randint(0, 14)] return "#" + color if __name__ == '__main__': config = get_client_config() quant_client = QuoteClient(config) stocks = ['QQQ', 'TLT'] data = quant_client.get_bars(stocks) years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month yearsFmt = mdates.DateFormatter('%Y') # fig, ax = plt.subplots() fig = plt.figure() ax = fig.add_subplot(111) # ax1 = None # for index, stock in stocks: y1 = data.loc[(data["symbol"] == stocks[0])] x_time = timestamp_2_str(y1['time'].values) ax.plot(x_time, y1['close'], color='red', label=stocks[0])