Python Backtesting Library you should DEFINITELY check out - Backtesting.py
HTML-код
- Опубликовано: 17 июн 2022
- In this video we are going over the very easy to use and handy Backtesting library Backtesting.py and build a SMA crossover strategy. In the end we are playing a bit around with Optimization.
Interesting library, right?
Please subscribe for more content like this!
I am using basically the very well written documentation for everything used in this video with some amendments. Check out the docs here:
kernc.github.io/backtesting.p...
Strategy is explained here:
• Trading moving average...
Video on Backtrader:
• Introduction to BACKTR...
Get the Notebook/Source code by becoming a Tier-2 Channel member:
/ algovibes
Be invited to check out my 1 hour Python course to get started:
www.udemy.com/course/python-p...
DISCLAIMER:
THIS VIDEO IS NOT AN INVESTMENT ADVICE AND IS FOR INFORMATIONAL AND EDUCATIONAL PURPOSES ONLY!
#Python #Backtest #Backtesting
Who else here has accidentally built a backtesting library without realizing there was a nice pre-built option like this out there?
📌
@@Algovibes I appreciate it - thanks!
Ive spent months working through Algovibes videos and have built out a back testing library just over time for myself,
ive recently been playing around with concepts inspired by the JPMorgan video. My use with it is, if you take the 10year treasury bond and VIX index, divide the close values, apply a MACD stratergy to it, then you overlay the dates for triggers and buys onto other assets. Have found that there a feasibility to it in the sense that the overlay ratio stratergy returns are higher than using the MACD on the asset alone, but yeah my backtester provides the information, all the trades etc, plots of application, returns distributions , but yeah thats quite funny that there is an insanely detailed free version out there. Although part of the fun of coding is building it out in the way that im happy with.
Thanks Algovibes!
what's that pre-built option ???
Thanks a lot algovibes for your quick response, luckily problem is sorted out by watching some of your other videos. Great content.
thx a lot buddy, happy to read!
This channel is great. Would love to see some intermediate complexity strategies and then maybe a super in depth video on a very complex strategy.
^^
Thanks a lot man :-) My newest video contains a quite complex strategy (from scratch tho). Be invited to check that out!
Thanks, great video. Would definitely be interested in more in depth tutorial on this, particularly regarding bespoke strategies.
Thank you very much :-)
Also thx for your feedback!
Yes. Definitely a deep drive with your expert intuitive videos. Also teach how to apply backtesting to real trading. How to take trades, shoot trades etc
Awesome. Thanks a lot for your suggestion!
This is genuinely amazing. Would love to see it on aroon crossover strategies and other strategies
Thanks a lot for watching, your comment and your suggestion!
Excellent video thanks! When testing other strategies, e.g an rsi(2) from Larry Connors, I had problems using the rsi indicator from the ta library but the pandas-ta worked fine. Coding indicators from scratch and back testing just using python is time consuming but worth it for the expertise gained.
Thanks, great intro to the back testing lib
Welcome man, thanks for your comment :-)
unbelievable beautiful, thank you
Thanks for watching mate :-)
Excellent article.. please do a video with deep dive strategy end2end
Amazing video, Awesome Resource. Thanks!
Thank you my friend! Happy to read.
thankyou so much for taking time and making such an amazing content
Very welcome! Be invite to check out my other stuff.
Cheers
@@Algovibes sure.
YES SIR VERY GOOD VIDEOS WE WANT TO DEEP DRIVE IN IT.
awesome, thx for your feedback!
Simple and to the point.
exactly my goal! Thanks for watching mate :-)
@@Algovibes
I tried to replicate this but for macd, it returns 0% Return
Edit: nvm. I figured out by passing signals
Excellent
Thank you mate!
Thanks. That Backtesting library looks so powerful.
(It makes me a bit nervous to hand off the calcs to the TA library IYKWIM. I like to understand the whole of how things work.)
Sure! But you could also just define your custom indicator functions containing your own personal calculation.
SCAMMER
love your videos thank you
Thanks a lot buddy :-)
Thx for ur vids, really helpful. In general terms, what’s ur opinion on quantconnect ?
Thanks for watching! Opinion is straightforward: decent.
BTW: Nice Name :D
Yes!!!
Hi! Thanks for the content :) is it possible to minimize a variable? i used minimize but it prompts and error. I want to minimize the drawdown. That point is very important, on the other side can we ask to minimize drawdown and maximize profit at the same time?
Sir, thank you for this amazing tutorial! Could we include leverage in backtest?
Welcome John! Thanks for your comment. Yes, that's possible
great video, let's do some different strategies then try to implement on binance api like the older videos, and put this to the real test!!
Thanks a lot mate
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
😀
you are good man. ❤❤❤
Thanks for your kind words ❤️
This is great
Thanks mate. Happy you like it!
@@Algovibes btw could you please help me? How do I access the traded volume of a coin and import it as we do it with prices in your other videos?
Great Video! :D What is the advantage of doing this in the OOP style?
It's just the way you are inheriting certain methods and properties from the Backtrader/Strategy class and the way the library is supposed to work.
Loving your videos, what's your favourite backtesting library you've seen so far? Want to get started on the right one :)
Also.. would be interested in a deep dive to see if you can implement better Risk Management: layering entries / SL / TP strategy (e.g. SL below previous wick, TP a certain % at next horizontal or after certain Profit % has been hit), and does this have other indicators like BBWP / RSI to be used to improve the Crossover strategy?
Thank you my mate! Well, my favorite approach is coding the strategies from scratch ;-)
Good suggestions, thx! Well you can add all indicators from the ta libraries or even your own individuals ones in the init method.
Thanks for your video. I saw few #Trades, why? Thanks again.
Welcome mate. Can you elaborate?
😳wow thanks
Welcome mate, thanks for watching
I really like this video. Here's another question though. Could you show how you might use the back testing library on, say your Stock Recommendation Class that you made? Given there are three different "strategies" in that Class I'd like to see how you would apply this library to the class structure of the a more complex script. I think it would really hammer home the application.
Thanks a lot Bryan!
Algotrading under your guidance sounds really intriguing... but I am not a programmer and therefore I would like to be able to C&P some of your scripts (like this one ie) and get to test them extensively... both backtesting and FW testing on a demo account. I need to know how to run the scripts , for example on Tradingview. Can you help?
Great Video. Is there any reason why you classify bull, bear, side direction as 2, 1, 3 in the emasignal? I find it will make more sense if they are 1, 0, -1. But I am not sure if you use those number with intention for other unknown purpose.
Hi Stan, sorry quite some time since I recorded this. Can you pass me a timestamp? Thx!
Fan Request - Using TA-Lib and yfinance, can you transform all the indicators of ta-lib into Strong Sell, Sell, Neutral, Buy, and Strong Buy (#1)? And then #2, allow a user to Check box however many indicators they want to calculate an overall average of Sell or Buy?
Thanks a lot for the suggestion! I have done something really similar here:
ruclips.net/video/3WIcaCMJoqA/видео.html
and the follow up video.
Be kindly invited to check that out!
Sick if this tied into Tradingview
I played a bit around with Tradingview & Python if you are interested in that. But yea a direct connection would be convenient indeed.
What other libraries are available for backtesting, that are still being maintained and good support?
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!
Wie immer sehr inspirierend. Geht sowas auch mit komplexen Vorgehen? Z.B. mit einem mtl. Oder wöchentlichen Sparplan? Wann macht es Sinn seine Rate zu erhöhen oder zu senken? Kann man sowas auch backtesten?
Herzlichen Dank :-) Du meinst sowas wie einen cost average Effekt? Prinzipiell ist alles möglich.
So hab ich mir verschiedene coins in verschiedenen marktphasen (bullruns, cryptowinter) angesehen. Sehr gute Erkenntnisse. Danke 🙏 fürs daraufhinweisen.
how can I optimize the Take profit and stop loss ?
Thanks! To backtest on a weekly timeframe, how do you do?>
You can pass weekly data. Either by changing the interval of the pulled data or resampling the data.
Hello Sir, how can we set a trailing stoploss condition with backtesting library? Can you explain it with any basic strategy (such as ema crossover)
Hey Aman, thanks a lot for your comment.
Did you check this:
ruclips.net/video/lKh-NZgnpMQ/видео.html
Was playing around with SL/TP there.
i'm a beginner so i apologize for this question. but the screen when the video begins, what is that and where can i find mine? thank you
Great video as usual! I somehow cant plot the backtest though, there is no data in the graph and i get this error. Do you know how to solve it?
BokehDeprecationWarning: Passing lists of formats for DatetimeTickFormatter scales was deprecated in Bokeh 3.0. Configure a single string format for each scale
Thanks mate. Didn't have this error yet but it is most probably solved by up or downgrading some library.
Have the same issue did you manage to find a solution?
@@alessio491 yep, i always pass this now, works for me:
import backtesting
backtesting.set_bokeh_output(notebook=False)
bt.plot(plot_width=900, reverse_indicators=True)
I Guess you should Trim the data to training and testing before the optimization, and then test with n1 and n2 returned
Good idea!
What IDE are you using? VSC doesn't work similarly, even with a ipynb file
in that case Jupyter notebook but VSC should (not only should but actually works as I am using it frequently) do the job
What if the strategy would be something like buy at certain logic, and sell at certain percentage of the close price (for a bullish trade)?
Definitely possible!
Can this be used to backtest intraday strategies? I have tried feeding intraday data and it gives me an error.
Yes it can and I already used it for that. Can you just double check the other videos where I am using it? Pretty sure I used it on Intraday somewhere.
Which notebook you use for backtesting
Jupyter Notebook for presenting but I am privately using VSC a lot
Thanks a lot god bless you 💖
Hello,
How could we implement our own strategies?
Hi Ahmet,
covered it e.g. here:
ruclips.net/video/lKh-NZgnpMQ/видео.html
@@Algovibes Thanks you so much.
I've tried it and noticed the plot gets messed up (the entries and exits) when testing on lower timeframes. Also doesn't really work well on longer periods with smaller timeframes like 1min, too many candles, plot freezes. So not sure what to make of it, is the results also getting messed up on lower timeframes or is it only the plot?
Thinking it's probably better to code a simple backtester on your own, so you can confirm/know the inner workings.
As I always say: Whatever gets the Job done :-)
Which one do you think its better? Backtesting or Backtrader?
Hard to tell. Backtrader has way more functionalities but Backtesting is way easier to use.
cool
I think so too :-)
everything works but I'm not getting any plots oddly. Using the exact same styntax. I get a output: Row(id="5403",. . .) . The number I used for ID is random as it changes every time. Very good metrics however !
Hmm... hard to say what's the problem. Sometimes downgrading matplotlib does the job for me.
add these lines of code at the top:
import backtesting
backtesting.set_bokeh_output(notebook=False)
and it should work!
Precisely. I can't install backtesting on terminal. I'm using jupyter notebook in VSC.
Hey Algo! I'm following the tutorial and the plotting simply does not work for me (using Jupyter notbook as well).
I get a broken empty chart that is not interactive and basically shows nothing. I have searched extensively in the backtesting.py issue tracker and the fixes did not work for me.
Any idea how to fix this?
I am suspecting it has something to do with JS support on the Jupyter client, based on the warning you got after your imports
Thanks in advance
Hi Rey,
did you try it out with an IDE (Spyder, VSC, PyCharm) with external plotting? Sometimes a downgrade of Matplotlib also does the job.
@@Algovibes
EDIT: Fixed by downgrading package bokeh to bokeh==2.4.3
Tried in PyCharm and VSCode as well and got the same. Downgrading matplotlib sounds interesting. Any particular version you think I should downgrade to?
Do you share your own strategy in one of your videos or do you plan to do so?
I am backtesting, live testing and implementing bots on different strategies on different assets.
This channel is not about selling trading strategies, so basically: No. But I will let you know whenever I find something interesting to share!
how to check optimize parameters
Got a ton of videos like that on my channel. Please check out the Python for Finance playlist or also my course which is linked in the About section!
Hello, nice vid, can you check freqtrade bot?
Thanks man, anything specific you would be interested in?
If I run a backtest using moving averages with n periods, the dataframe will contain Nan values for the first n periods. So the strategy will actually not be backtested at the start date I initially set up. However it will compare with a buy and hold return strategy using the correct dataframe (including the first n periods). So the comparison will actually be flawed. Have you thought about it? What can be done to fix it? I love to hear your German accent on a Sunday, it reminds me of my good friend from Munich haha
You are just dropping the NaN values to get rid of this problem.
I actually did that in my newest video. Be kindly invited to check that!
@@Algovibes I checked my friend but you did not use the backtesting.py in the new video.
I am also having the same issue right now with an ema200 letting many nans in my plot, so I am asking myself if it,s possible to remove empty rows in the strategy class
Where do you get the data?
What exactly do you mean?
@Algovibes The tick data for backtesting. I'm wondering where you pull your data from.
Wie schafft man es das Zeit Interval kleiner wie einen Tag zu bekommen ?
Hab ich in ein paar anderen Video gecovered. Check mal am besten alle Videos in der Python for Finance und cryptobot playlist aus.
Sag bescheid wenn du irgendwas nicht findest.
@@Algovibes Vielen Dank für deine ganze Arbeit und dass du dein Wissen teilst. Pures Gold
@@Algovibes yfinance bietet es garnicht mehr an xd hab die historischen Daten auf Kaggle noch bekommen in nem Minutenchart. Wundert mich aber das die Daten garnicht mehr bereitgestellt werden bzw. ist es schon erschreckend wie schnell der Absatzmark für validierte Daten sind. Hast du noch ne Möglichkeit die Daten BTCUSD in 5min Chart zu ziehen ?
First it was a pain to install TA-Lib, now plot() does not work. #TOFIX pip install --upgrade bokeh==2.4.3
Thanks for sharing your solution! Appreciate your attitude
Where can i find de formula of the return that we get it with command Backtest? Because I think it 's wrong. I have done a normale own backtest for BTC-USD between 2017-6-1 and 2018-2-1 ; n1=8 ; n2=40 and I get a Cuml.return of 225%. NOT 104 % !!!😉
the code showed in this video are not working? i don't know what the real problem is.
It works. Where do you get problems?
Please update the GDrive 😉
Will do so the upcoming days. Thanks a lot for your patience!
I keep getting an Error:
TypeError Traceback (most recent call last)
c:\Users\Desktop\python\PythonParseltongue\backtest-1.ipynb Cell 6' in ()
----> 1 output = bt.run()
File c:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\backtesting\backtesting.py:1137, in Backtest.run(self, **kwargs)
1135 data = _Data(self._data.copy(deep=False))
1136 broker: _Broker = self._broker(data=data)
-> 1137 strategy: Strategy = self._strategy(broker, data, kwargs)
1139 strategy.init()
1140 data._update() # Strategy.init might have changed/added to data.df
TypeError: Can't instantiate abstract class SMAcross with abstract method next
wondering what could be causing this?
Just double check your syntax again. Somewhere you messed up in the method definitions. Just go over the code in the video again and the error will be solved.
i also have the same error as you do, can you tell me where the error is?
Bro, just copy and pasted from official doc.
Exactly, that's my source as clearly stated in the description. I did a follow up video going over a strategy so be sure to check that out! Cheers
Don't use the library it's a trash just use numpy and build your own
Hello, what is the editor that you're using?
Hi mate, using Jupyter here. cheers!