How to find the OPTIMAL Stop Loss / Target Profit with Python for a Trading Strategy

แชร์
ฝัง
  • เผยแพร่เมื่อ 19 พ.ค. 2024
  • In this video we are going over finding the best pair of Target profit and Stop Loss levels for a given Trading strategy with the example of a Simple moving average (SMA) crossover strategy. In the end we are doing some stuff like splitting data into training and testing to challenge the recommended parameters. I am working with Intraday Cryptocurrency data here but be invited to test on stocks and other timeframes as well!
    Get the Notebook/Source code by becoming a Tier-3 Channel member:
    / @algovibes
    Comment your thoughts and leave a like if you enjoyed pls :-)
    PREREQUISITES:
    Pull cryptocurrency data:
    • Introduction To Automa...
    SMA explained in general:
    • Trading moving average...
    Iterative Backtesting:
    • INTRADAY Trading Strat...
    Calculate returns:
    • How To Calculate Stock...
    Let me know if you need anything else! :-)
    00:00 - 01:00 Introduction & libraries
    01:00 - 01:49 Pulling Intraday crypto prices
    01:49 - 06:00 SMA Crossover strategy
    06:00 - 11:50 Iterative Backtest
    11:50 - 14:22 Profit Calculation / trading fees
    14:22 - 17:20 Refactoring for Optimization
    17:20 -18:49 Stop Loss/Target Profit arrays
    18:49 - 20:24 Finding best pair of SL/TP
    20:24 - 21:45 Splitting the dataset (talk)
    21:45 - 25:36 Splitting the dataset (code)
    #python #trading #strategy

