0

作为 backtrader 文档中第一个示例的替代方案,我尝试传递 ETHUSDT 的每小时数据,但cerebro.run().

我发现next()在策略类中根本没有调用,这是不应该的。问题可能出在数据馈送操作中,但我现在找不到任何东西。

下面是这个项目的 jupyter notebook 代码。任何帮助将不胜感激!

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import backtrader as bt

设置

# instantiate cerebro object
cerebro = bt.Cerebro()

添加数据馈送

import datetime  # For datetime objects
import os.path  # To manage paths
import sys  # To find out the script name (in argv[0])
# import as data feed
data = bt.feeds.GenericCSVData(
        dataname='./backtest_data/Binance_ETHUSDT_1h.csv',
        # Do not pass values before this date
        fromdate=datetime.datetime(2021, 8, 1),
        # Do not pass values after this date
        todate=datetime.datetime(2021, 8, 31),
        nullvalue=0.0, 
        
        dtformat=('%Y-%m-%d %H:%M:%S'),
        timeframe=bt.TimeFrame.Minutes,
        compression=60,
        headers=True,
    
        datetime=1,
        high=4, 
        low=5, 
        open=3, 
        close=6, 
        volume=8, 
        openinterest=-1
)

第一个策略

第一个策略旨在打印出每天的“收盘价”。

# create a strategy class
class TestStrategy(bt.Strategy):
    
    def log(self, txt, dt=None):
        # logging function for this strategy
        dt = dt or self.datas[0].datetime.datetime(0)
        print('%s, %s' % (dt.isoformat(), txt))
        
    def __init__(self):
        # reference to "close" line
        self.close = self.datas[0].close
        
    def next(self):
        # log the closing price of the series from reference
        self.log('Close', self.close[0])
# add strategy to cerebro
cerebro.addstrategy(TestStrategy)

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

# set initial amount
cerebro.broker.setcash(1000000.0)

# starting condition
print('Starting Portfolio Value:', cerebro.broker.getvalue())

# run
cerebro.run()

# final result
print('Final Portfolio Value:', cerebro.broker.getvalue())
Starting Portfolio Value: 1000000.0
Final Portfolio Value: 1000000.0
import pandas as pd
pd.read_csv('./backtest_data/Binance_ETHUSDT_1h.csv')

这是我正在使用的数据集的一瞥:

ETHUSDT 数据集

4

0 回答 0