MACD Optimized via Historical Volatility For ThinkOrSwim

rockster195

New member
I was browsing through research articles and came upon this article pertaining to the MACD.
Volume 2018 | Article ID 9280590 | https://doi.org/10.1155/2018/9280590

To provide a summary, the professors explain that the MACD, while reliable and widely used by traders, and focuses solely on price points to measure momentum and trend, it is prone to false signals and has a lagging sense that could make entering a trade a little late or provide a false opportunity. To combat this, the professors believe that by adding Historical Volatility to the MACD, it will provide faster responses, as well as less fluctuations (therefore less false signals). The professors even provided their own backtesting on the proposed HVIX-MACD and has provided a better win rate from buying and selling the next day, selling after the 5th day, and selling after the 10th day. They also provided comparisons to the default MACD to support their claims.

On the lower end of the article, the professors provided the formula for the default MACD as well as providing their algorithm for their proposed MACD_HVIX.

10P71fs.png


(An expanded and detailed walkthrough is also provided via this link: "https://www.hindawi.com/journals/mpe/2018/9280590/alg1/").

Unfortunately, my flaw is that I find it difficult to decipher math language into codeable language; let alone thinkscript language, but I wasn't backing on something that has been proven well.

Below is the result from my attempt:
Code:
declare lower;
#Credit goes to the researchers at  https://doi.org/10.1155/2018/9280590

script EMA_HVIX {
input length = 12;
def R = Sum((Log(close[1]) / Log(close)), length); #Generates logarithmic returns from the previous close
def R_mean = R / (length - 1); #Returns the mean average from "length" - 1 days.
def sumVariance = Sum(Power((R - R_mean), 2), length-2); #Sums the variance in the past "length" - 1 days.
def deviation = Sqrt(sumVariance / length - 2); #Calculating the standard deviation in the past "length" - 2 days.
def sumonedeviation = Sum(deviation, length - 1); #
def sumtwodeviation = Sum(deviation, length - 2); #Sums up both deviation in alternating days.
def alphahvix = 1 - (sumtwodeviation/sumonedeviation); #Returns the ALPHA_VIX

def ema_hvix = (1 - alphahvix[1])*ema_hvix[1] + Alphahvix[1]*close;
plot data = ema_hvix; #plots the EMA with Historical Volatility;
}



input fastLength = 12; # According to the paper, this is classified as "m"
input slowLength = 26; # Default settings for MACD; "n"
input MACDLength = 9;  # "p"


def alpha = 2 / fastlength + 1;

plot dif = EMA_HVIX(fastLength) - EMA_HVIX(SlowLength);
def dea_hvix = (Sum(dif, macdlength) / macdlength); #Sum(dif, macdlength) / macdlength;  #Starting Gun
def de = dea_hvix; #(1 - Power(Alpha, fastlength)) * de[1] + Power(Alpha, fastLength) * dif[1];
plot dea = de ;
plot osc = dif - dea; #Osc is Histogram
plot ZeroLine = 0;

dif.SetDefaultColor(Color.CYAN);
dea.SetDefaultColor(Color.RED);
osc.SetDefaultColor(GetColor(5));
osc.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
osc.SetLineWeight(3);
osc.DefineColor("Positive and Up", Color.GREEN);
osc.DefineColor("Positive and Down", Color.DARK_GREEN);
osc.DefineColor("Negative and Down", Color.RED);
osc.DefineColor("Negative and Up", Color.DARK_RED);
osc.AssignValueColor(if osc >= 0 then if osc > osc[1] then osc.Color("Positive and Up") else osc.Color("Positive and Down") else if osc < osc[1] then osc.Color("Negative and Down") else osc.Color("Negative and Up"));
ZeroLine.SetDefaultColor(GetColor(0));

Shareable code link: https://tos.mx/8z6yicn

To see the differences in action, I provided a couple of screenshots from the MACD, and MACD_HVIX to let you be the judge.


iQI5xnT.png


On the first image is the $QQQ and I've highlighted the major differences. On the left side, we see the MACD telling the user that the Average (cyan color) crossed below the zero line and the stock is in a potential downtrend. BUT, the MACD_HVIX tells a different story, telling the user that not only did it drop, it never crossed below the zero line to dictate a downtrend, and if you look closely, it hasn't provided a signal crossover (buy signal) until the indicator showed it's breakout above.

On the right side of the first image, we see the MACD having difficulty keeping the downward trend and providing false reverse signals, unlike MACD_HVIX that does it's best into holding on to the trend while providing minimal false positives.

I'm also including an extra screenshot for more comparisons.

$TSLA


J361zbO.png



An issue

3WCeTTn.png


For my first attempt of deciphering math language, I feel like I did a pretty good job, unfortunately, I left out a piece of code due to it being difficult for me to understand, maybe some of you guys can look into a solution for this, and if you know how to decipher math language to thinkscript, I would love it greatly for you to review my code and make any adjustments to make this code reliable for the community as it is also lagging by two bars when it comes to reversals. Thank you for looking at my code.

NOTE: Due to the complexity of the indicator, there may be times where the indicator doesn't show. I find it that if you run MACD, the indicator tends to show up.
 
Thank you for sharing.
It works very well for me and helps me to stay in the trades a little longer than I would if using other "Sell" Macd signals or Stochastic signals.
Do you think is possible to add buy and sell signal arrows?
 
Thank you for sharing.
It works very well for me and helps me to stay in the trades a little longer than I would if using other "Sell" Macd signals or Stochastic signals.
Do you think is possible to add buy and sell signal arrows?
ADD This to the bottom of your script

