Risk Management Backtested for Algorithmic Trading in Python (7-Year Backtest)

CodeTrading www.youtube.com

Kurze Zusammenfassung

Das Video demonstriert eine zufällige Trading-Strategie, die auf sieben Jahre historischen Daten von 14 verschiedenen Aktien getestet wurde. Die Strategie basiert auf dem Konzept von Tom Basso, dass mit robustem Risikomanagement und Positionsgrößenbestimmung auch zufällige Einstiege profitabel sein können. Der Fokus liegt auf einer soliden Ausstiegsstrategie mit Trailing Stops und dem schnellen Begrenzen von Verlusten. Durch Backtesting mit Python wird gezeigt, wie diese Strategie eine Rendite von 160% erzielen kann.

  • Zufällige Einstiege in den Markt, entweder Long oder Short.
  • Stop-Loss basierend auf dem ATR (Average True Range), um die Volatilität zu berücksichtigen.
  • Trailing Stop, um Gewinne zu maximieren.
  • Positionsgröße von 1-5% des aktuellen Kontos.

Einführung in die zufällige Trading-Strategie

Der Sprecher stellt eine Trading-Strategie vor, die auf zufälligen Einstiegen basiert und durch Backtesting mit Python überprüft wurde. Die verwendeten Codes und Daten sind frei verfügbar. Die Strategie wurde von Tom Basso inspiriert, der glaubt, dass ein gutes Risikomanagement wichtiger ist als die Vorhersage von Marktbewegungen.

Regeln der zufälligen Trading-Strategie

Die Strategie beinhaltet das Generieren einer zufälligen Richtung (Long oder Short) für den Markteintritt. Ein Stop-Loss wird basierend auf dem ATR (Average True Range) platziert, um die Marktvolatilität zu berücksichtigen. Ein Trailing Stop wird verwendet, um Gewinne zu maximieren, und die Positionsgröße wird auf einige Prozent des Kontos festgelegt. Die Strategie zielt darauf ab, Gewinne laufen zu lassen und Verluste schnell zu begrenzen.

Python-Code und Backtesting-Ergebnisse

Der Sprecher zeigt den Python-Code, der für das Backtesting verwendet wurde. Er verwendet Bibliotheken wie Pandas und TA-Lib zur Berechnung des ATR. Der Code liest CSV-Dateien mit historischen Daten, generiert zufällige Handelssignale und berechnet den ATR. Die Handelssignale werden zufällig generiert, wobei zwischen Long- und Short-Positionen unterschieden wird. Die ATR wird verwendet, um die Stop-Loss-Distanz zu bestimmen.

Funktionen zur Datenverarbeitung und Signalerzeugung

Es werden Funktionen vorgestellt, die CSV-Dateien einlesen, bereinigen und in DataFrames umwandeln. Eine Funktion generiert zufällige Handelssignale (Long oder Short). Der ATR wird mit der TA-Lib-Bibliothek berechnet, wobei ein Standardwert von 10 für die Länge verwendet wird. Eine weitere Funktion fügt dem DataFrame Spalten für die Signalpositionen hinzu, um diese später auf Candlestick-Charts darzustellen.

Anwendung der Funktionen und Datenvisualisierung

Die zuvor definierten Funktionen werden auf die eingelesenen Daten angewendet. Der ATR und die Handelssignale werden zu den DataFrames hinzugefügt. Die Verteilung der Signale wird visualisiert, um sicherzustellen, dass keine bevorzugte Richtung vorliegt. Die Candlestick-Charts zeigen die zufällige Verteilung der Long- und Short-Signale.

Backtesting mit Backtesting.py

Das Backtesting erfolgt mit der Backtesting.py-Bibliothek. Eine Signalfunktion gibt die Handelssignale aus dem DataFrame zurück. Eine benutzerdefinierte Strategieklasse erbt von der Strategieklasse von Backtesting.py. Die Positionsgröße wird auf 1% des Kontos festgelegt, und das Stop-Loss-Verhältnis zum ATR wird auf 3 gesetzt.

Implementierung der Strategie und des Trailing Stops

Die Strategie implementiert Long- und Short-Positionen basierend auf den Handelssignalen. Wenn ein Long-Signal vorliegt und keine offene Position vorhanden ist, wird eine Kaufposition mit einem Stop-Loss platziert, der auf dem ATR basiert. Ein Trailing Stop wird verwendet, um den Stop-Loss bei steigenden Kursen nachzuziehen. Das gleiche Prinzip gilt für Short-Positionen.

Ergebnisse des Backtestings und Optimierung

Die Ergebnisse des Backtestings werden analysiert. Die aggregierten Renditen betragen 42%, der maximale Drawdown liegt bei -6,6%, und die Gewinnrate beträgt 46%. Der durchschnittliche Trade-Return beträgt 1,62%. Es wird die Möglichkeit erwähnt, die Strategie durch Erhöhung der Positionsgröße oder des Hebels zu optimieren, was jedoch das Risiko erhöht.

Experimente mit Risiko und Hebel

