How To Backtest A Trading Strategy in Python

Поделиться
HTML-код
  • Опубликовано: 17 май 2024
  • In this video I am presenting a backtesting method using the backtesting.py package. We will backtest a winning strategy using python, we already detailed the strategy in a previous video using candlesticks patterns and support and resistance levels.
    #TradingBot #PythonCoding #forexanalysis
    🍓 If you want to follow structured courses with more details and practice exercises check my "About" page for Discount Coupons on my Udemy courses covering: Python basics, Object Oriented Programming and Data Analysis with NumPy and Pandas, ... more courses are on the way drop me a message if you have a particular interesting topic! Good luck!
    code is available from the link:
    drive.google.com/file/d/1g-sy...
    00:00 Strategy Backtesting In Python
    02:30 Python Code Candlestick Patterns
    06:40 Using Backtesting.py Library
    13:00 Backtesting Results
    14:05 Strategy Returns

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

  • @fisal-oe2ze
    @fisal-oe2ze 2 года назад +3

    Thanks again, i completely forgot about u r channel, spent the weekend trying to test a strategy, watch a lot of video's and read a lot articles, but no success, but now i watched your video , i am very confidant that i can test the strategy, Thank you so much

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

      I am happy it's been of help, good luck with your strategy

  • @MrSamyWageh
    @MrSamyWageh 2 года назад +3

    Great video as usual. Backtesting topic is always essential for Algo traders. I have reviewed many videos but I admit at least for me this is the first to connect between the two worlds my own algo code flexibility and the backtesting ratios results. May be we can extend it later to Optimisation final step to get best results from varied indicators parameters since we rely here on our script logic not Backtesting optimisation functionality. Finally, thanks a lot for your efforts and the ease to transfer the knowledge. Looking forward to your next videos.

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

      Thank you for your nice support, yes I am intending to investigate more indicators, and mainly try to apply this at the 4hours charts I need to get more signals and higher number of trades, still not convinced with the statistics, but with time I think we will find something nicer.

  • @stanyu5506
    @stanyu5506 Год назад +7

    It's a great work. However, some bug in support/resistance calculation leads to high return ratio. Try to locate this: for subrow in range(row-backCandles+n1, row+1) when create list ss/rr for a row and calculate the signal, it should be : for subrow in range(row-backCandles+n1, row+1-n2). Because when use {row+1}, support/resistance function will calculate n2 row after current row, which is already in a GOD mode. In real trading, we would never know next 2 bars when placing an order.

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

      Nicely explained thank you for sharing. Did you try it? Let us know if it makes a difference in the results.

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

      @@CodeTradingCafe Yep, and return ratio goes back to around 1~2%. It looks normal compared with up to 15% in return :D, it's still a very competitive strategy, and could work nicely after minor modification~~thanks for sharing

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

      Thank you for the results... I have to revisit this strategy and see if it can be improved

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

    Hey man, this is a brilliant video!

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

    Hi! Thanks again for your video! I was wandering if you code your strategy to trade only one operation at time in the backtest stage. What happen if you had a new signal when a past operation was still at market (no TP or SL reachef)? in backtesting is it better trade all the signals or the good idea is to open a new position only after the previous was closed? thank you for providing your point of wiew!

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

      Hi thank you for your support, I usually test one trade opened at a time and no other trade is opened until first one is closed. Unless you have a signal on different currencies then maybe yes you can allow simultaneous trades. Good luck!

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

    Amazing video as always.

  • @matteomaga9466
    @matteomaga9466 11 месяцев назад +1

    Thank you for the video! Where do you get the historical data to run the backtesting?

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

      Thank you for your support, you can get data from yfinance or dukascopy both are free.

  • @randomdude79404
    @randomdude79404 2 года назад +3

    Thank you brother I had requested this , great video as always

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

    First thanks for new video for learning... 🙏🙏 after complete watching i ask questions if i have thanks sir..

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

      Thank you for your comment, Good luck trading.

  • @starvlingk5122
    @starvlingk5122 2 года назад +5

    In my case I found a way to add some randomness to my backtesting to make sure successful trading strategies are not a fluke. I also compare my backtesting strategies to a control system like buying and selling decisions based on coin flips.

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

      Interesting Yes it is good to compare strategies to coin flips but also using the same SL TP methods so this doesn't affect the comparison.

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

    To be honest, this is the best video on this topic… I was struggeling the last days to find a video like this. Thank you so much! I have one question: My strategy works just with buys and sells. So if my strategy gives me a signal of 0 I want you sell, else it‘s 1 and I want you buy… how can I code this in the take profits and stoploss parameters? How can I set my stoploss to signal(0) for buys and the stoploss to signal(1) for my sells?
    Thank you :)

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

      thank you for your nice and supportive comment, for this you will have to open trades without TP or SL values, and use trade close() function when the signal is inverted, of course you need to add a condition when signal goes from 0 to 1 or from 1 to 0 you close the corresponding trade. I hope you'll make it, check the backtesting py website it's a lot of information there.

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

      @@CodeTradingCafe thanks!
      I completely forgot that there is a close function lol.. I will try it tomorrow :)

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

    Wow, very nice Thank you. God Bless you

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

    very good friend. The best explanation on the web abou backtesting library

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

    Awesome video!

  • @letsjohnnylp5533
    @letsjohnnylp5533 11 дней назад +1

    Very nice Video!
    Is there a possibility to get the data aswell?
    And where do you get these giant datasets from?
    Thanks!

    • @CodeTradingCafe
      @CodeTradingCafe  10 дней назад

      Hi, thank you, this video has been out for a while I don't think I can retrieve the data, but you can check the recent videos I always publish csv files as well. I usually get my data from yfinance, my broker or dukascopy. Good luck!

  • @pobchubbington6759
    @pobchubbington6759 2 месяца назад +1

    A way of incorporating higher rewards and losses is leverage. That how you will get a strategy with a high return, although has risks.

    • @CodeTradingCafe
      @CodeTradingCafe  2 месяца назад +1

      Yes but drawdown also increases with leverage, which I am trying to avoid. I don't like to be in the negative for long.

    • @pobchubbington6759
      @pobchubbington6759 2 месяца назад +1

      @@CodeTradingCafe Certainly. Im currently working on an algorithm involving conditional probability.

    • @CodeTradingCafe
      @CodeTradingCafe  2 месяца назад +1

      That's interesting. Keep us informed.

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

    perfect 👌

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

    Cool video thank you again.
    You are a best teacher.
    I have a question about the BTC-USD pair. when i want to use it ,i use it bt = Backtest(df, MyCandlesStrat, cash=1000000, commission=0) but that is not the solution. could you help me ?
    UserWarning: Some prices are larger than initial cash value. Note that fractional trading is not supported. If you want to trade Bitcoin, increase initial cash, or trade μBTC or satoshis instead (GH-134).

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

      Hi yes if the asset which bitcoin is expensive you need to have enough cash in your account to buy, or you can also use some leverage, for example add margin=1/10 in your function arguments (bt = Backtest(..., margin=1/10, ...)).

  • @TheRealEstatePerson
    @TheRealEstatePerson 8 месяцев назад +1

    Question: After I programmed in Python for backtesting a strategy, how can I incorporate that on the charts? Can I pull data on a website? Usually, I trade cryptocurrency, is there a website to pull data in cryptocurrency?

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

      Hi, yes you will need the data, you can either download it for the backtesting or stream for live testing.

  • @user-eh1vh4rj2o
    @user-eh1vh4rj2o 2 года назад +3

    my profit received successfully thank you sir for your faithfulness and honesty it wouldn't be possible without your help God bless you with your company for putting smile on my face again now I and my family are having a good time today thank you sir

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

    sir how to optimize strategy using bactestin.py when signals are calculated outside the strategy class ...

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

      It's better I show this in a video with the details

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

      @@CodeTradingCafe god bless you...

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

      @@thinketh2408 but it will be a while since the list is getting long

  • @raphaelarguello5020
    @raphaelarguello5020 Месяц назад +1

    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%
    And in your code, you don't enter any size, do you know how much is risked per trade?
    Would you maybe have a solution please?
    Thanks for your help!

    • @CodeTradingCafe
      @CodeTradingCafe  Месяц назад +1

      Hi, in Backtesting if you enter size below 1, it will trade with a percentage from the total equity, so 0.1 is 10% of your total equity. If you want more details and you are not in a rush I am preparing a video about lot sizing but it might be a month before I can upload it, it takes too much preparation.

    • @raphaelarguello5020
      @raphaelarguello5020 Месяц назад +1

      @@CodeTradingCafe Thank you for your answer. When I enter below 1, it weirdly does not risk a percentage from the equity but I'll wait for your video, I might find where the problem come from. Thank you, keep doing your great work!

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

    Thanks mate for share this detailed video> shall be grateful if you please share the link for the coding.

  • @Dr.jayfrancis
    @Dr.jayfrancis 2 года назад +6

    This shouldn't be on the net for free 😅

    • @CodeTradingCafe
      @CodeTradingCafe  2 года назад +3

      Lol thank you well some are kept on a side

    • @Dr.jayfrancis
      @Dr.jayfrancis 2 года назад +3

      @@CodeTradingCafe you've got some serious potential. Keep it up

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

    Bro actually i watched the whole video but, I wanted to see how can i backtest my strategy with Lot Size and Leverage which we used in forex differently compared to other markets. if you can help me please make some content on this topic...bcz all the backtesting library are only showing examples of stock or crypto market...thats why i didn't get ans for my question...

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

      Hi check my recent videos I do backtesting with leverage, ruclips.net/video/RbQaARxEW9o/видео.html

  • @athh123
    @athh123 10 месяцев назад +1

    I need to know past years what day mostly make weekly high and low.eg-: Monday 60% Tuesday 20% ....like,but i dont know how to code. Please help ❤

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

      that's relatively simple to code using Pandas, however if you have no coding experience at all it might be a bit hard. Now my opinion is that statistically there will be no special day for high and special day for low prices, I guess it's a uniform distribution.

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

    I think the way which invoke self.init(SIGNAL) is very cool. BTW, how I could add multi signal?

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

      I usually combine multisignals in the dataframe then generate a final signal. Now if you want to execute a trade at ANY signal you can use "OR" logic between different signals to generate your final one. I am not sure my answer is the clearest lol.

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

      @@CodeTradingCafe Thank you for your help. Multisignal in self.init.I(sing1, sig2) did not work ( It must be one series).
      After I tried your proposed method, it actually work well. I convined multisignal into one pandas series (integer 1,2,3...).
      Again, thank you very much!

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

      I am glad it worked, Good luck!

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

    Could you tell me where I can get the csv file

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

      Hi, data can be downloaded from yfinance, dukascopy or some of my other videos I also included data files.

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

    Hey man why is your take profit smaller than you stop loss ? @10:45

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

      Hi, trial and error and for this data it seemed to slightly improve the results, these are not optimised it was just a quick demonstration. That being said, I noticed sometimes putting SL further improved returns because it avoids frequent SL triggering. (SL TP is a topic that needs development... a video :) )

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

      @@CodeTradingCafe Could you be able to backtest the results if I only risk 1-1.5% per trade taken

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

      Well I haven't tried to change the trade lot yet but it must be doable, I think once we do this and maybe add a few rules for SL TP values we would have a complete and ready trading strategy!

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

    can we look for edges in python backtest?

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

      Hi depends what you mean by edges if these are price movement edges then yes we can

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

      @@CodeTradingCafe not the price on the edge, but the other edge. or people use this just to find out how likely the indicator is. I'm sorry because I'm learning to find out about edge

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

      @@swashk2594 ok is it for example the RSI edge? Like the limits up and down?

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

      @@CodeTradingCafe almost close but that's pretty much what it says many successful traders get the edge through backtesting. thank you

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

    Does this strategy work on lower timeframe?

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

      Hi I don't think so, lower time frames are usually more challenging.

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

    Can you Please make a video on...How to deploy these Scripts on Cloud ??

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

      Hi, sorry not my field of expertise, I am more focused on backtesting potential strategies, one day if we find THE strategy then cloud is worth it 🙂

  • @pobchubbington6759
    @pobchubbington6759 Месяц назад +1

    Sell signal as in shorting the stock?

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

      Hi, yes selling/shorting

    • @pobchubbington6759
      @pobchubbington6759 Месяц назад +1

      Amazing stuff, also do you know how to take profits not by a specific value but by time. I want to take profits after the next candlestick - in my case the next hour- my algorithm has a reduction for the next hour, I want to buy at the beginning of the hour and sell when the hour is over no matter the fluctuation. Any tips on this?@@CodeTradingCafe

    • @CodeTradingCafe
      @CodeTradingCafe  Месяц назад +1

      to close trades after one candle you can create a loop over trades (that executes at each candle open) and closes any opened trades if any. that's for one candle duration. If you want more custom duration 2, 3 candles ... you can make the difference between current index and index at which the trade was opened and close the trade accordingly.

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

      @@CodeTradingCafe Do you know how I could do that? So buy at the open price of the current hour candlestick and sell at the close? How would I do that for loop or any other efficient way. I also want to levarge my positions based on confidence of my prediction at any given time. Is it me or does the documentation not give very much information 😂. But Thank you very much for your video I've learnt alot.

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

    Que legal, parabéns pelo conteúdo! Tem ajudado muito! Uma pergunta, se fosse pra fazer com Criptomoedas, como ficaria? Obrigado!
    How cool, congratulations on the content! It has helped a lot! One question, if it was to do with Cryptocurrencies, what would it look like? Thanks!

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

      Muito tempo atras, eu falo portogues ainda entendo ler 🙂
      I think with crypto it works the same however there is not much data since crypto is relatively new so you can test on small dataset

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

      @@CodeTradingCafe obrigado, vou tentar salvar os dados e carregar pra teste

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

      @@rogerinhoramos good luck and best for this year

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

      @@CodeTradingCafe amém, a você também feliz e abençoado 2022

  • @dicloniusN35
    @dicloniusN35 6 месяцев назад +1

    Setting Bokeh output to notebook. This may not work in Jupyter clients without JavaScript support (e.g. PyCharm, Spyder IDE). Reset with `backtesting.set_bokeh_output(notebook=False)

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

      Ah yes I had this problem one time in PyCharm, thank you for the heads up!

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

    signal[row+2] is true. if you using signal[row] backtest is wrong

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

    Make a bot backtesting breakout support and resistance with limit order. I think it high winrate

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

      Nice idea, classic approach but yes I think it's good!

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

      @@CodeTradingCafe coding now sir!

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

      @@kodzuvu good luck!

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

    if you make your date column index result start and end date will be dates

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

      Yes, did you try it?

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

      @@CodeTradingCafe yes. Love your videos great work.

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

    how to use your code?

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

      You need to run it in Jupyter notebook, if you are new to python I suggest you start learning through the previous videos, I have a playlist for learning Python
      Good luck

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

      Thank you.

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

    Moral of the story. If want to use algo, use robot to trade.

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

      Yes but i still can trust a machine over my money I prefer to remain in control, algo is just here as an indicator

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

    Your timeframe is far too large per trade. You need to add in Rollover into your calculation. In forex trading you will generally only trade intraday. Holding a position for greater than a day will incur rollover interest which will eat into your profits.

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

      True in other strategies I try to limit my trades to 2 days max, hopefully it will improve the results.

  • @Aram-SEMO
    @Aram-SEMO Год назад +1

    #كوابيس_سليمان

  • @alexeyabakumov9497
    @alexeyabakumov9497 7 месяцев назад +1

    А можно нормально говорить? На мойве непонятно ничего

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

      Sorry I don't read/understand russian, good luck anyway :)

  • @fisal-oe2ze
    @fisal-oe2ze 2 года назад +1

    so in my strategy , i put the signal , target, and stop each in separate columns , and call there values liek this "sl1 = self.data.Stop[-1]
    tp1 = self.data.Target[-1], but i get ValueError: Long orders require: SL (15835.125) < LIMIT (15877.4415) < TP (15850.48125),what i am doing wrong ?

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

      From your messages looks like the SL and TP are not correct. Try checking the values first in your columns and verify if sl is lower than price for buying positions and higher than price for sell positions, one hint is that the SL should be equal to the price value minus (or plus depending on your trade if it's long or short) the SL distance... Let me know if it works

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

      Also your TP should be greater than the price for long positions, and the error message is pointing to this as an error your TP seems lower than limit value

    • @fisal-oe2ze
      @fisal-oe2ze 2 года назад +1

      @@CodeTradingCafe thx a lot for u r response , now i cant test anymore , i change so much in teh code ,i think i need to redo teh code and start from scratch again :P , then will test and see , again , Thank you so much for u r help

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

      @@fisal-oe2ze yes I know I have been there many times :) patience is the key

    • @fisal-oe2ze
      @fisal-oe2ze 2 года назад +1

      @@CodeTradingCafe the signal triggered on price 15844 that is where the signal column == 1( long), so stop is 15835 and target is 15850, i have no idea where is the 15877 came from. still stuck for now, but I will get back at it tomorrow. Thanks

  • @user-eh1vh4rj2o
    @user-eh1vh4rj2o 2 года назад +5

    my profit received successfully thank you sir for your faithfulness and honesty it wouldn't be possible without your help God bless you with your company for putting smile on my face again now I and my family are having a good time today thank you sir

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

      I am happy for you, hopefully you will always be as lucky, just be careful and always limit your risk.