綠茶妹 發表於 23-2-5 22:38

Backtrader的hello world (Python回測)

https://www.backtrader.com/home/helloalgotrading/


這個sample直接跑會有error。有2個地方要改,改了才會好。
(還真麻煩,我以為一下載就可以用{:4_186:})

1) Yahoo下載報錯
File "D:\92-investment-python\backtrader\feed.py", line 674, in start
    self.f = io.open(self.p.dataname, 'r')
FileNotFoundError: No such file or directory: 'MSFT'
解決方法在這裡看到的
https://community.backtrader.com/topic/3979/help-with-yahoofinance-data/2

用下面這個寫法
import yfinance as yf
import backtrader as bt

data = bt.feeds.PandasData(dataname=yf.download('TSLA', '2018-01-01', '2019-01-01'))

cerebro = bt.Cerebro()
cerebro.adddata(data)

2) 解決這個又有另一個問題
在使用backtrader时,遇到 ImportError: cannot import name ‘warnings‘ from ‘matplotlib.dates‘ 报错的解决方法

解法
https://blog.csdn.net/m0_65167078/article/details/121942610
使用matplotlib==3.2.2版本
請打 pip install matplotlib==3.2.2

以上解決後終於有個hello world了!




完整程式如下
from datetime import datetime
import backtrader as bt
import yfinance as yf

# Create a subclass of Strategy to define the indicators and logic

class SmaCross(bt.Strategy):
    # list of parameters which are configurable for the strategy
    params = dict(
      pfast=10,# period for the fast moving average
      pslow=30   # period for the slow moving average
    )

    def __init__(self):
      sma1 = bt.ind.SMA(period=self.p.pfast)# fast moving average
      sma2 = bt.ind.SMA(period=self.p.pslow)# slow moving average
      self.crossover = bt.ind.CrossOver(sma1, sma2)# crossover signal

    def next(self):
      if not self.position:# not in the market
            if self.crossover > 0:# if fast crosses slow to the upside
                self.buy()# enter long

      elif self.crossover < 0:# in the market & cross to the downside
            self.close()# close long position


cerebro = bt.Cerebro()# create a "Cerebro" engine instance

# Create a data feed
#data = bt.feeds.YahooFinanceData(dataname='MSFT',
#                              fromdate=datetime(2011, 1, 1),
#                                 todate=datetime(2012, 12, 31))
data = bt.feeds.PandasData(dataname=yf.download('MSFT', '2011-01-01', '2012-12-31'))

cerebro.adddata(data)# Add the data feed

cerebro.addstrategy(SmaCross)# Add the trading strategy
cerebro.run()# run it all
cerebro.plot()# and plot it with a single command

頁: [1]
查看完整版本: Backtrader的hello world (Python回測)