Es werden Experimente mit höheren Kommissionen, einer Positionsgröße von 5% und einem Hebel von 1:10 durchgeführt. Eine höhere Positionsgröße führt zu höheren Renditen, aber auch zu einem höheren maximalen Drawdown. Ein höherer Hebel erhöht ebenfalls das Risiko. Der Sprecher kehrt zu sichereren Einstellungen zurück, um das Risikomanagement zu verbessern.

Anpassung und Diversifizierung des Portfolios

Die Ergebnisse mit einer Positionsgröße von 2% und einem Hebel von 1:5 werden gezeigt. Der maximale Drawdown beträgt -12%, was als akzeptabel angesehen wird. Die Equity-Kurven der einzelnen Aktien werden visualisiert, und es wird die Möglichkeit erwähnt, ungeeignete Aktien aus dem Portfolio zu entfernen. Es wird betont, dass Diversifizierung wichtig ist, um Verluste durch Gewinne anderer Aktien auszugleichen.

Fasse jedes YouTube-Video in Sekunden zusammen

Hol dir Zusammenfassungen wie diese für jedes Video, in deiner Sprache, mit der kostenlosen Summ-App.

Laden im App Store
Jetzt bei Google Play

Transkript

Vollständiges Transkript von „Risk Management Backtested for Algorithmic Trading in Python (7-Year Backtest)“. Klicke auf einen Zeitstempel, um das Video an dieser Stelle zu öffnen. Du brauchst ein anderes Video? Nutze den YouTube-Transkript-Generator.

0:00 hi today's strategy was tested on seven years of historical data and 14 different stocks the indicator is totally random so ENT positions don't follow any specific rules except the one of throwing a die I will show you how this random strategy achieved 160% in returns through our automated back test using Python and by the way the code I'll be using in this video and the data files as well are freely available for download from the link in the description so you can replicate the results and experiment a bit with the back testing this concept of random entry trading was introduced by hedge fund manager named Tom basso whose famous idea is that with robust risk management and position sizing even random entries can be profitable so the real Edge in trading comes from a solid exit strategy and not really from

0:47 predicting Market Direction with pinpoint accuracy so here we go I give up the secret it's mostly risk management now let's check some more details about it before the coding and back testing part the strategy we test today follows these rules first we generate a random direction to short or long the market then we open a trade in the generated Direction with a stop-loss distance of n times the ATR or the average true range this way the stop-loss distance is related to the volatility of the market we will use a trailing stop so the stop- loss Will Follow the price in the winning direction to maximize profits and the position sizing is usually few per of the current account we can start with 1% and increase our risk up to 5% position size why do we expect this strategy to work simply because we are letting

1:34 winning trades run to maximize profits and we are cutting losing trades as quickly as possible which will bring the risk reward balance in our favor now let me show you the python code and the back testing results so this is our Jupiter notebook file I'm importing the libraries we will be using so I'm using pandascore technical analysis ta for the indicators we're going to be using this for computing the ATR the average through range the first function read CSV to data frame is used to read CSV files and casting these into a data frame so there's a bit of cleaning here where discarding candles where we have the high equal to low so these are candles where we have no Market movements and so on then this one actually uses the previous function to read a folder because we're going to test our strategy on multiple assets so

2:21 we're going to have multiple CSV files for the different stocks and this function is going to read the whole folder of csvs and we'll cast these into a list of data frames and a list of file names then this is where we generate the uh signal our total signal is actually a random choice between one and two so this is for shorting the market this is for longing the market the function at total signal is going to apply this total signal function to all the rows that we have I'm not vectorizing this we're putting these into a function so as you may have noticed um applying this to each of the rows I know it's less efficient it's simply much easier easier this way if we want to deploy this live on the market so for live trading we're Computing the ATR using this function so

3:06 I'm using Panda's technical analysis again providing the high the low the close and the length so the length by default is 10 this was provided by one of your comments so the person who pointed out this strategy advised to use length equal 10 so we're going to start with this one we can experiment by changing this value later on but for now we're starting with 10 then I have ADD Point position column so that's going to add one more column to the data frame where we uh position or points coordinates that we're going to use later on in the following function in the plot Candlestick with signals in order to be able to plot the uh candles going to show you this on the chart so we plot the candles with these

3:52 signal points so this signal points so the previous function computes the uh positions of these points if the point is below the candle it's a long position if the point is above the candle it's a short position and now we can start using these functions so um providing the folder uh path so I put my data into dataor stocks that's a folder for each of these data frames we're going to add the ATR we're going to add the total signal column as well going to add the points positions for plotting in order to plot some of these charts so a data frame would look like this we have the Open high low closing and volume columns we have the ATR we have the total signal as you can see it's random either short or long for two and then we have the point positions uh related to these uh

4:39 to this total signal column now if you want to compute the um sum of the signals we can use this line it's going to show us that we have 11,000 shorting signals 11,000 long signals we're not going to use all of them simply because when a trade is opened we will not allow for another trade to be opened in parallel so it will be one trade at a time until each trade is closed and now we can use the plot Candlestick with signals just to make sure that we have signals and how the distribution is so looking at the density of the points we know that it's randomly distributed we don't have any privileged or biased signal direction as you can see so it's in both directions on all the chart Candles now to back test the strategy

