COCO研究院

 找回密碼
 註冊
搜索
查看: 1393|回復: 0

Backtrader的hello world (Python回測)

[複製鏈接]
發表於 23-2-5 22:38 | 顯示全部樓層 |閱讀模式
https://www.backtrader.com/home/helloalgotrading/


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

1) Yahoo下載報錯
  1.   File "D:\92-investment-python\backtrader\feed.py", line 674, in start
  2.     self.f = io.open(self.p.dataname, 'r')
  3. FileNotFoundError: [Errno 2] No such file or directory: 'MSFT'
複製代碼

解決方法在這裡看到的
https://community.backtrader.com ... yahoofinance-data/2

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

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

  4. cerebro = bt.Cerebro()
  5. 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了!

11.png


完整程式如下
  1. from datetime import datetime
  2. import backtrader as bt
  3. import yfinance as yf

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

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

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

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

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


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

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

  27. cerebro.adddata(data)  # Add the data feed

  28. cerebro.addstrategy(SmaCross)  # Add the trading strategy
  29. cerebro.run()  # run it all
  30. cerebro.plot()  # and plot it with a single command
複製代碼


評分

參與人數 2金錢 +4 收起 理由
songmoney + 2 感謝分享
CalmState951 + 2 太強了

查看全部評分

您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

手機版|Archiver|站長信箱|廣告洽詢|COCO研究院

GMT+8, 24-4-20 16:55

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.

快速回復 返回頂部 返回列表
理財討論網站 | AI繪圖AI超擬真美女AI beauty AI Stable DiffusionAI正妹AI Lookbook