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
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
I am happy it's been of help, good luck with your strategy
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.
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.
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.
Nicely explained thank you for sharing. Did you try it? Let us know if it makes a difference in the results.
@@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
Thank you for the results... I have to revisit this strategy and see if it can be improved
Hey man, this is a brilliant video!
Thank you, I am happy you like it
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!
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!
Amazing video as always.
Thank you for your support 😊
Thank you for the video! Where do you get the historical data to run the backtesting?
Thank you for your support, you can get data from yfinance or dukascopy both are free.
Thank you brother I had requested this , great video as always
Backtesting worked somehow, enjoy it!
First thanks for new video for learning... 🙏🙏 after complete watching i ask questions if i have thanks sir..
Thank you for your comment, Good luck trading.
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.
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.
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 :)
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.
@@CodeTradingCafe thanks!
I completely forgot that there is a close function lol.. I will try it tomorrow :)
Wow, very nice Thank you. God Bless you
Thanks a lot for your support 😊
very good friend. The best explanation on the web abou backtesting library
Thank you for your support 😊
Awesome video!
Thank you!
Very nice Video!
Is there a possibility to get the data aswell?
And where do you get these giant datasets from?
Thanks!
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!
A way of incorporating higher rewards and losses is leverage. That how you will get a strategy with a high return, although has risks.
Yes but drawdown also increases with leverage, which I am trying to avoid. I don't like to be in the negative for long.
@@CodeTradingCafe Certainly. Im currently working on an algorithm involving conditional probability.
That's interesting. Keep us informed.
perfect 👌
Thank you for your support 😊
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).
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, ...)).
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?
Hi, yes you will need the data, you can either download it for the backtesting or stream for live testing.
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
sir how to optimize strategy using bactestin.py when signals are calculated outside the strategy class ...
It's better I show this in a video with the details
@@CodeTradingCafe god bless you...
@@thinketh2408 but it will be a while since the list is getting long
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!
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.
@@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!
Thanks mate for share this detailed video> shall be grateful if you please share the link for the coding.
yes sorry I completely forgot!
Done, let me know if it works
This shouldn't be on the net for free 😅
Lol thank you well some are kept on a side
@@CodeTradingCafe you've got some serious potential. Keep it up
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...
Hi check my recent videos I do backtesting with leverage, ruclips.net/video/RbQaARxEW9o/видео.html
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 ❤
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.
I think the way which invoke self.init(SIGNAL) is very cool. BTW, how I could add multi signal?
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.
@@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!
I am glad it worked, Good luck!
Could you tell me where I can get the csv file
Hi, data can be downloaded from yfinance, dukascopy or some of my other videos I also included data files.
Hey man why is your take profit smaller than you stop loss ? @10:45
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 :) )
@@CodeTradingCafe Could you be able to backtest the results if I only risk 1-1.5% per trade taken
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!
can we look for edges in python backtest?
Hi depends what you mean by edges if these are price movement edges then yes we can
@@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
@@swashk2594 ok is it for example the RSI edge? Like the limits up and down?
@@CodeTradingCafe almost close but that's pretty much what it says many successful traders get the edge through backtesting. thank you
Does this strategy work on lower timeframe?
Hi I don't think so, lower time frames are usually more challenging.
Can you Please make a video on...How to deploy these Scripts on Cloud ??
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 🙂
Sell signal as in shorting the stock?
Hi, yes selling/shorting
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
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.
@@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.
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!
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
@@CodeTradingCafe obrigado, vou tentar salvar os dados e carregar pra teste
@@rogerinhoramos good luck and best for this year
@@CodeTradingCafe amém, a você também feliz e abençoado 2022
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)
Ah yes I had this problem one time in PyCharm, thank you for the heads up!
signal[row+2] is true. if you using signal[row] backtest is wrong
Make a bot backtesting breakout support and resistance with limit order. I think it high winrate
Nice idea, classic approach but yes I think it's good!
@@CodeTradingCafe coding now sir!
@@kodzuvu good luck!
if you make your date column index result start and end date will be dates
Yes, did you try it?
@@CodeTradingCafe yes. Love your videos great work.
how to use your code?
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
Thank you.
Moral of the story. If want to use algo, use robot to trade.
Yes but i still can trust a machine over my money I prefer to remain in control, algo is just here as an indicator
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.
True in other strategies I try to limit my trades to 2 days max, hopefully it will improve the results.
#كوابيس_سليمان
А можно нормально говорить? На мойве непонятно ничего
Sorry I don't read/understand russian, good luck anyway :)
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 ?
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
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
@@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
@@fisal-oe2ze yes I know I have been there many times :) patience is the key
@@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
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
I am happy for you, hopefully you will always be as lucky, just be careful and always limit your risk.