5:24 I'm using the back testing Pi package first we Define a signal function that's just going to return the uh column total signal from the data frame then we inherit from class strategy uh defining my strategy the size for now is 0.01 and that's 1% of the current account as we have mentioned then we have the ratio stoploss ATR ratio that's the ratio with which we're going to multiply the ATR in order to compute the stop-loss distance we're starting with three but we can optimize it later on and change things automatically between let's say three and 8 see which one will yield the best results for now we're going to keep it this way then we have these two blocks here of instructions this one if the

6:11 signal is two so we have a long signal and we don't have any open positions currently on the market so we allow one trade at a time going to compute the current close which is the self. dat. close minus one so that's the closing price or the most recent candle then we comp compute the stoploss distance which is equal to the current close minus the ratio stoploss ATR ratio times the ATR current ATR of the current candle so that's the uh stoploss distance and we're going to put a buy position with the size and the stop-loss distance so we're not using a takeprofit as you have noticed because we're going to apply a trailing stop for our trades now in the opposite direction if we have a shorting

6:57 signal we're going to do the same now these two are for opening these two blocks are for opening the uh positions the trades and this part here is for trailing the stop it's very important because this is going to make the difference in our strategy so that's how we code the uh trailing stop if the trade is long we're going to change at each step at each closing price for each candle provided we have an open trade going to change the stop- loss position and this is only applied if the price is moving in the uh winning Direction in our profit this is why we put the maximum between the current stop loss or minus infinity actually and this value of the stop loss same here we put the minimum for the shorting part for the

7:44 short uh trades so this is our strategy it's very simple nothing complex here and we're going to run it on all the assets and so now we can aggregate the results I'm checking the aggregated returns that's 42% for now number of Trades is 420 maximum drow down is- 6.6% that's very good and then average drw down was of minus 0.35% a winning rate modestly 46% the best trade is around 200% and the worst trade isus 56% and on average the trade return is 1.62% as you can see it's not a spectacular return so we don't have a lot of a huge number here uh remember

8:31 that this is almost over 7 years of back testing but we can still uh add some assets we just put 14 or 15 stocks we're using the daily time frame again so that's going to be a bit slower than other uh trading strategies however it's kind of safe actually so it is a good in terms of risk management look at the maximum Throwdown it's- 6.6% so that's over 7 years of data and 15 or 14 stocks historical data for stocks so that's quite decent uh versus the 42% returns now I know at this point we want to experiment and make things a bit more exciting so what we can do is by the way I've added commissions here so

9:16 that's a modest commission that would cover the spread and a bit of fees so you can increase it if you want but it's not going to change much actually even if I put five here it's not going to change much because we are using the Daily Time fr frame and so the daily time frame has wider range usually and the trades are going to cover for the um expenses of themselves so uh the winds are usually higher on the daily time frame and fees are not of importance because they are easily covered by the range of the price and the amount you are winning when you have a winning trade so as you can see I've increased I've doubled actually the uh the fees and we just lost a bit like 1% of our aggregated returns so now we are at 4159

10:03 per. I don't think it changes much especially that the maximum drw down is still around minus 6.6% so now to increase our risk I'm going to trade with 5% of the account instead of 1% and we're going to run it again going to run the simulation again the optimization and so on now we can check the results so now we are up to 200 and 7% but also our maximum drow down is minus 29% and the average drow down is minus 1.7% this is not bad but the maximum drw down is huge in my opinion notice also that I'm using a leverage of 1 to five so this is our margin we can also

10:50 increase it 1 to 10 if you intend to increase the risk but this is also going to increase the maximum drow down which is not really aligned with what the original author Tom baso intended he wanted a very safe strategy with a good risk management and now we are going out of the scope of his strategy but anyway we have aggregated returns of 427 per. but then we have a maximum drw down of minus 50% definitely you're not going to trade this we're going to put it back to um the safe Zone let's go back to 2% let's say and the margin of 1 to5 and I'm going to keep the uh

11:36 commissions actually uh as is for now so we're going to run strategy the back test again and just show you the results before we can plot this so we have 78% which is okayish - 12% - 133% as a maximum drow down this is also okay for now now and then average Throwdown of minus 0.7% this is great actually so we're still uh considering this as a safe strategy now we can plot the equities uh depending on the different stocks but you can see that some of them are going down so them some of them are not uh suitable for this strategy some of them are going up dramatically so we

12:22 could also filter some of the stocks just to choose those that are aligned with such approach of trading maybe it can also improve our results but there's no guarantee that if it worked in the past it will still work in the future for some stocks the best way is to do like we are doing here just to diversify the portfolio trade on many different stocks at the same time this is how if one stock is losing it will be compensated by another winning stock and so on so this is it for this video I hope you guys liked it if so you can support the channel by leaving a comment provide some Trading ideas and if you like subscribe and press the like button until our next one trade safe and see you next time

Share

Weitere Video-Zusammenfassungen