plot UpSignal = if Dif crosses above Dea then Dea else Double.NaN;
UpSignal.SetPaintingStrategy(PaintingStrategy.Arrow_Up);
UpSignal.SetLineWeight(1);
UpSignal.SetDefaultColor(Color.GREEN);


plot DownSignal = if Dif crosses below Dea then Dea else Double.NaN;
DownSignal.SetPaintingStrategy(PaintingStrategy.Arrow_DOWN);
DownSignal.SetLineWeight(1);
DownSignal.SetDefaultColor(Color.RED);
 
I was browsing through research articles and came upon this article pertaining to the MACD.
Volume 2018 | Article ID 9280590 | https://doi.org/10.1155/2018/9280590

To provide a summary, the professors explain that the MACD, while reliable and widely used by traders, and focuses solely on price points to measure momentum and trend, it is prone to false signals and has a lagging sense that could make entering a trade a little late or provide a false opportunity. To combat this, the professors believe that by adding Historical Volatility to the MACD, it will provide faster responses, as well as less fluctuations (therefore less false signals). The professors even provided their own backtesting on the proposed HVIX-MACD and has provided a better win rate from buying and selling the next day, selling after the 5th day, and selling after the 10th day. They also provided comparisons to the default MACD to support their claims.

On the lower end of the article, the professors provided the formula for the default MACD as well as providing their algorithm for their proposed MACD_HVIX.

10P71fs.png


(An expanded and detailed walkthrough is also provided via this link: "https://www.hindawi.com/journals/mpe/2018/9280590/alg1/").

Unfortunately, my flaw is that I find it difficult to decipher math language into codeable language; let alone thinkscript language, but I wasn't backing on something that has been proven well.

Below is the result from my attempt:
Code:
declare lower;
#Credit goes to the researchers at  https://doi.org/10.1155/2018/9280590

script EMA_HVIX {
input length = 12;
def R = Sum((Log(close[1]) / Log(close)), length); #Generates logarithmic returns from the previous close
def R_mean = R / (length - 1); #Returns the mean average from "length" - 1 days.
def sumVariance = Sum(Power((R - R_mean), 2), length-2); #Sums the variance in the past "length" - 1 days.
def deviation = Sqrt(sumVariance / length - 2); #Calculating the standard deviation in the past "length" - 2 days.
def sumonedeviation = Sum(deviation, length - 1); #
def sumtwodeviation = Sum(deviation, length - 2); #Sums up both deviation in alternating days.
def alphahvix = 1 - (sumtwodeviation/sumonedeviation); #Returns the ALPHA_VIX

def ema_hvix = (1 - alphahvix[1])*ema_hvix[1] + Alphahvix[1]*close;
plot data = ema_hvix; #plots the EMA with Historical Volatility;
}



input fastLength = 12; # According to the paper, this is classified as "m"
input slowLength = 26; # Default settings for MACD; "n"
input MACDLength = 9;  # "p"


def alpha = 2 / fastlength + 1;

plot dif = EMA_HVIX(fastLength) - EMA_HVIX(SlowLength);
def dea_hvix = (Sum(dif, macdlength) / macdlength); #Sum(dif, macdlength) / macdlength;  #Starting Gun
def de = dea_hvix; #(1 - Power(Alpha, fastlength)) * de[1] + Power(Alpha, fastLength) * dif[1];
plot dea = de ;
plot osc = dif - dea; #Osc is Histogram
plot ZeroLine = 0;

dif.SetDefaultColor(Color.CYAN);
dea.SetDefaultColor(Color.RED);
osc.SetDefaultColor(GetColor(5));
osc.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
osc.SetLineWeight(3);
osc.DefineColor("Positive and Up", Color.GREEN);
osc.DefineColor("Positive and Down", Color.DARK_GREEN);
osc.DefineColor("Negative and Down", Color.RED);
osc.DefineColor("Negative and Up", Color.DARK_RED);
osc.AssignValueColor(if osc >= 0 then if osc > osc[1] then osc.Color("Positive and Up") else osc.Color("Positive and Down") else if osc < osc[1] then osc.Color("Negative and Down") else osc.Color("Negative and Up"));
ZeroLine.SetDefaultColor(GetColor(0));

Shareable code link: https://tos.mx/8z6yicn

To see the differences in action, I provided a couple of screenshots from the MACD, and MACD_HVIX to let you be the judge.


iQI5xnT.png


On the first image is the $QQQ and I've highlighted the major differences. On the left side, we see the MACD telling the user that the Average (cyan color) crossed below the zero line and the stock is in a potential downtrend. BUT, the MACD_HVIX tells a different story, telling the user that not only did it drop, it never crossed below the zero line to dictate a downtrend, and if you look closely, it hasn't provided a signal crossover (buy signal) until the indicator showed it's breakout above.

On the right side of the first image, we see the MACD having difficulty keeping the downward trend and providing false reverse signals, unlike MACD_HVIX that does it's best into holding on to the trend while providing minimal false positives.

I'm also including an extra screenshot for more comparisons.

$TSLA


J361zbO.png



An issue

3WCeTTn.png


For my first attempt of deciphering math language, I feel like I did a pretty good job, unfortunately, I left out a piece of code due to it being difficult for me to understand, maybe some of you guys can look into a solution for this, and if you know how to decipher math language to thinkscript, I would love it greatly for you to review my code and make any adjustments to make this code reliable for the community as it is also lagging by two bars when it comes to reversals. Thank you for looking at my code.

NOTE: Due to the complexity of the indicator, there may be times where the indicator doesn't show. I find it that if you run MACD, the indicator tends to show up.
Hi, Great job! I like the smoothness and less false signals. Were you able to figure out the small issue regarding the 2 bar lag? Thank you
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
279 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top