ความคิดเห็น • 98

  • @Kr3m3rsVids
    @Kr3m3rsVids ปีที่แล้ว +1

    Fantastic! Forward looking bias, overfitting, slicing data, stop loss optimising and so on, all in 1 video and 100% Python!
    Great content, thanks again!

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks a lot for your comment buddy. Appreciate it!

  • @cmrncrick
    @cmrncrick ปีที่แล้ว +4

    Love all your videos! Thank you for such quality education!

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks a ton mate! My pleasure.

  • @vidabask
    @vidabask ปีที่แล้ว +3

    Thanks mate! Keep doing what you're doing. Everytime I watch one of your videos I feel inspired to keep working on my algo trading!
    Question: don't you use CCXT?

    • @Algovibes
      @Algovibes  ปีที่แล้ว +1

      I am not using CCXT for trading (yet). Planning something on it and actually will release an intro video on ccxt today.

  • @kev0dev
    @kev0dev ปีที่แล้ว +1

    This is an awesome video! Thanks so much for you work!

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thank you very much buddy :-)

  • @hosseinvahidi5387
    @hosseinvahidi5387 10 หลายเดือนก่อน +1

    Very intuitive and simple. Thank you.👍

    • @Algovibes
      @Algovibes  10 หลายเดือนก่อน

      Welcome buddy, thanks a lot for watching! :-)

  • @PavelSumik
    @PavelSumik ปีที่แล้ว +1

    Another super video, thank you very much for your great work

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks a ton Pavel!

  • @rajeshnair8872
    @rajeshnair8872 ปีที่แล้ว +1

    Rightly said about np. arrange is really helpful
    Thank you Algo Vibes.

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks buddy. Yea it is quite convenient even tho you can also do that with raw python but with a bit more calculation steps.

  • @anilmm2005
    @anilmm2005 ปีที่แล้ว +1

    Thanks for wonderful set up and explanation

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks for watching buddy

  • @tradingbotspro
    @tradingbotspro ปีที่แล้ว +1

    Hey! Nice video! Thanks a lot for showing your approach of handling stops.
    Looking forward to take a look to the next stage - figuring out how to implement and optimise trailing sl he-he.
    Also, regarding math of this video: what is about DD? Because we calculated tp and sl every time like we have the same position size, but that is not correct since we definitely had got DD from negative trades. Thus, we should either took the bigger leverage or deposit additional money or decrease lot size which would definitely distort the final PnL.
    I understand, that purpose of the video was to explore stops calculation and operation logics, but I would like to pay attention for everyone that there are a tons of moments before some real and working strategy will be done, backtested and optimised :)

    • @Algovibes
      @Algovibes  ปีที่แล้ว +1

      Thanks mate! You made good and correct points and they are all covered in my videos 😁 I just cannot cover everything in every single video.

    • @tradingbotspro
      @tradingbotspro ปีที่แล้ว

      @@Algovibes understood, otherwise it would be a very long videos hehe

  • @ionutoceanu1434
    @ionutoceanu1434 ปีที่แล้ว +1

    Very good explanation and very usefull piece of code. Thanks !

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks a lot buddy. Appreciate your comment :-)

  • @drizham
    @drizham ปีที่แล้ว +1

    Very elegant programming and logic. Very nice

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks buddy. Appreciate your comment! Be invited to check out my other stuff :-)

  • @mahmoodhajipour3680
    @mahmoodhajipour3680 ปีที่แล้ว

    thank you, it was enjoyable to watch this video, would you please use optimization algorithms for this topic?

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Welcome mate. Which one do you have in mind would be interesting for you?

  • @mrrolandlawrence
    @mrrolandlawrence ปีที่แล้ว +1

    great content as ever :)

    • @Algovibes
      @Algovibes  ปีที่แล้ว +1

      Thanks a ton Roland!

  • @rraul
    @rraul ปีที่แล้ว +1

    5 stars content 👏👏👏

    • @Algovibes
      @Algovibes  ปีที่แล้ว +1

      5 star audience! Thanks a lot rraul

  • @saisac7357
    @saisac7357 ปีที่แล้ว +1

    Great work sir...

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks a ton :-)

  • @arunavadatta7734
    @arunavadatta7734 ปีที่แล้ว +1

    This tutorial video is awesome......now make a video with same logic with trailing stoploss instead of static stoploss.

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Cool suggestion. Thanks a lot!

  • @eliotharreau7627
    @eliotharreau7627 ปีที่แล้ว +1

    Very nice Bro. Lets try it. Thnx.👌

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks mate :-)

  • @jitkadyan
    @jitkadyan ปีที่แล้ว +1

    Another Greate Video , very detailed explain , very thankful for your quick response for considering our suggestion. Sir requesting you to also create a video on martingale system trading application with any trading strategy as most of the strategy not produced continue loosing trade more than 4 so can we apply martingale system on that strategy . pls consider if possible. Thanks for your time and sharing these valuable knowledge with us. Thanks a lot

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks a ton and I am extremely grateful for your suggestions man. Always something interesting. I cannot promise anything but I have noted it and will see what I can do.

  • @Niko-ie6dh
    @Niko-ie6dh ปีที่แล้ว +4

    good video, just one remark: you added trading fees but you didnt incorporate slippage. as you do not buy an Open by limitorder, your marketorder would cost you a certain amount of %. The trade exit is done by limit so there you can 1:1 use the price. This is actually very important to keep in mind because it will ruin alot of good-looking paper strategies. 👍🏻

    • @tradingbotspro
      @tradingbotspro ปีที่แล้ว +2

      I think, if we are talking about some highly liquid crypto like btc, eth, etc. and usual individual trader amount of trade - it will be almost without slippage because of relatively small amount of position and high liquidity OR yes you're right we could simply use LO and get exact price. And btw on btc pair there is no fees for a while)))

    • @Algovibes
      @Algovibes  ปีที่แล้ว +2

      Good point on the market order in general. Anyhow I assume the slippage effect on high liquidity cryptos will be too small to make any substantial difference.

    • @Larussiecestlavie
      @Larussiecestlavie ปีที่แล้ว

      ​@@Algovibes the fees for crypto are so high that you don't have to care about slippage

  • @jerrywang3225
    @jerrywang3225 ปีที่แล้ว

    I believe there's a bug here. df.Low < buyprice *0.99, what if the low happens to be on the same candle of the buy signal, so i think we should add index> buydate to our selling condition. Correct me if i am wrong.

  • @alexanderher7692
    @alexanderher7692 10 หลายเดือนก่อน

    how do you pull tradingview data including previous signals from dynamic strat?

  • @mistycsoul
    @mistycsoul ปีที่แล้ว +1

    Good video👍Can you make a video for a optimal sl tp ,for renko strategy?

    • @Algovibes
      @Algovibes  ปีที่แล้ว +1

      Thanks mate. Noted your suggestion!

  • @user-jn1ky7ev2r
    @user-jn1ky7ev2r 2 หลายเดือนก่อน +1

    superb imagetek

    • @Algovibes
      @Algovibes  2 หลายเดือนก่อน

      thx mate :-)

  • @user-co6ku3bo2w
    @user-co6ku3bo2w ปีที่แล้ว +1

    I think it's simpler to generate "Buy" columns use:
    df['Buy'] = (df.SMA_50 > df.SMA_100) & (df.SMA_50.shift() < df.SMA_100.shift())
    Just for reference. By the way, nice tutorial again, Thanks.

    • @Algovibes
      @Algovibes  ปีที่แล้ว +1

      Sure! Also a legit and even better way to do it. Thanks for your contribution.

  • @yanchobeats
    @yanchobeats ปีที่แล้ว +1

    Amazing! Can you feature in your next video how to enter only once per candle even if we get taken out because of stoploss or takeprofit?

    • @tradingbotspro
      @tradingbotspro ปีที่แล้ว +1

      You need just to add additional condition when you are trying to open new position in if statement that there was no sl or tp record in date sell array.

    • @yanchobeats
      @yanchobeats ปีที่แล้ว +1

      @@tradingbotspro Hey, can you drop a few lines on how that might look like, im new to coding :D

    • @tradingbotspro
      @tradingbotspro ปีที่แล้ว +1

      @@yanchobeats i posted msg with explanation but it was not published. Will try again.

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks mate. Sorry, maybe I am a bit tired but can you elaborate on your suggestion? Thanks!

    • @yanchobeats
      @yanchobeats ปีที่แล้ว

      @@Algovibes Hey mate, I think it would be awesome to show how to enter a trade only once per candle, if you get taken out of that trade because of stoploss or takeprofit, the algo does not re-enter that candle, it has to wait for a new one to form. My algo right now is entering non stop on a candle when it gets taken out, and a entry once per bar no matter what seems great. I have this strategy on tradingview, there i use the "close" function and it works there perfectly, it enters once per bar no matter what. I think that would be greatly beneficial and cool as a strategy for your channel. If you want I can show you some screenshots for more context? Thank you for the great work bro!

  • @kitbodeephongkasem909
    @kitbodeephongkasem909 ปีที่แล้ว +1

    please show video how to optimize tp and sl in multitime frame ?

    • @Algovibes
      @Algovibes  ปีที่แล้ว +1

      Cool idea, thanks a lot.
      Maybe interesting for you: Multi Timeframe strategy:
      th-cam.com/video/YXjEN9vI-aU/w-d-xo.html

  • @denniscarver9147
    @denniscarver9147 ปีที่แล้ว +1

    Hey Algo, how can I do this by testing a portfolio? Instead of a single stock or crypto, a portfolio of positions that meet our buy criteria?

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Yea sure! Also possible. I have videos on backtesting large amount of cryptos and stocks both in my Python for Finance and cryptobot playlist. Be invited to check that out!

  • @Larussiecestlavie
    @Larussiecestlavie ปีที่แล้ว +1

    very good video, but what if the stoploss and take profit get hit both at the same time step?

    • @Algovibes
      @Algovibes  ปีที่แล้ว +1

      Thanks mate. To avoid that you need more granular data. I think I am also mentioning that some when in the video.

  • @Ejnota
    @Ejnota 10 หลายเดือนก่อน +1

    ¡Gracias!

    • @Algovibes
      @Algovibes  10 หลายเดือนก่อน

      Thanks buddy! :-) Appreciate your support

    • @Ejnota
      @Ejnota 2 หลายเดือนก่อน

      One question, if the open is the one that is shifted and the iteration over the rows gos row by row, then why you compared the row.Low of that particular row if that row already passed, shouldn't we compared with row.Low of the next row?
      @@Algovibes

    • @Ejnota
      @Ejnota 2 หลายเดือนก่อน

      Could happen that the stop lost of take profit is triggered over a row that has past already

    • @Ejnota
      @Ejnota 2 หลายเดือนก่อน

      I just realized that it could be fixed adding an elif in the first if

  • @InspiringVibesVideos
    @InspiringVibesVideos ปีที่แล้ว +1

    Thanks for the Tutorial, Can you share the code so it is easier to code in colab? Thank!

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Welcome mate. Sure! Code is available here:
      th-cam.com/channels/87aeHqMrlR6ED0w2SVi5nw.htmljoin
      Looking forward to your mail! :-)

  • @ionutoceanu1434
    @ionutoceanu1434 ปีที่แล้ว +1

    Valuable content sir. The only issue that I found is the calculation of relative profits reported to buyprice.
    I think it should be:
    profits = pd.Series([((sell-buy)/buy)*100 for sell,buy in zip(sellprices, buyprices)])
    print(profits.sum())

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Thanks mate. No You cannot do that.
      I explained why you can't do that here:
      th-cam.com/video/fWHQwqT3lNY/w-d-xo.html
      Let me know if you need any more input!

  • @lorenzobaggi161
    @lorenzobaggi161 ปีที่แล้ว +1

    top player

  • @AshishKumar-oe2sx
    @AshishKumar-oe2sx ปีที่แล้ว +1

    Is theres a method where we can get the number of stop loss hit in the intraday and if once the desired profit is achieved then to leave the marker ... In short we want to backrest how many times does the indicator fails in the intraday.

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Sure, that's definitely possible!

  • @satyamARAS
    @satyamARAS ปีที่แล้ว +1

    Nice

  • @alexanderher7692
    @alexanderher7692 10 หลายเดือนก่อน +1

    do you have the code somewhere in open repo?

    • @Algovibes
      @Algovibes  10 หลายเดือนก่อน

      Even better! You have the opportunity to support my channel and get access to the code:
      th-cam.com/channels/87aeHqMrlR6ED0w2SVi5nw.htmljoin
      Looking forward to see you there!

  •  ปีที่แล้ว +1

    Welche Börse benutzt du ? FTX ist schon mal nicht. Binance kann keine Futures in der EU. Bleibt noch Phemex und so ähnliche. Schiele auch auf einen institutionellen Accout.

    • @Algovibes
      @Algovibes  ปีที่แล้ว +1

      Ne FTX habe ich glücklicherweise nie benutzt. Ich hab nur mal ein bisschen mit deren API rumgespielt. Ich handle aktiv momentan spot auf Binance, Optionen/Futures hatte ich mal bei Delta gecheckt, allerdings crasht deren API permanent bei mir und ist daher produktiv nicht nutzbar für mich. Ich will die short Seite wieder traden, daher bin ich auch immer auf der Suche nach guten Alternativen zu Binance.

    •  ปีที่แล้ว +1

      @@Algovibes ich schau mir gerade phemex an und recherchiere erstmal nach Standort, Support, Sicherheit und api quality.

  • @titucartoon
    @titucartoon ปีที่แล้ว +1

    Hi Sir This Is Biplov From India I am really help full from you but one thing sir when i code it it showing
    import pandas as pd
    import numpy as np
    from binance.client import client
    client = client()
    ModuleNotFoundError Traceback (most recent call last)
    Cell In[1], line 3
    1 import pandas as pd
    2 import numpy as np
    ----> 3 from binance.client import client
    4 client = client()
    ModuleNotFoundError: No module named 'binance.client'; 'binance' is not a package
    plz help me

    • @Algovibes
      @Algovibes  ปีที่แล้ว +1

      Just install the binance library. Should the solve the issue. Greetings to India :-)

    • @titucartoon
      @titucartoon ปีที่แล้ว +1

      @@Algovibes 🙏🙏🙏👍🏻

    • @titucartoon
      @titucartoon ปีที่แล้ว

      Sir have you any mail???

  • @welcometomathy6944
    @welcometomathy6944 ปีที่แล้ว +1

    Last time I did that king of code I got 150/150 Tp/SL long and 1000/350 Tp/SL short xD

  • @borism4849
    @borism4849 ปีที่แล้ว

    It's called a fragile strategy according to Taleb.

    • @GeeNee25
      @GeeNee25 ปีที่แล้ว

      Why is it so? Can you explain or give a reference, please?

    • @borism4849
      @borism4849 ปีที่แล้ว +2

      @@GeeNee25 With this strategy you make a lot of small gains (1%) but when you lose, you lose big (4%). With this strategy, you have a high probability of making smaller gains and a lower probability of making big losses. If you try this strategy on the SPY during a bear market, you will see that this strategy underperforms massively.

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Yep. I would be very cautious with this as well.

    • @denniscarver9147
      @denniscarver9147 ปีที่แล้ว

      @@borism4849 I think a filter would be helpful in that situation. Something to identify the regime change ( bull to bear). I don't know for sure.

  • @mrnobody2492
    @mrnobody2492 ปีที่แล้ว

    Hast du schon selber einen Trading bot am laufen ? Das muss doch laufen wie sau

  • @ko-prometheus
    @ko-prometheus ปีที่แล้ว +1

    ☢☢☢☢☢

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      😁thx for watching buddy

  • @timwaldau1649
    @timwaldau1649 ปีที่แล้ว

    Hi, cool stuff! Thank you! ... but in my point of view there is a little issue.
    In some cases it could be that both conditions apply (if row.Low < buyprice * 0.99:... elif row.High > buyprice * 1.01:).
    In a 4h timeframe and higher volatility the candle low and the candle high could touch both - the sl- and also the tp-price within one candle. But which of both first?
    ... In this case it is theoretically necessary to zoom in a smaller timeframe to find out which high or low was first.
    I'm wrong?
    Here an example with a assumed buyprice (next time stamp open) of 41k
    buyprice=41000
    # 41000 * 0.99 = 40590
    # 41000 * 1.01 = 41410
    Low=40500
    High=41600
    if Low < buyprice * 0.99:
    sellprice = buyprice * 0.99
    print("sellprice SL: {}".format(sellprice))
    print()
    elif High > buyprice * 1.01:
    sellprice = buyprice * 1.01
    print("sellprice TP: {}".format(sellprice))
    print()
    '''
    sellprice SL: 40590.0
    '''
    # 'elif' is only applied if the first condition is false...

  • @vannikuhs674
    @vannikuhs674 ปีที่แล้ว

    Prⓞм𝕠𝕤𝐌