刚接触Backtrader,完全按照教程写的,但无法回测,请问是哪里出了问题?

刚接触Backtrader,完全按照教程写的,但无法回测,请问是哪里出了问题?

不知道TypeError问题出在哪,我是新手,刚开始接触backtrader

Traceback (most recent call last):
File "C:\Virtual Hard Drive D\Python project\venv\backtrader\trader.py", line 27, in <module>

data = bt.feeds.PandasData(stock_df, fromdate=fromdate, todate=todate)

File "C:\Users\34063\AppData\Local\Programs\Python\Python39\lib\site-packages\backtrader\metabase.py", line 88, in call

_obj, args, kwargs = cls.doinit(_obj, *args, **kwargs)

File "C:\Users\34063\AppData\Local\Programs\Python\Python39\lib\site-packages\backtrader\metabase.py", line 78, in doinit

_obj.__init__(*args, **kwargs)

TypeError: __init__() takes 1 positional argument but 2 were given

import pandas as pd

from datetime import datetime

import backtrader as bt

import matplotlib.pyplot as plt

import tushare as ts

'''plt.rcParams["front.sans-serif"] = ["SimHei"] # 设置画图时的中文显示

plt.rcParams["axes.unicode_minus"] = False # 设置画图时的负号显示'''

# 1.数据加载

def get_data(code='600519', starttime='2017-01-10', endtime='2020-01-01'):

df = ts.get_k_data(code, start=starttime, end=endtime)

df.index = pd.to_datetime(df.date)

df['openinterest'] = 0

# 对df的数据列进行一个整合

df = df[['open', 'high', 'low', 'volume', 'openinterest']]

print(df)

return df

stock_df = get_data()

fromdate = datetime(2017, 1, 1)

todate = datetime(2020, 1, 1)

# 加载并读取数据源 dataname(数据来源) fromdata(date格式) todate

data = bt.feeds.PandasData(stock_df, fromdate=fromdate, todate=todate)

# 2.构建策略

class Mystrategy(bt.Strategy):

params = (

('maperiod',20),

)

def __init__(self):

self.order = None

self.ma = bt.indicators.SimpleMovingAverage(self.datas[0], period = self.params.maperiod)

# 每个bar都会执行一次,回测的每个日期都会执行一次

def next(self):

# 判断是否有交易指令

if self.order:

return

# 判断是否空仓

if not self.position:

if self.datas[0].close[0]>self.ma[0]:

self.order = self.buy(size=200) # 买二百股

else:

if self.datas[0].close[0]<self.ma[0]:

self.order = self.sell(size=200)

# 3.策略设置

cerebro = bt.Cerebro() # 创建大脑

# 将数据加入回测系统

cerebro.adddata(data)

# 加入自己的策略

cerebro.addstrategy(Mystrategy)

# 经纪人

startcash = 100000

cerebro.broker.setcash(100000)

# 设置手续费

cerebro.broker.setcommission(0.0002)

# 4.执行回测

s = fromdate.strftime("%Y-%m-%d")

t = todate.strftime("%Y-%m-%d")

print(f"初始资金:{startcash}\n回测时间: {s} {t}")

cerebro.run()

portval = cerebro.broker.getvalue()

print(f"剩余总资金:{portval}\n回测时间: {s} {t}")


回答:

问题出在这一行代码:

data = bt.feeds.PandasData(stock_df, fromdate=fromdate, todate=todate)

在创建PandasData对象时,你需要将stock_df作为dataname参数传递。所以,应该是这样的:

data = bt.feeds.PandasData(dataname=stock_df, fromdate=fromdate, todate=todate)

把这一行代码进行相应修改后,你的代码应该可以正常运行。

以上是 刚接触Backtrader,完全按照教程写的,但无法回测,请问是哪里出了问题? 的全部内容, 来源链接: utcz.com/p/938831.html

回到顶部