用40分鐘學會專業回測工具 - backtrader基本操作

  Рет қаралды 18,771

PyInvest

PyInvest

Күн бұрын

Пікірлер: 52
@Pyinvest
@Pyinvest 3 жыл бұрын
在7:22開始之前,有使用cerebro.setcash(10000000)改變期初的資產金額,在製作影片時遺漏了這個部分 在請注意
@Eddie-h4s
@Eddie-h4s 2 жыл бұрын
非常感謝分享,很實用!
@洪博益-i4i
@洪博益-i4i Жыл бұрын
ctrl + F5 其實是個很讚的快捷鍵
@pieceone1761
@pieceone1761 2 жыл бұрын
會出現AttributeError: Can't get attribute 'TestStrategy',可是我事先宣告class,下部分是if __name__ == '__main__': 但在做cerebro.optstrategy(TestStrategy,maperiod=range(10,31))還是會有問題
@Pyinvest
@Pyinvest 2 жыл бұрын
不太確定,可以分享一下程式碼嗎? 大家比較容易幫忙~
@pieceone1761
@pieceone1761 2 жыл бұрын
@@Pyinvest import backtrader as bt import os from pathlib import Path import datetime from IPython.display import display,display_html,display_png,display_svg import matplotlib.pyplot as plt class TestStrategy(bt.Strategy): params=(('maperiod',15),) def __init__(self): self.dataclose = self.datas[0].close self.order = None self.sma = bt.indicators.SimpleMovingAverage(self.datas[0],period=self.params.maperiod) def notify_order(self, order): if order.status in [order.Submitted,order.Accepted]: return if order.status in [order.Completed]: if order.isbuy(): self.log("Buy Executed {}".format(order.executed.price)) elif order.issell(): self.log("Sell Executed {}".format(order.executed.price)) self.bar_executed = len(self) elif order.status in [order.Canceled, order.Margin, order.Rejected]: self.log("Buy Executed {}".format(order.executed.price)) self.order=None def next(self): self.log("Close {}".format(self.dataclose[0])) if self.order: return if not self.position: if self.dataclose[0] > self.sma[0]: self.log("Buy Create {}".format(self.dataclose[0])) self.order=self.buy() else: if self.dataclose[0] < self.sma[0]: self.log("Sell Create {}".format(self.dataclose[0])) self.order = self.sell() def log(self,txt): dt = self.datas[0].datetime.date(0) print("{} {}".format(dt.isoformat(),txt)) def stop(self):# 配cerebro.optstrategy print(self.params.maperiod,self.broker.getvalue()) if __name__ == '__main__': cerebro = bt.Cerebro() cerebro.broker.setcash(10000000) cerebro.broker.setcommission(commission=0.001) #cerebro.addstrategy(TestStrategy) cerebro.optstrategy(TestStrategy,maperiod=range(10,31)) data_path= Path(os.getcwd()) / 'data/2330.TW.csv' data=bt.feeds.YahooFinanceCSVData(dataname=data_path, fromdate=datetime.datetime(2019,1,1), todate=datetime.datetime(2019,12,31)) cerebro.adddata(data) print("Start Portfolio {}".format(cerebro.broker.getvalue())) cerebro.run() print("Final Portfolio {}".format(cerebro.broker.getvalue())) plt.figure() cerebro.plot() plt.show()
@pieceone1761
@pieceone1761 2 жыл бұрын
是在spyder上運行 所以畫圖有引用其他的模組
@MrLam-lx7td
@MrLam-lx7td 2 жыл бұрын
簡單,圖表很美。
@yu-peisun1310
@yu-peisun1310 3 жыл бұрын
感謝分享!
@donnieshao2092
@donnieshao2092 2 жыл бұрын
刚刚写了一遍发现动态传参取值的时候要用 self.p.{参数名}取值,可能是版本不同导致的。
@herbyho1997
@herbyho1997 3 жыл бұрын
想請問有沒有辦法匯入其它外部資料(比如三大法人買賣超、期權或是其它有datetime的任意資料)來做為策略指標,還是說只能用有open,high,close….的資料類型。感謝!
@Pyinvest
@Pyinvest 3 жыл бұрын
可以的,可以參考這篇文章( algotrading101.com/learn/backtrader-for-backtesting/ ),在How to use alternative data in Backtrader這個部分,作者使用google trends當做產生信號的資料源,再加入這個資料的時候,可以使用GenericCSVData方法,然後在建立strategy在引用
@想傑的大水蛇
@想傑的大水蛇 3 жыл бұрын
請問網路上使用的backtesting 和版主用的backtrader 的差別在哪裡呢? 感謝分享!
@Pyinvest
@Pyinvest 3 жыл бұрын
兩個是不同的套件喔,其語法跟支援的功能可能都不太一樣,但看起來backtrader的使用者應該多不少。 www.libhunt.com/compare-backtrader-vs-backtesting.py?ref=compare backtesting沒有使用過,但看起來也是不錯的回測框架,但不確定有沒有直接支援程式實盤交易的功能。 Backtrader的幾個優點 - 1.功能完善 2.文檔很詳細 3. 蠻多人在用的
@marktung9676
@marktung9676 2 жыл бұрын
教學清晰~讚!!!,可惜教技術的頻道總是沒啥觀看人數qq
@tony93058
@tony93058 2 жыл бұрын
老師不好意思,我想問為何我圖畫出來然後觀察是否有去照著買賣訊號,卻發現買賣訊號有出來,卻沒看到圖上面有buy or sell 的圖示,想問是正常的嗎?
@tony93058
@tony93058 2 жыл бұрын
另外想詢問如何進行雙均線的參數優化
@tony93058
@tony93058 2 жыл бұрын
import datetime import backtrader as bt import backtrader.feeds as btfeeds import pandas as pd import numpy as np import matplotlib.pyplot as plt from pandas_datareader import data import backtrader as bt import backtrader.feeds as btfeeds import yfinance as yf import math data = bt.feeds.PandasData(dataname=yf.download('AMZN', '2020-01-01', '2022-01-01', auto_adjust=True)) # data_path = r'C:\Users\user\Desktop\python\final presentation\AMZN.csv' # data = btfeeds.YahooFinanceCSVData(dataname=data_path,fromdate=datetime.datetime(2019, 1, 1), # todate=datetime.datetime(2019, 12, 31)) # sma cross strategy class SmaCross(bt.Strategy): # 交易紀錄 def log(self, txt, dt=None): dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) # 設定交易參數 #params = dict( #ma_period_short=20, #ma_period_long=60 #) params = (('ma_period_short',13),('ma_period_long',69)) def __init__(self): # 均線交叉策略 sma1 = bt.ind.SMA(period=self.p.ma_period_short) sma2 = bt.ind.SMA(period=self.p.ma_period_long) self.crossover = bt.ind.CrossOver(sma1, sma2) # 使用自訂的sizer函數,將帳上的錢all-in self.setsizer(sizer()) # 用開盤價做交易 self.dataopen = self.datas[0].open def next(self): # 帳戶沒有部位 if not self.position: # 5ma往上穿越20ma if self.crossover > 0: # 印出買賣日期與價位 self.log('BUY ' + ', Price: ' + str(self.dataopen[0])) # 使用開盤價買入標的 self.buy(price=self.dataopen[0]) # 5ma往下穿越20ma elif self.crossover < 0: # 印出買賣日期與價位 self.log('SELL ' + ', Price: ' + str(self.dataopen[0])) # 使用開盤價賣出標的 self.close(price=self.dataopen[0]) # 計算交易部位 class sizer(bt.Sizer): def _getsizing(self, comminfo, cash, data, isbuy): if isbuy: return math.floor(cash/data[1]) else: return self.broker.getposition(data) # 初始化cerebro cerebro = bt.Cerebro() cerebro.broker.setcash(1000000) cerebro.broker.setcommission(commission = 0.0006) # feed data cerebro.adddata(data) # add strategy cerebro.addstrategy(SmaCross) # run backtest cerebro.run() # plot diagram cerebro.plot()
@Pyinvest
@Pyinvest 2 жыл бұрын
不太確定,預設應該是有?
@Pyinvest
@Pyinvest 2 жыл бұрын
之後有機會來研究看看
@donnieshao2092
@donnieshao2092 2 жыл бұрын
感谢,博主代码写的好遛
@林靜惠-c6f
@林靜惠-c6f 3 жыл бұрын
謝謝分享
@nadillalin8428
@nadillalin8428 2 жыл бұрын
老師您好,無法繪圖怎麼辦?試過很多辦法都不行。
@Pyinvest
@Pyinvest 2 жыл бұрын
請問有錯誤訊息嗎
@Jim-or5wp
@Jim-or5wp 2 жыл бұрын
請問用jupyter notebook也可以嗎
@Pyinvest
@Pyinvest 2 жыл бұрын
可以喔,但是畫圖要特別注意
@yaoxiao7583
@yaoxiao7583 2 жыл бұрын
老師,為什麼最後回測結果只有100多盈利,用其他品種像TQQQ回測盈利也只有100多,是哪裡出了問題嗎
@1個顗任
@1個顗任 9 ай бұрын
請問看影片看不太懂 是不是要先理解基本backtrader功能
@Pyinvest
@Pyinvest 9 ай бұрын
嗯嗯 也可以參考他們官方的教學文件
@recently2012
@recently2012 3 жыл бұрын
程式加入 optstrategy / plot 會報一個找不到 attribute 的錯誤 請問要如何處理呢 ?
@Pyinvest
@Pyinvest 3 жыл бұрын
請問是怎樣的錯誤訊息?
@pjs888
@pjs888 3 жыл бұрын
@@Pyinvest 我的是 AttributeError: 'Figure' object has no attribute 'init_layoutgrid'
@Pyinvest
@Pyinvest 3 жыл бұрын
matplotlib的版本? 可以試試看把matplotlib的版本設定為3.2.2試試看
@recently2012
@recently2012 3 жыл бұрын
@@Pyinvest 運行optstrategy 會跳出下列提示,但class是寫在同一個腳本裡面 Can't get attribute 'TestStrategy' on
@Pyinvest
@Pyinvest 3 жыл бұрын
恩恩 TestStrategy有定義在cerebro宣告之前嗎? 可以參考這個 community.backtrader.com/topic/2120/optstrategy-get-error-help-me-thanks
@廖漢文-o3p
@廖漢文-o3p 3 жыл бұрын
想請教一下,程式跳出說我在broker沒有訊息,請問這broker也是自己寫嗎?卡在這一段時間很困擾⋯⋯
@Pyinvest
@Pyinvest 3 жыл бұрын
是錯誤訊息嗎 broker是程式寫好的 我們只需要初始化設定即可
@yaoxiao7583
@yaoxiao7583 2 жыл бұрын
老师,这个盈利这么少是因为backtrader默认买的份数很少吗,是只买了一个单位的吗
@Pyinvest
@Pyinvest 2 жыл бұрын
用預設的話,是的 可以調整position sizer來達到想要的效果 www.backtrader.com/docu/sizers/sizers/
@youngsen288
@youngsen288 2 жыл бұрын
请问下教程代码可以开源嘛谢谢
@Pyinvest
@Pyinvest 2 жыл бұрын
可以參考backtrader的quickstart,這個影片主要參考文檔,所以沒有放上來,程式碼應該只有一些差別(如下) www.backtrader.com/docu/quickstart/quickstart/
@fu4123
@fu4123 2 жыл бұрын
code 可以分享吗? 谢谢
@Pyinvest
@Pyinvest 2 жыл бұрын
可以參考前面的回答 這主要跟隨官方教學 可以參考官方的程式碼 不會差很多
@RCoool-k6r
@RCoool-k6r Жыл бұрын
英文發音好多念錯..看到後來很出戲
@joshuag52129
@joshuag52129 Жыл бұрын
我現在只差不能畫圖不知道怎麼解決我是用VS code import backtrader as bt import os from pathlib import Path import datetime class TestStrategy(bt.Strategy): params = ( ('maperiod', 15), ) def __init__(self): self.dataclose = self.datas[0].close self.order = None self.sma = bt.indicators.MovingAverageSimple( self.datas[0],period=self.params.maperiod) def notify_order(self,order): if order.status in [order.Submitted, order.Accepted]: return if order.status in [order.Completed]: if order.isbuy(): self.log("Buy Executed {}".format(order.executed.price)) elif order.issell(): self.log("Sell Executed {}".format(order.executed.price)) self.bar_executed = len(self) elif order.status in [order.Canceled, order.Margin, order.Rejected]: self.log("Order Canceled/Margin/Rejected") self.order = None def next (self): self.log("Close {}".format(self.dataclose[0])) if self.order: return if not self.position: if self.dataclose[0] > self.sma[0]: self.log("Buy Create {}".format(self.dataclose[0])) self.order = self.buy() else: if self.dataclose[0] < self.sma[0]: self.log("Sell Create {}".format(self.dataclose[0])) self.order = self.sell() def log(self, txt): dt = self.datas[0].datetime.date(0) print("{} {}" .format(dt.isoformat(), txt)) if __name__ == '__main__': cerebro = bt.Cerebro() cerebro.broker.setcash(10000000) cerebro.broker.setcommission(commission=0.001) cerebro.addstrategy(TestStrategy) data_path = Path(os.getcwd()) / 'data/AAPL.csv' data = bt.feeds.YahooFinanceCSVData( dataname=data_path, fromdate=datetime.datetime(2019, 1, 1), todate=datetime.datetime(2019, 12, 31), ) cerebro.adddata(data) print ("Start Portfolio{}".format(cerebro.broker.getvalue())) cerebro.run() print ("Final Portfolio{}".format(cerebro.broker.getvalue())) cerebro.plot()
@Pyinvest
@Pyinvest Жыл бұрын
請問是什麼樣的錯誤訊息?
@joshuag52129
@joshuag52129 Жыл бұрын
@@Pyinvest 最後畫圖功能出不來
@Pyinvest
@Pyinvest Жыл бұрын
這邊要用matplotlib畫圖,可以檢查安裝以及安裝的版本 可以用以下的指令在終端機試試 pip uninstall matplotlib pip install matplotlib==3.1.1
@joshuag52129
@joshuag52129 Жыл бұрын
@@Pyinvest 我的環境變數有檢查過 畫圖終端機也試過但還是跑不出來 我也是用vsco
Yay😃 Let's make a Cute Handbag for me 👜 #diycrafts #shorts
00:33
LearnToon - Learn & Play
Рет қаралды 117 МЛН
Smart Sigma Kid #funny #sigma
00:33
CRAZY GREAPA
Рет қаралды 8 МЛН
МЕНЯ УКУСИЛ ПАУК #shorts
00:23
Паша Осадчий
Рет қаралды 5 МЛН
Players push long pins through a cardboard box attempting to pop the balloon!
00:31
「HongKongDoll」為何自嘲自己是敗家女!「狗仔隊長」
8:58
《狗仔隊長》分享網紅八卦
Рет қаралды 1,5 МЛН
What is Backtesting? [Explained]
8:17
VRDNation
Рет қаралды 11 М.
Vectorbt for beginners - Full Python Course
3:59:04
Chad Thackray
Рет қаралды 77 М.
【泛泛说量化】回测框架哪家强
8:53
泛程序员
Рет қаралды 1,2 М.
Yay😃 Let's make a Cute Handbag for me 👜 #diycrafts #shorts
00:33
LearnToon - Learn & Play
Рет қаралды 117 МЛН