当前位置: 代码迷 >> 综合 >> 开源量化框架backtrader FAQ:开发MySQL data feed
  详细解决方案

开源量化框架backtrader FAQ:开发MySQL data feed

热度:88   发布时间:2023-12-08 09:32:15.0

完整技术教程见这里

有很多人建立了自己本地的行情数据库,希望能够从本地数据库将数据发到backtrader,供策略使用。一个通用的方法是将数据库的行情数据读到pandas dataframe里,然后将这个数据帧的数据传给backtrader的pandas feed数据对象,这样策略就能够使用了。

但是有些同学不想通过pandas dataframe中转,而是想直接从数据库将数据喂给backtrader的数据馈送对象,这就需要针对数据库开发专门的data feed类了。

以下就是backtrader社区提供的一个从MySQL数据库读取数据的feed类MySQLData,大家可以试一试。

from __future__ import (absolute_import, division, print_function,unicode_literals)import datetime
from backtrader.feed import DataBase
from backtrader import date2num
from sqlalchemy import create_engineclass MySQLData(DataBase):params = (('dbHost', None),('dbUser', None),('dbPWD', None),('dbName', None),('ticker', 'ISL'),('fromdate', datetime.datetime.min),('todate', datetime.datetime.max),('name', ''),)def __init__(self):self.engine = create_engine('mysql://'+self.p.dbUser+':'+ self.p.dbPWD +'@'+ self.p.dbHost +'/'+ self.p.dbName +'?charset=utf8mb4', echo=False)def start(self):self.conn = self.engine.connect()self.stockdata = self.conn.execute("SELECT id FROM stocks WHERE ticker LIKE '" + self.p.ticker + "' LIMIT 1")self.stock_id = self.stockdata.fetchone()[0]#self.result = self.engine.execute("SELECT `date`,`open`,`high`,`low`,`close`,`volume` FROM `eoddata` WHERE `stock_id` = 10 AND `date` between '"+self.p.fromdate.strftime("%Y-%m-%d")+"' and '"+self.p.todate.strftime("%Y-%m-%d")+"' ORDER BY `date` ASC")self.result = self.conn.execute("SELECT `date`,`open`,`high`,`low`,`close`,`volume` FROM `eoddata` WHERE `stock_id` = " + str(self.stock_id) + " AND `date` between '"+self.p.fromdate.strftime("%Y-%m-%d")+"' and '"+self.p.todate.strftime("%Y-%m-%d")+"' ORDER BY `date` ASC")def stop(self):#self.conn.close()self.engine.dispose()def _load(self):one_row = self.result.fetchone()if one_row is None:return Falseself.lines.datetime[0] = date2num(one_row[0])self.lines.open[0] = float(one_row[1])self.lines.high[0] = float(one_row[2])self.lines.low[0] = float(one_row[3])self.lines.close[0] = float(one_row[4])self.lines.volume[0] = int(one_row[5])self.lines.openinterest[0] = -1return True

 

发布于 19 小时前

  相关解决方案