Multiple Timeframes Trading: Build Custom Indicators in Python

Поделиться
HTML-код
  • Опубликовано: 18 окт 2024

Комментарии • 53

  • @johndemp4483
    @johndemp4483 13 дней назад +1

    always enjoy your videos, think it would make more sense to have sell signal = -1 and buy signal = +1 instead of 1 & 2, ideally you shouldn't need to download 2 different time frames, there must be a way to aggregate 6 (6x4=24H) candles on the 4H timeframe to make a 1D time frame.

    • @CodeTradingCafe
      @CodeTradingCafe  12 дней назад

      Hi, thank you. Actually yes I thought we could aggregate candles into one larger candle... maybe a new video idea!

  • @nkwebikarome4764
    @nkwebikarome4764 2 месяца назад +1

    Thank you very. Missed your content
    Still trying to learn and this is very helpful.

    • @CodeTradingCafe
      @CodeTradingCafe  2 месяца назад

      Glad it was helpful! Keep up the learning it must work at some point.

  • @vassiliscapsis5828
    @vassiliscapsis5828 3 месяца назад +2

    Once again a great video !!! Thank you !!! I like the idea of the utils file and the ffill method is also amazing !!!

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад +1

      Thank you Vassilis your contribution is much appreciated.

  • @PeterPankowski
    @PeterPankowski 3 месяца назад +1

    Outstanding done as usual.....🤩
    Improvement would be instead circles a triangle up or downl.....
    There are also other libraries for charting... I m not so a fan of this one... what about a tradingview similar chart.... this would be amazing!

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад

      Hi thank you! do you have any packages suggestion in python for better vis quality?

  • @rainnerl
    @rainnerl 3 месяца назад +1

    i have a strategy i like you would try, based on the two timeframe approach , On the 1H time frame we detect the trend using 3 emas(50-100-200) and also if the MACD Histogram if Decreasing we can say the trend is Bearish, and if the 3 emas are bullish and the MACD histogram is Increasing we can say the trend is bullish, then we can go to a lower timeframe, e.g 5m or 15 m and look for an entry based on the same approach, the signal based on the trend of the 3 emas, and a trigger based on the MACD

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад

      Hi, thank you for sharing I will add it to the list, but 2 things:
      1- it will be couple of months before the video
      2- Can't promise it will work

  • @kobiyobi629
    @kobiyobi629 3 месяца назад +1

    great video as always. the signals on the 4H will not show up until the 1D is complete and calculated correct?

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад +1

      Yes, true, so I guess we need to check the previous day signal in this case.

  • @guillermoguerra3836
    @guillermoguerra3836 3 месяца назад +1

    Hi, I really admire your work, a few months ago I started to do my own coding and I have found the best bases for operations in your courses and your videos. I would like to know if it is possible to replicate a WWA trading strategy of Alex Garcia or Waqar Asim where they try to decrease the stop loss to the minimum so that even if you do not enter the trade the number of trades where you make entries are of large proportions. It is a scalping strategy but theoretically generates profits much higher than the losses with trades where operations are made with the risk of 1% to 100% profit. Thanks again for all your content, I will continue to follow your videos.😁

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад

      Hi, in theory anything is possible using python. But I will need to check the details and see how complex the implementation would be. If it works I will make a video about it.

  • @boamahmarcus4002
    @boamahmarcus4002 3 месяца назад +3

    4 hour is my favorite time frame

    • @sinan_islam
      @sinan_islam 3 месяца назад +2

      4 hour and 4 minute is my favorite time frame

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад

      it's a balanced timeframe not too noisy nor too slow and it goes well with the daily analysis too.

    • @boamahmarcus4002
      @boamahmarcus4002 3 месяца назад +1

      @CodeTradingCafe I have to back test this 🤣

  • @stjepanherceg7365
    @stjepanherceg7365 3 месяца назад +1

    Just an idea for possible multitimeframe analysis: Use 10 and 20 EMAS, if 10 above 20 it's a bullish trend, if 20 is above 10 it's a bearish trend. If you have a bullish trend on the 4h and 1h, track the 5 minute that needs to switch from bearish into bullish -> buy signal. If you have a bearish trend, do the opposite. Would you try this idea or is it too trivial?

    • @vassiliscapsis5828
      @vassiliscapsis5828 3 месяца назад

      What about adding some extra emas on your chart? If you have a 10 ema on a 15 min chart and you add a 40 ema on the chart is like seeing what is happening on the 1H chart (1 hour = 4 15min). Same for the 4H. Add a 160 ema on your 15min chart. I know that the ema is putting more weight on the recent candles but anyway in trading everything is relative. There are indicators (in Metatrader for example) that will plot an ema from higher time frames and it will usually look like a staircase because the value of the indicator will remain the same during the 8 15m candles.

    • @stjepanherceg7365
      @stjepanherceg7365 3 месяца назад

      @@vassiliscapsis5828 Yes, essentially the EMAs can account for different timeframes already, but it's still a multitimeframe approach worthy of testing. It's about lower TF trend realigning with the higher TF trend and using that fact to define entries and exits.

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад +3

      Vassilis has a point, it's actually true moving averages can be easily translated in between timeframes, I am more curious about let's say support resistance levels on Daily then we use these as strong levels on the hourly for example. Moving average might also be interesting... there is only one way to find out :) I will spare a day for this

    • @stjepanherceg7365
      @stjepanherceg7365 3 месяца назад +2

      @@CodeTradingCafe Yes I understand that EMA can easily account for different timeframes, I just spelled it out that way because I didn't want to calulate the exact lengths that correspond to the 1 hour 20 ema on a 5 minute chart and so on. But you get the idea. It's mostly about a trend realignment setups. It could be good to impose a minimum countertrend duration on the 5 min chart. That way, when the realignment happens, it's more meaningful. Either way, I'm happy you'll try to backtest any type of such strategy! Thanks for these instructional videos and your efforts!

    • @judecosmo8503
      @judecosmo8503 3 месяца назад

      Tried this already. Not as easy as it sounds

  • @jroche1832
    @jroche1832 3 месяца назад

    Another potential approach is to run leveraged vs unleveraged or rotation strategy. If close on say SPY is under 50 MA (or whatever) then buy XLU (for example). If over 50 MA sell any XLU and buy UPRO (3x levered). All the other methods apply ie TP/SL etc

    • @jroche1832
      @jroche1832 3 месяца назад

      Here's the code. import yfinance as yf
      import pandas as pd
      import numpy as np
      from datetime import datetime, timedelta
      from backtesting import Strategy, Backtest
      # Download data
      end_date = datetime.now()
      start_date = end_date - timedelta(days=5*365)
      spy = yf.download('SPY', start=start_date, end=end_date)
      xlu = yf.download('XLU', start=start_date, end=end_date)
      upro = yf.download('UPRO', start=start_date, end=end_date)
      # Calculate 50-day MA for SPY
      spy['MA50'] = spy['Close'].rolling(window=50).mean()
      # Define the strategies
      class XLUStrategy(Strategy):
      def init(self):
      self.spy_close = self.I(lambda: spy['Close'])
      self.spy_ma50 = self.I(lambda: spy['MA50'])
      def next(self):
      if self.spy_close[-1] < self.spy_ma50[-1]:
      if not self.position:
      self.buy()
      elif self.spy_close[-1] >= self.spy_ma50[-1]:
      if self.position:
      self.position.close()
      class UPROStrategy(Strategy):
      def init(self):
      self.spy_close = self.I(lambda: spy['Close'])
      self.spy_ma50 = self.I(lambda: spy['MA50'])
      def next(self):
      if self.spy_close[-1] >= self.spy_ma50[-1]:
      if not self.position:
      self.buy()
      elif self.spy_close[-1] < self.spy_ma50[-1]:
      if self.position:
      self.position.close()
      # Run backtests
      bt_xlu = Backtest(xlu, XLUStrategy, cash=10000, commission=.002)
      stats_xlu = bt_xlu.run()
      bt_upro = Backtest(upro, UPROStrategy, cash=10000, commission=.002)
      stats_upro = bt_upro.run()
      # Calculate combined results
      combined_return = (stats_xlu['Return [%]'] + stats_upro['Return [%]']) / 2
      combined_value = (stats_xlu['Equity Final [$]'] + stats_upro['Equity Final [$]']) / 2
      combined_max_drawdown = (stats_xlu['Max. Drawdown [%]'] + stats_upro['Max. Drawdown [%]']) / 2
      # Calculate buy and hold returns and max drawdowns
      def calculate_max_drawdown(data):
      peak = data['Close'].cummax()
      drawdown = (data['Close'] - peak) / peak
      max_drawdown = drawdown.min() * 100
      return max_drawdown
      xlu_buy_hold_return = (xlu['Close'][-1] / xlu['Close'][0] - 1) * 100
      upro_buy_hold_return = (upro['Close'][-1] / upro['Close'][0] - 1) * 100
      xlu_buy_hold_max_drawdown = calculate_max_drawdown(xlu)
      upro_buy_hold_max_drawdown = calculate_max_drawdown(upro)
      # Print results
      print(f"XLU Strategy Return: {stats_xlu['Return [%]']:.2f}%")
      print(f"XLU Strategy Max Drawdown: {stats_xlu['Max. Drawdown [%]']:.2f}%")
      print(f"UPRO Strategy Return: {stats_upro['Return [%]']:.2f}%")
      print(f"UPRO Strategy Max Drawdown: {stats_upro['Max. Drawdown [%]']:.2f}%")
      print(f"Combined Strategy Return: {combined_return:.2f}%")
      print(f"Combined Strategy Max Drawdown: {combined_max_drawdown:.2f}%")
      print(f"Combined Strategy Final Value: ${combined_value:.2f}")
      print(f"XLU Buy and Hold Return: {xlu_buy_hold_return:.2f}%")
      print(f"XLU Buy and Hold Max Drawdown: {xlu_buy_hold_max_drawdown:.2f}%")
      print(f"UPRO Buy and Hold Return: {upro_buy_hold_return:.2f}%")
      print(f"UPRO Buy and Hold Max Drawdown: {upro_buy_hold_max_drawdown:.2f}%")

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад

      Thank you for sharing. Rotation was requested also previously, I will research a managed strategy for a video.

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад +1

      Just saw the code that you shared, thanks a lot I will try it and see maybe put it in a video.

  • @sanjib77424
    @sanjib77424 Месяц назад +1

    Can i use this code for tradingview pine editor?

    • @CodeTradingCafe
      @CodeTradingCafe  Месяц назад

      I don't think so, you will need to translate python into pine.

  • @agxgaming2327
    @agxgaming2327 2 месяца назад +1

    bro you can talk about how to create strategy in Indian stock market because this market always (new days) show gap Up and gap Down so you tell about how to create strategy code in Indian stock market 😐

    • @CodeTradingCafe
      @CodeTradingCafe  2 месяца назад

      Hi, I have no experience in the Indian market I wouldn't know what's best, you can adapt any of my codes to the asset of your choice though, it might work.

    • @agxgaming2327
      @agxgaming2327 2 месяца назад

      @@CodeTradingCafe ok thanks 😊

  • @tingchan4605
    @tingchan4605 3 месяца назад +2

    You only know a date is rejection only when the day is over, therefore you cannot forward fill this rejection signal to the lower time frame, you are seeing the future!

    • @ziadfrancis9035
      @ziadfrancis9035 3 месяца назад

      Well spotted, in this case yes but you can also generate the signal for the previous day to avoid lookahead bias.

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад +1

      we can shift the signal by one day to avoid this. Thanks again for sharing.

  • @Eddie-mh6bl
    @Eddie-mh6bl 3 месяца назад +1

    This looks like future bias though... If the daily forms a local maximum at, say, 1PM, this method then paints all the H4 candles of that day as being part of that rejection... But the first 3 H4 candles happened before 1 PM so, the H4 signal leaks information from the future, no? So any algo using the combined data would suffer future bias. Am I missing something?

    • @vassiliscapsis5828
      @vassiliscapsis5828 3 месяца назад +1

      I see your point, I will agree with you that in order to "see" a rejection on the daily, the day must be closed first. We do not know what the final strategy will look like, most probably will check if the previous day was a rejection so that we can catch an early move on the current 4H chart. Today's video is showing the technique of two different time frames using the ffill method

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад +1

      Totally agree with you the example shown in the video has a look ahead bias, I suggest shifting the daily signal by one day so you basically detect the rejection in the previous day and use this info today on the 4H timeframe... just as an example but then the possibilities are endless.

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад

      @vassilis you got my point right just showing the tool but still need to use this in a full strategy... I will look for a good one.

  • @80sVectorz
    @80sVectorz 3 месяца назад +2

    Be very careful when doing multi timeframe stuff. I've been cooked by accidental future leak.
    Specifically, when I sampled the 1h bars into minute bars and used those resampled hourly candle data. Which caused future leak.

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад +2

      I totally agree this was flagged by many comments, for now the solution is to consider the previous candle signal on the higher timeframe instead of the current candle. Like on the daily we check signals for the previous day not the current day. Thanks for sharing this, data leak is a curse while backtesting.

    • @octoii2418
      @octoii2418 2 месяца назад

      What is a future leak?

    • @80sVectorz
      @80sVectorz 2 месяца назад +1

      @@octoii2418 It's when you (accidentally) show the algo data that's in the future while back testing

  • @stockTr
    @stockTr 2 месяца назад +1

    Where do we get the utilis file?

    • @CodeTradingCafe
      @CodeTradingCafe  2 месяца назад

      It's shared in the link from the description, the whole folder with complete files.

  • @FatihVardar
    @FatihVardar Месяц назад

    Hi when i tried to add to code at the first line it says : 1/1 Script coulnt be translated from :null
    What should i do ? i couldnt use the code