Multiple Timeframes Trading: Build Custom Indicators in Python

  Рет қаралды 9,592

CodeTrading

CodeTrading

Күн бұрын

Welcome back! In today's tutorial, we explore how to build an advanced indicator that operates on multiple timeframes in parallel, and translates signals from one timeframe to another. We will use the daily and 4-hour timeframes as examples. I will guide you through creating a custom indicator in Python on the daily timeframe and translating the signal into the 4H timeframe. This method can be applied to any timeframe you desire. The Python code used in this video is available for download from the link below, along with the data files for your experiments. Multi-timeframe analysis provides a clearer picture of market trends and reduces noise. In this video, we will identify rejection candles on the daily timeframe and transmit the signal to the 4H timeframe, allowing us to combine daily signals with patterns occurring on lower timeframes for confirmation. Coding and testing this in Python will definitely enhance your understanding of the details and improve trading your strategy with multi-timeframe analysis.
°°° Discount Vouchers for my Algorithmic Trading and Python courses:
💲 Algorithmic Trading: bit.ly/CouponA...
💲 Data Analysis with Numpy and Pandas: bit.ly/CouponD...
💲 Machine Learning Methods In Algorithmic Trading: bit.ly/CouponM...
Download the code and the data files... and enjoy coding:
drive.google.c...
#backtesting #algorithmictrading #tradingsignals #timeframe #tradingmethods #tradingstrategy

Пікірлер: 51
@vassiliscapsis5828
@vassiliscapsis5828 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 2 ай бұрын
Thank you Vassilis your contribution is much appreciated.
@nkwebikarome4764
@nkwebikarome4764 2 ай бұрын
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.
@rainnerl
@rainnerl 2 ай бұрын
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 2 ай бұрын
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
@PeterPankowski
@PeterPankowski 2 ай бұрын
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 2 ай бұрын
Hi thank you! do you have any packages suggestion in python for better vis quality?
@boamahmarcus4002
@boamahmarcus4002 2 ай бұрын
4 hour is my favorite time frame
@sinan_islam
@sinan_islam 2 ай бұрын
4 hour and 4 minute is my favorite time frame
@CodeTradingCafe
@CodeTradingCafe 2 ай бұрын
it's a balanced timeframe not too noisy nor too slow and it goes well with the daily analysis too.
@boamahmarcus4002
@boamahmarcus4002 2 ай бұрын
@CodeTradingCafe I have to back test this 🤣
@stjepanherceg7365
@stjepanherceg7365 2 ай бұрын
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 2 ай бұрын
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 2 ай бұрын
@@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 2 ай бұрын
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 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 2 ай бұрын
Tried this already. Not as easy as it sounds
@jroche1832
@jroche1832 2 ай бұрын
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 2 ай бұрын
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 2 ай бұрын
Thank you for sharing. Rotation was requested also previously, I will research a managed strategy for a video.
@CodeTradingCafe
@CodeTradingCafe 2 ай бұрын
Just saw the code that you shared, thanks a lot I will try it and see maybe put it in a video.
@guillermoguerra3836
@guillermoguerra3836 2 ай бұрын
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 2 ай бұрын
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.
@kobiyobi629
@kobiyobi629 2 ай бұрын
great video as always. the signals on the 4H will not show up until the 1D is complete and calculated correct?
@CodeTradingCafe
@CodeTradingCafe 2 ай бұрын
Yes, true, so I guess we need to check the previous day signal in this case.
@tingchan4605
@tingchan4605 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 2 ай бұрын
Well spotted, in this case yes but you can also generate the signal for the previous day to avoid lookahead bias.
@CodeTradingCafe
@CodeTradingCafe 2 ай бұрын
we can shift the signal by one day to avoid this. Thanks again for sharing.
@sanjib77424
@sanjib77424 9 күн бұрын
Can i use this code for tradingview pine editor?
@CodeTradingCafe
@CodeTradingCafe 7 күн бұрын
I don't think so, you will need to translate python into pine.
@agxgaming2327
@agxgaming2327 2 ай бұрын
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 Ай бұрын
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 Ай бұрын
@@CodeTradingCafe ok thanks 😊
@stockTr
@stockTr 2 ай бұрын
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 18 күн бұрын
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
@CodeTradingCafe
@CodeTradingCafe 17 күн бұрын
Hi you need to run it in jupyter notebook.
@Eddie-mh6bl
@Eddie-mh6bl 2 ай бұрын
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 2 ай бұрын
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 2 ай бұрын
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 2 ай бұрын
@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 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 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 Ай бұрын
What is a future leak?
@80sVectorz
@80sVectorz Ай бұрын
@@octoii2418 It's when you (accidentally) show the algo data that's in the future while back testing
Cute
00:16
Oyuncak Avı
Рет қаралды 11 МЛН
小丑在游泳池做什么#short #angel #clown
00:13
Super Beauty team
Рет қаралды 42 МЛН
Самое неинтересное видео
00:32
Miracle
Рет қаралды 2,7 МЛН
Predict The Stock Market With Machine Learning And Python
35:55
Dataquest
Рет қаралды 687 М.
How to Code a AI Trading bot (so you can make $$$)
35:09
Nicholas Renotte
Рет қаралды 630 М.
Backtesting.py - Full course in python
1:09:34
Chad Thackray
Рет қаралды 186 М.
Trading with Python: Simple Scalping Strategy
13:47
CodeTrading
Рет қаралды 93 М.
Trading Indicator Analysis: CHOCH Indicator Python Implementation
14:10
The Most Realistic Automated Trading Analysis Using Python
10:46
CodeTrading
Рет қаралды 48 М.
Master This ONE Candlestick Pattern TODAY (Full Training)
55:11
Ross Cameron - Warrior Trading
Рет қаралды 754 М.
I Found The Hidden Trading Pattern That Controls All Markets
13:53
Cute
00:16
Oyuncak Avı
Рет қаралды 11 МЛН