下载数据

在开始策略回测之前,必须保证数据库内有充足的历史数据。故vnpy提供了历史数据一键下载的功能。

RQData

RQData提供国内股票、ETF、期货以及期权的历史数据。其下载数据功能主要是基于RQData的get_price()函数实现的。

  1. get_price(
  2. order_book_ids, start_date='2013-01-04', end_date='2014-01-04',
  3. frequency='1d', fields=None, adjust_type='pre', skip_suspended =False,
  4. market='cn'
  5. )

在使用前要保证RQData初始化完毕,然后填写以下4个字段信息:

  • 本地代码:格式为合约品种+交易所,如IF88.CFFEX、rb88.SHFE;然后在底层通过RqdataClient的to_rq_symbol()函数转换成符合RQData格式,对应RQData中get_price()函数的order_book_ids字段。

  • K线周期:可以填1m、1h、d、w,对应get_price()函数的frequency字段。

  • 开始日期:格式为yy/mm/dd,如2017/4/21,对应get_price()函数的start_date字段。(点击窗口右侧箭头按钮可改变日期大小)

  • 结束日期:格式为yy/mm/dd,如2019/4/22,对应get_price()函数的end_date字段。(点击窗口右侧箭头按钮可改变日期大小)

填写完字段信息后,点击下方“下载数据”按钮启动下载程序,下载成功如图所示。

https://vnpy-community.oss-cn-shanghai.aliyuncs.com/forum_experience/yazhang/cta_backtester/data_loader.png

IB

盈透证券提供外盘股票、期货、期权的历史数据。下载前必须连接好IB接口,因为其下载数据功能主要是基于IbGateway类query_history()函数实现的。

  1. def query_history(self, req: HistoryRequest):
  2. """"""
  3. self.history_req = req
  4.  
  5. self.reqid += 1
  6.  
  7. ib_contract = Contract()
  8. ib_contract.conId = str(req.symbol)
  9. ib_contract.exchange = EXCHANGE_VT2IB[req.exchange]
  10.  
  11. if req.end:
  12. end = req.end
  13. end_str = end.strftime("%Y%m%d %H:%M:%S")
  14. else:
  15. end = datetime.now()
  16. end_str = ""
  17.  
  18. delta = end - req.start
  19. days = min(delta.days, 180) # IB only provides 6-month data
  20. duration = f"{days} D"
  21. bar_size = INTERVAL_VT2IB[req.interval]
  22.  
  23. if req.exchange == Exchange.IDEALPRO:
  24. bar_type = "MIDPOINT"
  25. else:
  26. bar_type = "TRADES"
  27.  
  28. self.client.reqHistoricalData(
  29. self.reqid,
  30. ib_contract,
  31. end_str,
  32. duration,
  33. bar_size,
  34. bar_type,
  35. 1,
  36. 1,
  37. False,
  38. []
  39. )
  40.  
  41. self.history_condition.acquire() # Wait for async data return
  42. self.history_condition.wait()
  43. self.history_condition.release()
  44.  
  45. history = self.history_buf
  46. self.history_buf = [] # Create new buffer list
  47. self.history_req = None
  48.  
  49. return history

BITMEX

BITMEX交易所提供数字货币历史数据。由于仿真环境与实盘环境行情差异比较大,故需要用实盘账号登录BIMEX接口来下载真实行情数据,其下载数据功能主要是基于BitmexGateway类query_history()函数实现的。

  1. def query_history(self, req: HistoryRequest):
  2. """"""
  3. if not self.check_rate_limit():
  4. return
  5.  
  6. history = []
  7. count = 750
  8. start_time = req.start.isoformat()
  9.  
  10. while True:
  11. # Create query params
  12. params = {
  13. "binSize": INTERVAL_VT2BITMEX[req.interval],
  14. "symbol": req.symbol,
  15. "count": count,
  16. "startTime": start_time
  17. }
  18.  
  19. # Add end time if specified
  20. if req.end:
  21. params["endTime"] = req.end.isoformat()
  22.  
  23. # Get response from server
  24. resp = self.request(
  25. "GET",
  26. "/trade/bucketed",
  27. params=params
  28. )
  29.  
  30. # Break if request failed with other status code
  31. if resp.status_code // 100 != 2:
  32. msg = f"获取历史数据失败,状态码:{resp.status_code},信息:{resp.text}"
  33. self.gateway.write_log(msg)
  34. break
  35. else:
  36. data = resp.json()
  37. if not data:
  38. msg = f"获取历史数据为空,开始时间:{start_time},数量:{count}"
  39. break
  40.  
  41. for d in data:
  42. dt = datetime.strptime(
  43. d["timestamp"], "%Y-%m-%dT%H:%M:%S.%fZ")
  44. bar = BarData(
  45. symbol=req.symbol,
  46. exchange=req.exchange,
  47. datetime=dt,
  48. interval=req.interval,
  49. volume=d["volume"],
  50. open_price=d["open"],
  51. high_price=d["high"],
  52. low_price=d["low"],
  53. close_price=d["close"],
  54. gateway_name=self.gateway_name
  55. )
  56. history.append(bar)
  57.  
  58. begin = data[0]["timestamp"]
  59. end = data[-1]["timestamp"]
  60. msg = f"获取历史数据成功,{req.symbol} - {req.interval.value},{begin} - {end}"
  61. self.gateway.write_log(msg)
  62.  
  63. # Break if total data count less than 750 (latest date collected)
  64. if len(data) < 750:
  65. break
  66.  
  67. # Update start time
  68. start_time = bar.datetime + TIMEDELTA_MAP[req.interval]
  69.  
  70. return history