Algorithmic Trading in Python - Bollinger Bands, Trading strategy and Backtest

แชร์
ฝัง
  • เผยแพร่เมื่อ 12 มิ.ย. 2024
  • In this video we will take a look at coding Bollinger Bands in Python, do some amendments and backtest a strategy based on BBs.
    Get the Notebook/Source code by becoming a Tier-2 Channel member:
    / @algovibes
    Video on coding a Trailing Stop Loss:
    • Cryptocurrency 💰 Trad...
    Be kindly invited to incorporate Bolling Band Signals to the Recommender system we have built here:
    • How to build a Stock R...
    If you can extract value out of my videos I would really appreciate you subscribing! Thanks a lot :-)
    0:00 - 02:18 Introduction
    02:18 - 07:20 Coding the calculation of Bollinger Bands
    07:20 - 12:38 Plotting Bollinger Bands
    12:38 - 13:19 Problem of multiple buying/selling signals
    13:19 - 18:50 Coding the strategy (Crossing)
    18:50 - 24:12 Backtest
    24:12 - 25:00 Final thoughts
    This video is not an investment advice and is for educational and entertainment purposes only.
    #Python #Trading #BollingerBands

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

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

    You are amazing, today I'm doing a robo advisor, so I take some popular indicators and this video opens me a great outlook of Bollinger bands, thank you very much!

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

      Thx mate! Appreciate you leaving a comment

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

    Here again , thank you pal

  • @teggy-ggames5103
    @teggy-ggames5103 ปีที่แล้ว +2

    A very comprehensive tutorial... Thank you very much. Would also love to see a beginner trade terms broken down (also in codes).
    Thank you so much

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

      Welcome buddy, thanks a lot for watching!

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

    Your explanation is clear as water

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

      Great to hear, thank you! :-)

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

    Massive thank you :)

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

      Thanks a lot for watching Oscar!

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

    Thanks so much for the vids man your the man

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

      Thank YOU for your support :-)

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

    You’re a legend 🙌🙌🙌

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

      You are for supporting me (-:

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

    Thank you so much ☺️

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

      welcome buddy. Be kindly invited to check out my other stuff :-)

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

    Brilliant

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

    Nice, really good, more video like that

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

      Thanks a lot for your feedback :-)

  • @vardhand.n.8585
    @vardhand.n.8585 2 ปีที่แล้ว +1

    Great coding sir,
    She'll it work for indian indexs

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

      Thanks buddy. Well, try it out :D
      BTW if you need Indian stock market data or are interested in a momentum strategy on the Indian market I got you covered:
      th-cam.com/video/YIsKSQh1xpY/w-d-xo.html

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

    Good vid.... Thanks.

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

      Thanks buddy :-)

  • @HimanshuSharma-bz2gh
    @HimanshuSharma-bz2gh 2 ปีที่แล้ว +1

    Thank you.

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

      Thank YOU :-)

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

    :) I want more. I tried TradeWindow etc now testing PlutoHQ Trading

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

    Video is great and in line with your other videos. Can you do one for rsi + divergence strategy as well if possible

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

      Thank you mate. Already did here: th-cam.com/video/r8pU-8l1KPU/w-d-xo.html

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

    I think it is better to let the signal of BB to trigger a trailing stop and put a condition for buy or sell signal, once the trailing stop is triggered(position close) then enter the new position of signal entry... hope that make sence 😆

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

    Thanks.

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

      Thank YOU :-)

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

    Wonderful video, I subscibed. I am a complete new beginner to python. I want to start learning, so that even i can do these programs.
    How can I start of with learning. Any specific playlists to watch in your channel or any recommendation ?

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

      Thanks for your subscription buddy, appreciate it :-)
      You can check out my Python Introduction playlist and my Python for finance playlist.
      More advanced stuff can be found e.g. in the stock recommender series.
      Wishing you success and joy on your journey!

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

    could you maybe post your code in the video description? would make it easier to copy it and tinker around along your videos! Thx mate!

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

    Interested in your background and what led you to algo trading. Brilliant video btw

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

      Hi buddy, thank you very much! :-)
      Let me try to break it down shortly:
      1. I got deeper into this topic while "writing" (rather coding) my master thesis
      2. I am privately into trading both stocks and cryptos since several years
      3. Have a strong interest in programming and tech topics in general.
      Also it is pretty nicely combinable with my current job which is in the field of Data Science.
      Hope this is giving you some background!
      BTW I remember the greeks (options) from an internship and your name reminds me of it :-D

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

      @@Algovibes Haha, yeah my name was more fun back in 2020 when options were trading a higher premiums because of all the volatility, able to pull 5% a month. Now option selling strategies alone don't provide as good a returns as they did.
      Thanks for your background. It's cool that you decided to get into this area. Definitely difficult, but even more rewarding. Wish you all the success.

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

    Fab video! Could you make a video on how to optimise the parameters of technical indicators? For example, finding what is the most profitable window and standard deviation for bollinger bands?

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

      Hi buddy, thanks a lot :-)
      I already covered the main concepts of that in this one here:
      th-cam.com/video/vWVZxiaaTCs/w-d-xo.html
      But there surely will be more on that.

    • @yigityilmaz2786
      @yigityilmaz2786 2 ปีที่แล้ว

      @@Algovibes Thanks for your answer, found this video yesterday. Keep up the good work, loved your videos! Hopefully, there will be more people interested in algos and you will gain more subscribers soon!

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

    Nice one. I wonder whether you could make it so that the signal triggers when the crossover actually occurred. Your current code only shows the data point that is below the BB but it doesn't imply the crossover has occurred.

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

      Thanks mate, sure that's possible. You would just need to check if the current price is above/below the upper/lower band.

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

    Great video , could you do a video on good projects that one can work on (similar to this (algo trading)) to get a job in quant finance/ algo trading.

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

      Thanks for watching and your suggestion. Appreciate it :-)
      Will see what I can do but here are some thoughts from my side:
      Quantitative finance is a competitive field where in general a technical degree (Master or even PhD) is mandatory.
      Anyhow, when doing projects some general stuff:
      1. Write down in words what you want to trade
      2. Define an entry and exit strategy (including risk management)
      3. Code the strategy
      4. Backtest it
      5. Actually test it using an API in the best case
      6. Automate it by deploying the strategy (Cloud or similar)

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

    🔥

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

    hello,when i type import yfinance or any other import it says"import yfinance could not be found (reportmissingimport), i am not sure why

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

      This problem occurs because you are not writing code in a Python interpreter.
      My guess is that you are using VS Code but I might be wrong with that.
      In case I am right, check this out:
      code.visualstudio.com/docs/python/environments

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

    Hi, great video.
    I have been following Binace Trading in Python.
    is i possible to provide some tips to have Bollinger Bands strategy using Cripto (Binance)?
    I am not sure how to do it because in previous videos you are getting only prices with Websockets-
    Its not clear for me how to achive this. could I use websockets or need I to change back to the method used in very first binance video?

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

      Just I have seen anew video for crypto with SMA. Probably I will get more tips there

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

      Hi buddy, thanks a lot!
      No you can actually do that with streamed data.

  • @johanforsman9011
    @johanforsman9011 2 ปีที่แล้ว

    Ty for your videos! I've been following along with several of them and I've been learning alot! As of yesterday though the yfinance API doesn't seem to work for me :( Same for you?

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

      Awesome. Thanks a lot for watching them and your comment :-) Please check my newest community post. I recently had problems with yfinance as well and solved it with the described step.

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

      @@Algovibes You're the best! This solved my problem! Bonus fun fact, your voice and english dialect sounds exactly like one of my online gaming friends. Watching your videos is like taking lessons from a more tech savvy version of him haha!

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

    Great video, as usual...However, it looks like your loop is only running if the initiating position is a buy. But what happens if the first signal is a sell? You will need to add True to the open_pos. on an opening sell signal. I guess you are only running this to look for opening buy positions, but you might lose out on valuable initiating sell signals. I think that needs to be added to your loop. Just a thought....that video. and coding is great. Keep up the great work

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

      Thank you for your kind words and thank you even more for sharing your thoughts! :-)
      You are right! I actually did that on purpose to only include "complete" trades (so no short selling etc.) but I totally agree with what you said.

    • @onurkoc6869
      @onurkoc6869 2 ปีที่แล้ว

      @@Algovibes same problem can you send updated code? thanks

    • @onurkoc6869
      @onurkoc6869 2 ปีที่แล้ว

      # For generate signals which is buy,sell,buy,sell....(orderly)
      # we don't wanna see consecutive buy or sell signals
      buys = []
      sells = []
      open_pos = False
      for i in range(len(df)):
      if df.upper[i] < df[col][i]:
      if df.upper[i] < df[col][i]:
      if open_pos == False:
      sells.append(i)
      open_pos == True
      elif df.lower[i] > df[col][i]:
      if open_pos:
      buys.append(i)
      open_pos = False
      elif df.lower[i] > df[col][i]:
      if df.lower[i] > df[col][i]:
      if open_pos == False:
      buys.append(i)
      open_pos == True
      elif df.upper[i] < df[col][i]:
      if open_pos:
      sells.append(i)
      open_pos = False

    • @onurkoc6869
      @onurkoc6869 2 ปีที่แล้ว

      sorry actual solution:
      def implement_bb_strategy(data, lower_bb, upper_bb):
      buy_price = []
      sell_price = []
      bb_signal = []
      signal = 0

      for i in range(len(data)):
      if data[i-1] > lower_bb[i-1] and data[i] < lower_bb[i]:
      if signal != 1:
      buy_price.append(data[i])
      sell_price.append(np.nan)
      signal = 1
      bb_signal.append(signal)
      else:
      buy_price.append(np.nan)
      sell_price.append(np.nan)
      bb_signal.append(0)
      elif data[i-1] < upper_bb[i-1] and data[i] > upper_bb[i]:
      if signal != -1:
      buy_price.append(np.nan)
      sell_price.append(data[i])
      signal = -1
      bb_signal.append(signal)
      else:
      buy_price.append(np.nan)
      sell_price.append(np.nan)
      bb_signal.append(0)
      else:
      buy_price.append(np.nan)
      sell_price.append(np.nan)
      bb_signal.append(0)

      return buy_price, sell_price, bb_signal
      buy_price, sell_price, bb_signal = implement_bb_strategy(df[col], df['lower'], df['upper'])

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

    nice! what IDE is this btw?

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

      Thanks man, just Jupyter Notebook.

  • @Claudineionficinal
    @Claudineionficinal 2 ปีที่แล้ว

    Hey, I just made a similar algo that uses bollinger in crypto but Im having a issue while trying to keep my client going. It seems like my stream just get dropped after some hours. How can I make it run indefinitely? Thank you for your videos as always

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

      Hi, which API are you using?

    • @Claudineionficinal
      @Claudineionficinal 2 ปีที่แล้ว

      @@Algovibes Im using the binance client, Im not sure what is his name, its the one that you put your API key and API secret. I request data every minute, which I think its pretty far from the request limit, but still after around 15 hours running I get dropped. I get the error "connection forcibly closed by remote host", but I dont think Im doing anything irregular . Thanks

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

    Great video, unfortunately loop in not working correctly in my case. It returns only buy signals and empty sell list. Please advise

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

      Thanks for your comment, Spasibo :-) Probably a wrong indentation. Can you post your code?

    • @vdzneladze1
      @vdzneladze1 2 ปีที่แล้ว

      @@Algovibes
      buys = []
      sells = []
      open_pos = False
      for i in range(len(df)):
      if df.Lower[i] > df.Close[i]:
      if open_pos == False:
      buys.append(i)
      open_pos == True
      elif df.Upper[i] < df.Close[i]:
      if open_pos == True:
      sells.append(i)
      open_pos ==False

    • @michaelmurphy2924
      @michaelmurphy2924 2 ปีที่แล้ว

      It's a bit late. But the issue is when you are setting open_pos. open_pos == true does not set the value of open_pos it returns whether or not open_pos is true. You need one equals sign to set the value. open_pos = True. You also need to fix this is lower block where you sell and set open pos false.

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

    nice video, but is there a way to make a video about bollinger bands %b?

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

      Hey man, thanks a lot. Didn't plan on that yet but noted it.

  • @ameenpondy
    @ameenpondy 8 หลายเดือนก่อน

    Very good video and your progrmming skill, sorry to say that the strategy is not correct.
    Try BB squeeze out method. You will get good % of returns.
    Thanks for your understanding.

  • @ragha2846vs
    @ragha2846vs 2 ปีที่แล้ว

    Hey thanks for sharing this. Much appreciated!
    I am facing some Json error while downloading data from yfinance. Please help me with this
    json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

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

      Hi buddy, thanks for your comment. Appreciate it! :-)
      Please check my newest community post. I had this problem as well and I got it working again.
      Would be helpful if you can confirm this is solving the problem for you as well (don't forget to restart Jupyter after updating).

    • @ragha2846vs
      @ragha2846vs 2 ปีที่แล้ว

      @@Algovibes
      Thanks for the solution. Your method is worked on solving JSONDecodeError, I guess.
      But I am facing a new error here. Can you please help me out on this as well?
      requests.exceptions.SSLError: HTTPSConnectionPool(host='query2.finance.yahoo.com', port=443): Max retries exceeded with url: /v8/finance/chart/MSFT?period1=1609439400&period2=1627360626&interval=1d&includePrePost=False&events=div%2Csplits (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1125)')))

    • @rajatchouhan6617
      @rajatchouhan6617 2 ปีที่แล้ว

      @@ragha2846vs that's just an internet connection error

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

    Thanks man. Amazing. Please wite one code with kucoin api. Im in iran and i cant use binance api.

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

      Thanks mate. Best greetings to Iran 🇮🇷 I will see what I can do. I have covering another exchange on my to do list. Can't promise it will be Kucoin.

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

    Hi
    Can you combine all your strategies in one programm? Thanks

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

    That is 5% profit on each trade. How many trades were there?

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

    You should give it 10k dollars. And see how it would compound

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

      No, that's a very very bad idea.

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

      @@Algovibes not in real life! I mean 10k fake dollars on the python script. Just to see how it would do with compounding.

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

      @@enzanto Ah, I actually did that in a lot of my other videos. Be invited to check out the Python for Finance and cryptobot playlist.!

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

      @@Algovibes will do! Stumbled upon your channel last night. As I am in a learning period of both python, and stock market it is very interesting.

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

    Loved the video and followed along while coding with you, got all the same results though my x axis doesn' t show dates. I then got up to the plt.scatter for marking Buy_Signal syntax I can't seem to get it to plot. @11:20 and 18:20
    plt.scatter(df.index[df.Buy_Signal], df[df.Buy_Signal].Close, marker = '^', color='g')
    in concatenate(*args, **kwargs).
    The later return of buy and sell points works fine... just the scatter plot seems to be misbehaving.

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

      Thanks for your kind words man. Well that could be a lot of reasons. Can you double check the df.Buy_Signal series? Did the np.where function create a boolean series? I think that might be the problem.

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

    hi! thanks for the vid. I get this error everytime from the yfinance library. : yfinance\base.py", line 285, in history
    df.index = df.index.tz_localize("UTC").tz_convert(
    AttributeError: 'Index' object has no attribute 'tz_localize'
    anyone ever seen this?

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

      Welcome man. When exactly do you get this error?

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

      @@Algovibes appreciate your answer!
      when i put certain intervals in the yf.download function

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

      @@thomazzzzi Just checked. I don't get this error. Can you just update yfinance?

  • @thetagang6854
    @thetagang6854 2 ปีที่แล้ว

    Friend, I seem to get caught in the second line of code. I have all the packages, but it returns this error 'json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)'. Cheers

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

      Yep, I had the same problem. Please check my newest community post. This should solve the error. Please don't forget to restart Jupyter after updating the yfinance lib.
      Would be helpful if you can confirm this is solving your problem!

    • @thetagang6854
      @thetagang6854 2 ปีที่แล้ว

      @@Algovibes Thanks for that, unfortunately no luck, same error. Even after restarting the computer. I googled it, and some are saying it's a problem with yahoo api, but strangely it works for others.

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

    Please message me I would love to work on a project with you, if you are intrested