繁体   English   中英

将 GenericCSVData 对象转换为 backtrader 数据馈送

[英]Converting a GenericCSVData object to a backtrader datafeed

如何将backtrader csv reader转换为backtrader datafeed 我试过:

尝试 1:(用 GenericCSV 替换数据馈送)

all_data=bt.feeds.GenericCSVData(
  #my csv params here
)

for s, df in all_data.items(): #THIS LINE READS IN CSV AND ERRORS
    #do stuff

'Lines_LineSeries_DataSeries_OHLC_OHLCDateTime_Abst' 对象没有属性 'items'

尝试 2:(将 GenericCSV 转换为 Datafeed)

all_data=bt.feeds.GenericCSVData(
  #my csv params here
)
all_datafeed = bt.feeds.PandasData(dataname=all_data) 

错误:“Lines_LineSeries_DataSeries_OHLC_OHLCDateTime_Abst”对象没有属性“列”

尝试 3:(读入 csv 并转换为数据馈送)

df=pd.read_csv('/home/abc/EUR_USD.csv',header=0,parse_dates=True)
all_datafeed = bt.feeds.PandasData(dataname=df)
for df in all_datafeed.items():
    print(df)

'Lines_LineSeries_DataSeries_OHLC_OHLCDateTime_Abst' 对象没有属性 'items'

摘自 csv:

time,oask,hask,lask,cask,obid,hbid,lbid,cbid,volume
2002-05-06 20:00:00 UTC,0.9184,0.9184,0.9181,0.9184,0.9181,0.9181,0.9181,0.9181,1
2002-05-07 20:00:00 UTC,0.9155,0.9155,0.9152,0.9155,0.9152,0.9152,0.9152,0.9152,1
2002-05-08 20:00:00 UTC,0.9045,0.9045,0.9042,0.9045,0.9042,0.9042,0.9042,0.9042,1
# Create a Data Feed
data = bt.feeds.GenericCSVData(
    dataname='filepath.csv',
    fromdate=datetime.datetime(2018, 1, 1),
    todate=datetime.datetime(2018, 12, 31),
    nullvalue=0.0,
    dtformat=('%Y-%m-%d'),
    datetime=0,
    open = 1,
    high = 2,
    low = 3,
    close = 4,
    volume =5, 
    openinterest=-1,
    reverse=False)

# Add the Data Feed to Cerebro
cerebro.adddata(data)

如果这就是你想要完成的,虽然我不确定。

https://www.backtrader.com/docu/datafeed.html

您需要做的就是创建一个数据提要并将其传递给cerebro

比特币数据集

我有同样的问题,通过注意以下问题解决了:

  1. datetime格式为%Y.%m.%d hh:mm:ss

所以你应该用-替换. 在您的示例中,使用以下内容然后保存数据框:

import pandas as pd
df = pd.read_csv("your_csv_file.csv")
df.index = df.index.map(lambda datetime: datetime.replace("-", ".")
df.to_csv("your_csv_file.csv")

  1. 我们传递给GenericCSVData的数字是列的索引(从左到右从 0 开始)
| col_0 | col_1 | col_2 | col_3 | col_4 | col_5 | col_6 | col_7 | 
# in my example:
| datetime | symbol | open | high | low | close | volume btc | volume usd |

所以它应该像下面这样添加:

#...
data = bt.feeds.GenericCSVData(
    dataname="./dataset/btc.csv",
    dtformat=('%Y.%m.%d %H:%M:%S'),
    datetime=0,
    open=2,
    high=3,
    low=4,
    close=5,
)

cerebro.adddata(data)
#...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM