Backtesting.py - Full course in python

Поделиться
HTML-код
  • Опубликовано: 8 июн 2024
  • A full course covering all you need to know about the backtesting.py python library. Backtesting.py is a lightweight backtesting framework in the style of Backtrader which enables us to quickly get up and going.
    Get in touch:
    chad@greyhoundanalytics.com
    Or through my site:
    greyhoundanalytics.com/contact/
    ⭐ You will learn how to:
    ⌨️ Quickly get up and running with your own strategies.
    ⌨️ Run multi timeframe strategies
    ⌨️ Do parameter optimization and find the best parameters for your strategy
    ⌨️ Optimize your strategy to a custom metric
    ⌨️ Use different order types, stop-loss, take-profit, and shorting..
    ⏱️ Timestamps:
    (00:00:00) Course Introduction
    (00:03:21) Quickstart
    (00:16:59) Parameter Optimization
    (00:22:52) Custom optimization metrics
    (00:26:54) Organizing saved backtests
    (00:30:22) Randomized Grid Search
    (00:32:38) Parameter Optimization Heatmaps
    (00:42:48) Multi-timeframe strategies
    (00:49:13) Shorting, stop loss, take profit
    (00:58:42) Order Sizing
    (01:03:17) Extracting Trade Data
    (01:05:23) Bar Since Function
    (01:09:08) Wrapping up
    TA-lib installation:
    Windows:
    • [SOLVED] How to instal...
    Linux (Possibly mac as well):
    • TA-lib Install Guide f...
    📋 Blog Posts (with code):
    greyhoundanalytics.com/blog/b...

Комментарии • 235

  • @ChadThackray
    @ChadThackray  2 года назад +7

    Consulting available at:
    greyhoundanalytics.com/contact/

    • @user-yt7wr2de7s
      @user-yt7wr2de7s 9 месяцев назад

      I have metadata error when doing pip install backtesting

  • @danchatka8613
    @danchatka8613 Год назад +25

    This is an amazingly good tutorial and you, Chad, are an amazingly good teacher/guide. You don't make things more complicated than they are. You stay on track.

  • @samueltamayogaviria3377
    @samueltamayogaviria3377 2 года назад

    Holy ...!! I've been waiting for a course for this library, thanks!!

  • @ishaangupta3471
    @ishaangupta3471 Год назад +1

    Thanks a lot for this! Found exactly what I was looking for to run optimization.

  • @naelshichida7940
    @naelshichida7940 2 года назад +2

    Absoultely love the content, thanks for your hard work and grit.

  • @oliverSaquarema
    @oliverSaquarema Год назад +1

    Chad, I really appreciate your content, very well explained, you are an excellent teacher and your content is incredible! thanks again! I will study all the content on your channel!

  • @andhikaseptiawan8036
    @andhikaseptiawan8036 Год назад +1

    Very Informative, helpful and Educational video! Thx for the tutorial man!

  • @glenrichzuso9076
    @glenrichzuso9076 Год назад +1

    I am watching your tutorial over the others because your using VIM as your editor :)
    This shows the commitment of a person to learn beyond what is required
    Awesome work and thank you for the wonderful tutorial !

  • @aingo6521
    @aingo6521 Год назад +1

    Thank you for sharing this. I learn a lot from you ! much respect !

  • @transcendmoney
    @transcendmoney Год назад +1

    Best tutorial of backtesting.py on youtube !, thanks

  • @deviatewithDarrell
    @deviatewithDarrell 6 месяцев назад

    Great video Chad. I really appreciate you taking the time. I'm three months into learning Python and stock investing and I was able to follow along this entire video.

  • @stansuen8072
    @stansuen8072 Год назад +3

    Awesome tutorial! Learnt a lot! Thanks a lot.

  • @TundraKaffe1
    @TundraKaffe1 2 года назад +2

    Perfect course! The best out there by far.
    What I still don't get is how to replace a sl or tp if a certain event happens.
    For example I would like to move my stop loss up if a take profit of another order was hit.

  • @simulateworld3198
    @simulateworld3198 3 месяца назад +1

    I was looking for this type of tutorial you are the man❤❤

  • @virtuallore
    @virtuallore 7 месяцев назад

    Brilliant. Very high quality work ❤

  • @flydr2
    @flydr2 2 года назад

    Thank you for taking the time to do this... Very helpfull to me.

  • @SOMEONE-eq5bu
    @SOMEONE-eq5bu Год назад

    that was an excellent tutorial, thanks for sharing, liked and subbed.

  • @MrWittzHD
    @MrWittzHD Год назад +1

    this was wonderful, thank you very much

  • @jontycraine4903
    @jontycraine4903 2 года назад

    Another great Backtesting video Chad

  • @syng9596
    @syng9596 Год назад

    thx for the very detailed tutorial! appreciate it!

  • @jungkyunyang5184
    @jungkyunyang5184 Год назад +1

    Hi Chad, Thank you for the good video. If I had known this video first, I could have saved a lot of time. But I was able to get a lot of ideas from watching this video. Thanks once again.

  • @JurinoJr
    @JurinoJr 6 месяцев назад

    That was an awesome tutorial, thanks a lot!

  • @dilip.rajkumar
    @dilip.rajkumar 2 года назад +12

    Thank you for another Great video. I really do Love your video and channel, so much information on topics where there is hardly any information elsewhere ✌️. BTW, could you post in the description a pros and cons table comparing VectorBT vs. Backtesting.py or perhaps you can make a short 5 min video comparing the differences and highlighting the use cases.

  • @GEORGESDominique
    @GEORGESDominique 2 года назад +2

    Very interresting and clever explanation about backtesting. I'm looking since a few months for readable and understandable content about backtesting, and .. I just found it now :) Thanks for that.
    I'm more "crypto market" oriented, and more scalping strategy interrested (I don't have so much time to trade :'( )
    Thanks for this video, and waiting for the next ones.
    PS : I modified this message and deleted my "request" about developping a BOT, it is in your blog ;)

  • @behradio
    @behradio Год назад

    Awesome Tutorial, Thanks a lot.

  • @jordansoftware5941
    @jordansoftware5941 Год назад

    Thanks for sharing your wealth of knowledge in this excellent series Chad. I love your name by the way.

  • @tradewithaakash2939
    @tradewithaakash2939 9 месяцев назад

    You are just amazing !! thankyou so much for sharing your knowledge

  • @ramanuj_g
    @ramanuj_g 4 месяца назад

    dude this was fantastic... helped a ton..thx...

  • @chimgaebu8419
    @chimgaebu8419 8 месяцев назад

    thank you very much. this is very gorgeous video !!!! . It is very helpful.

  • @10milesfromnowhere
    @10milesfromnowhere 2 года назад

    Thanks! Great tutorial.

  • @naveenkumar-mh6zf
    @naveenkumar-mh6zf Год назад

    Enjoyable and informative video.

  • @surprise7917
    @surprise7917 Год назад

    Amazing video!

  • @nicolasepalaciosm8072
    @nicolasepalaciosm8072 Год назад +1

    Thanks for the video, awesome explanations! New subscription ;)
    I'm left thinking if it's possible to use some of the functions of the library in a different code which is mean to do trades and not only backtesting? Specifically, the bars since function.
    I ask because as I understand it as of now (after watching the video), you only seem to be able to use it inside a class which is extending the Strategy class imported also from this specific library, your RsiOscillator in this case.

  • @ierogosse
    @ierogosse Месяц назад

    Big thanks to you!

  • @masoud603
    @masoud603 Год назад

    thanks alot. it was very useful

  • @kadermoossa
    @kadermoossa 2 года назад

    Thank u… By the way, I like your contents a lot because of your exclusive content, as well as your deep and soothing voice,
    With that British accent :)
    so because of that, I can normally watch an hour-long video with no boring

  • @fauxz3782
    @fauxz3782 11 месяцев назад

    Excellent video

  • @brich8110
    @brich8110 Год назад

    Very nice video thank you

  • @HarpreetSingh-ps9rx
    @HarpreetSingh-ps9rx Год назад

    Brilliant video

  • @nukewares
    @nukewares 5 месяцев назад

    great work, this is excellent. I also appreciate the northern accent. It's been a while since I've heard a proper one.

  • @studiox_ui
    @studiox_ui 2 года назад

    dude you're the fucking best please post more about algotrading thanks

  • @karthickb1973
    @karthickb1973 3 месяца назад

    i needed this today. chad sent

  • @samueltamayogaviria3377
    @samueltamayogaviria3377 2 года назад +2

    could you make more in depth explanations for each action you can make with this library?

  • @trilokyadav4159
    @trilokyadav4159 2 месяца назад

    Hi Chad, thanks for the detailed tutorial! Is it possible to backtest mulit-asset strategies using this API i.e. say option straddle strategy, or say buying a stock and shorting an index at the same time if a signal is generated? Otherwise this would be really limited long/short strategies only and not dollar/delta neutral strategies.

  • @gkr7078
    @gkr7078 Год назад

    This is the best tutorial on backtesting iN RUclips.. a quick question. How do I for loop through different strategy classes for running tests in backtesting.py

  • @scripthunter3738
    @scripthunter3738 Год назад

    Great tutorial yar

  • @brianrowe1152
    @brianrowe1152 2 года назад +1

    Maybe cover trailing stop in a future video? Or can you replace an open order to sell with a new order that you want instead? For example a trailing stop % from the average price, not the close?

  • @Machiuka
    @Machiuka 3 месяца назад

    Very good tutorial. I have some problems to install TA-LIB on my Win11 computer, because of the Python version that I have (3.11). I solved this by creating an environment with Python 3.10.

  • @DigitalTrading
    @DigitalTrading Год назад

    great course

  • @ArneGockeln
    @ArneGockeln 2 месяца назад

    Good tutorial and introduction of this backtest library! Thanks. One last question: Would you bet your real money on strategies that you have tested with this library?

  • @GascanNBK
    @GascanNBK Год назад

    nice video, what about extending the Stats with CAGR/MaxDD?

  • @LucasMoreira-gz6xg
    @LucasMoreira-gz6xg Год назад

    great content

  • @juanbatista6075
    @juanbatista6075 Год назад

    Super.Great

  • @K_line_sorter
    @K_line_sorter Год назад

    How to set the transaction time? For example, trading is only done between 8-12 New York time.

  • @richardchu1593
    @richardchu1593 10 месяцев назад

    In the tutorial, there is example to resample from daily to weekly data such as:
    self.weekly_rsi = resample_apply("W-FRI", talib.RSI, self.data.Close, self.rsi_window).
    However for future contract such as MNQ, its session opening time is not exactly in the same day (using Eastern Time as base). For example MNQ's monday session starts trading from Sunday 6PM ET until Monday 5PM ET.
    Than for the above case, how do you define "session", "daily" and "weekly" resample?
    Thank you so much!

  • @transcendmoney
    @transcendmoney Год назад +1

    Hello, by default is doing size of units, how will be possible to make sizes with decimals, for example always enter with 0.95 of equity in ethereum, should be units with decimals

  • @mrrrokas
    @mrrrokas Год назад

    You an absolute chad

  • @user-uc6wo1lc7t
    @user-uc6wo1lc7t Год назад +1

    There is df.droplevel(axis=0, level=2) to drop "rsi_window" index level. That would be more reasonable to use instead of grouping and using meaningless .mean method.

  • @mohamedhicham6298
    @mohamedhicham6298 2 месяца назад

    Hey Chad great work, i have a question. If i have a dictionary of dataframes for 50 stocks. All of the dataframes have the same start and end date. So how can i run a backtest over all of them instead of running the backtest only one a single dataframe?

  • @astrojes849
    @astrojes849 Год назад +1

    You really are a Chad. Fr

  • @jroche1832
    @jroche1832 Год назад +1

    great video however I have a complex indicator which I am struggling to backtest. Do you have any strategies that you have built which are complex for example VIX/VVIX correlation?

  • @mehmetemin9598
    @mehmetemin9598 Год назад

    good tutorial, one question about soft recording. How do you do it? lol

  • @trollrequiem0444
    @trollrequiem0444 Год назад +1

    Thank you! Nice video! Is there any way to save the equity line data, so that you can, for example, draw it with matplotlib?

    • @ChadThackray
      @ChadThackray  Год назад

      Yep! You can get it from the stats. So you have something like:
      output = bt.run()
      curve = output._equity_curve
      If you look it's just under all the other stats like sharpe, etc. You get a nice pandas df you can plot to your heart's content

  • @davidhazle3234
    @davidhazle3234 2 месяца назад

    Chad, another really good training tutorial . Are you able to share the python code with each of your tutorialss pls?

  • @cosmicblack
    @cosmicblack Год назад

    I justo hace a question
    When i'm un the next method
    To use the actual data and the before injusto need yo use (for ex) self.rsi[-1] and [-2].?

  • @mustafasoeminabdullah3613
    @mustafasoeminabdullah3613 5 месяцев назад

    You're pretty good.

  • @V3ritas1989
    @V3ritas1989 11 месяцев назад

    hey, nice intro. Waht about position sizing with futures or CFDs ? With margins, over night margins, what about slippage, broker costs as well as spreads?

  • @vivekghule5601
    @vivekghule5601 9 месяцев назад

    How to write a strategy in backteting like : input data to backtest is one-minute chart, logic : get High and Low of 2 PM (5 minute candle), and then if current close > high buy order with target 20points , if current close < low sell with tartget of 20 points.
    Thanks

  • @timjx3675
    @timjx3675 Год назад

    Great channel - I wonder if you have come across Empyrial portfolio analysis
    And if so what do you think of it

  • @andreagiunta168
    @andreagiunta168 Год назад

    hi there. I would like use Bollinger Bands and consider "lenght" and "stdev" as variables to be used within the optimization function. have you got some solving answer?!??!?! pllsssssss

  • @220SouthlandAve
    @220SouthlandAve 3 месяца назад

    Hey, great content! I'm wondering how your init function is working properly without a double underscore..isn't init usually a dunder method?
    Thanks.

    • @ChadThackray
      @ChadThackray  3 месяца назад

      It's not a real __init__ function. We're just overriding a function from the parent class

  • @supertamtamtom
    @supertamtamtom 10 месяцев назад

    Can we put constraints on more than 1 parameter, and maximize/minimize several (more than 1) parameters?

  • @Luca-wg4cv
    @Luca-wg4cv 9 месяцев назад

    hi i have a huge problem, if i fix the quantity 1 i don’t work the code regarding the peack and the final how can i fix it?

  • @raphaelarguello5020
    @raphaelarguello5020 2 месяца назад

    Great content, thanks for your work!
    I am struggling with the size of the position for the backtesting. I am trying to risk 1% of the available cash per position so I enter the sl and size = 0.01. However, the risk is completely off and it only risk 0.014%
    I am also confused because in the video you just enter size without stop loss, but risk is normally calculated in function of the sl
    Would you maybe have a solution please?
    Thanks for your help!

  • @randb9378
    @randb9378 10 месяцев назад

    Can you use a ML algorithm as part of your strategy? (ML algorithm will be trained on data to say buy, sell, or hold?) Thanks for the video! You're awesome

  • @ghazanferali366
    @ghazanferali366 Год назад +1

    Great video, very informative.
    I am just having one problem while applying the multitimeframe strategy. If resample_apply is done on an indicator which takes more than one inputs, it is giving all sorts of errors.

    • @ghazanferali366
      @ghazanferali366 Год назад +1

      self.tf2MDI = resample_apply(
      '3T',ta.MINUS_DI(high,low,price,self.n) As an example is not working

  • @protopan7722
    @protopan7722 5 месяцев назад

    Hey what do you think of quant connect?

  • @hourglass9
    @hourglass9 Год назад

    Great Video! Can you simultaneously do a backtesting on all symbols
    like for example EURUSD and SPUSD
    so if I buy on SP500 on 2011-01-07 and sell on 2011-01- 10 then in the next buy this program will recheck the opportunity in EURUSD and SPUSD and automatically matches the buying signal and then buy that stock after 2011-01-10
    in this way we can have a full return on investment
    😀

  • @priyankamore1458
    @priyankamore1458 Год назад

    is there any other forex backtesting library, because I am having an issue regarding order size, leverage, lot size which are bit different than stock or crypto market...It would be very helpful. Thank you

  • @transcendmoney
    @transcendmoney Год назад +1

    so seems backtesting.py can't trade with fractional sizes (fractional ethereum for example 0.99 have to be 1 or 2 ethereum)

  • @kvekka9300
    @kvekka9300 Год назад

    @chad...how can it be run to test bracket orders

  • @VidyabhushanUpadhye
    @VidyabhushanUpadhye Год назад +2

    Hi Chad, this is a wonderful tutorial. Very well explained with the right context.I need help with the date column from a CSV file. python is not reading it as DateTime format but instead, it is reading it as an object. Not able to solve it, and because which not getting Sharpe and other ratios.

    • @ChadThackray
      @ChadThackray  Год назад

      I would look into the pd.to_datetime function from pandas, that will help you convert the date column from a string into datetime format

    • @VidyabhushanUpadhye
      @VidyabhushanUpadhye Год назад

      @@ChadThackray Thanks a lot. It worked. not the ratios are being calculated.😊👍

    • @VidyabhushanUpadhye
      @VidyabhushanUpadhye Год назад

      Hi @@ChadThackray, I am observing that my entries and exits are delayed by two candles not sure why it is happening. Send you an email with the python code and data file. Thanks

  • @fabriciofiel
    @fabriciofiel 2 года назад

    Congratulations on the content, very good!
    I would like to suggest a video with backtesting in renko with wick.

  • @TheRealEstatePerson
    @TheRealEstatePerson 9 месяцев назад

    how do I pull data of crytocurrencies?

  • @timonfranz4996
    @timonfranz4996 5 месяцев назад

    Hi Chad, is there any possibility to extend the _trades dataframe with for example the stop loss and take profit? Or any other trade attribute like a specific trade enty criteria? This would be very helpful to analyse which trades working and which are not working.

    • @ChadThackray
      @ChadThackray  5 месяцев назад

      It's open source so anything is possible. I would just build my own logger though in the main logic and use that to analyse

  • @canea4637
    @canea4637 Год назад

    If you are on Mac OS and use home brew just do brew install ta-lib

  • @zeus_2001
    @zeus_2001 2 года назад +2

    Excellent tutorial. I like the simplicity of this library. It's too bad it can't test and aggregate results for multiple tickers.

    • @damienong1462
      @damienong1462 Год назад

      There is a way to do it. By using for loop, where you will be able to test multiple tickers and even multiple timeframe. (if this is what you mean, it's easy to do it especially with this library, compare to freqTrade)

    • @zeus_2001
      @zeus_2001 Год назад +1

      @@damienong1462 No, that's not what I meant. Looping just runs a sequential series of separate tests. What I'm talking about involves trading multiple instruments as a single strategy.

  • @garyin5
    @garyin5 Год назад +1

    Hi Chad, I am interested in running the backtesting with multiple threads in gpu-process. Could you please help to talk more about how to run it with GPU?

    • @daxj9133
      @daxj9133 Год назад

      You can use CUDA

    • @FilSerge
      @FilSerge Год назад

      Have you succeeded in that?

  • @purasuerte1.0
    @purasuerte1.0 3 месяца назад

    please could anyone provide an example of a simple macd strategy. I've got:
    class RsiOscillator(Strategy):
    def init(self):
    self.macd = self.I(ta.macd, pd.Series(self.data.Close))
    But I don't know how to refer to the signal & the macd column in def next(self):

  • @drcesarvarela
    @drcesarvarela Год назад

    Hello Chad, thanks for the video. It's really useful. I wonder if this library can be used in intraday backtesting strategies. I'm asking because the format date in intraday data includes %D%H%S format and since the data retrieved from the library itself includes just %Y%M%D only I'm not sure if it can handle intraday data. Can you please provide more information about this query, thank you in advance.

    • @ChadThackray
      @ChadThackray  Год назад +1

      Yeah you can use whatever timeframe you want. In this instance it's formatted like that because it's daily data from yfinance. But it works exactly the same with intra-day data

    • @drcesarvarela
      @drcesarvarela Год назад

      @@ChadThackray Thanks for the prompt reply, you have a new subscriber.

  • @Cavz001
    @Cavz001 8 месяцев назад

    Great video sir. Quick question. Delving deeper into algorithmic trading, I’ve found that mere backtesting isn’t sufficient and processes like out-of-sample backtesting, Sample parameter optimization, walk-forward optimization and Monte Carlo Simulation are viltal to creating a solid system. Question is: how do you conduct these tests with Python?

    • @ChadThackray
      @ChadThackray  8 месяцев назад

      You are correct. There are many videos here on youtube that will teach you how to do these other tests. Some of those topics I've covered myself on this channel

    • @Cavz001
      @Cavz001 8 месяцев назад

      @@ChadThackray cool. I’ll check them out. Thank you

  • @pauljones9150
    @pauljones9150 День назад

    You multi-timeline test code is somehow broken. Not sure how or how to fix.
    It has something to do with this line: self.daily_rsi = self.I(ta.rsiI, pd.Series(self.data.Close), self.rsi_window). It doesn't think that ta.rsil is a thing

  • @PeterPankowski
    @PeterPankowski 5 месяцев назад

    By the way... nevertheless.. the video is excellent... 10 of 10 ....

  • @Thegiant4296
    @Thegiant4296 Год назад +1

    I am new to python and was just curious what you're using to write your code in? I couldn't make it out when you said it in the beginning but would like to use the same platform

    • @ChadThackray
      @ChadThackray  Год назад +1

      I'm using Vim, a command line based text editor

    • @Thegiant4296
      @Thegiant4296 Год назад

      @@ChadThackray Thank you!

  • @blasdelezo8396
    @blasdelezo8396 2 года назад

    Thanks for the video. Many questions and queries come to me.
    How to code a stop loss and take profit as a percentage of the purchasing power?
    Is there bibliography of online courses regarding this backtesting library?

    • @ChadThackray
      @ChadThackray  2 года назад

      It's a relatively niche library so there's not much content out there. Hence this video

    • @ChadThackray
      @ChadThackray  2 года назад

      It's a relatively niche library so there's not much content out there. Hence this video

  • @fiftyghoststrading8500
    @fiftyghoststrading8500 Год назад

    Thank you for the vid! Did you leave the TA-lib installation link anywhere? I'm not seeing it

    • @ChadThackray
      @ChadThackray  Год назад +1

      Just updated the description

    • @fiftyghoststrading8500
      @fiftyghoststrading8500 Год назад

      @@ChadThackray Cool, thank you! Great video, by the way.. it got me up and running!

  • @GD-bx5pk
    @GD-bx5pk Год назад

    Hi Chad @ 1:15 you said it doesn’t try to integrate with a broker does that mean i can only backtest and optimise i cant trade with it via api or whatever. I’m a python beginner

    • @ChadThackray
      @ChadThackray  Год назад +1

      Yes, there are no live trading functionalities. You could probably modify it to do that if you wanted, but it wouldn't be too easy

  • @pinalpatel5474
    @pinalpatel5474 2 месяца назад

    Can't download talib in python 3.12 version

  • @guidomarquez8973
    @guidomarquez8973 Год назад

    Hello!! Excellent video. I am exactly the code shown in the video, however I get the following error: "TypeError: Can't instantiate abstract class GoldenCross with abstract method init". What can it be, the version of python (I use 3.8.0)?

    • @user-yx1fy7sn5z
      @user-yx1fy7sn5z Год назад

      Type def init(self) instead of def __init__(self) . It was my mistake too

  • @efeeeeee212
    @efeeeeee212 11 месяцев назад

    why your script is so fast? i ran but its so slow. on windows 11 my own pc and i tryed to using multiprocessing but not working well?