Adaptive Trend Lines [MAMA and FAMA]Updated my previous algo on the Adaptive Trend lines, however I have added new functionalities and sorted out the settings.
You can now switch between normalized and non-normalized settings, the colors have also been updated and look much better.
The MAMA and FAMA
These indicators was originally developed by John F. Ehlers (Stocks & Commodities V. 19:10: MESA Adaptive Moving Averages). Everget wrote the initial functions for these in pine script. I have simply normalized the indicators and chosen to use the Laplace transformation instead of the hilbert transformation
How the Indicator Works:
The indicator employs a series of complex calculations, but we'll break it down into key steps to understand its functionality:
LaplaceTransform: Calculates the Laplace distribution for the given src input. The Laplace distribution is a continuous probability distribution, also known as the double exponential distribution. I use this because of the assymetrical return profile
MESA Period: The indicator calculates a MESA period, which represents the dominant cycle length in the price data. This period is continuously adjusted to adapt to market changes.
InPhase and Quadrature Components: The InPhase and Quadrature components are derived from the Hilbert Transform output. These components represent different aspects of the price's cyclical behavior.
Homodyne Discriminator: The Homodyne Discriminator is a phase-sensitive technique used to determine the phase and amplitude of a signal. It helps in detecting trend changes.
Alpha Calculation: Alpha represents the adaptive factor that adjusts the sensitivity of the indicator. It is based on the MESA period and the phase of the InPhase component. Alpha helps in dynamically adjusting the indicator's responsiveness to changes in market conditions.
MAMA and FAMA Calculation: The MAMA and FAMA values are calculated using the adaptive factor (alpha) and the input price data. These values are essentially adaptive moving averages that aim to capture the current trend more effectively than traditional moving averages.
But Omar, why would anyone want to use this?
The MAMA and FAMA lines offer benefits:
The indicator offers a distinct advantage over conventional moving averages due to its adaptive nature, which allows it to adjust to changing market conditions. This adaptability ensures that investors can stay on the right side of the trend, as the indicator becomes more responsive during trending periods and less sensitive in choppy or sideways markets.
One of the key strengths of this indicator lies in its ability to identify trends effectively by combining the MESA and MAMA techniques. By doing so, it efficiently filters out market noise, making it highly valuable for trend-following strategies. Investors can rely on this feature to gain clearer insights into the prevailing trends and make well-informed trading decisions.
This indicator is primarily suppoest to be used on the big timeframes to see which trend is prevailing, however I am not against someone using it on a timeframe below the 1D, just be careful if you are using this for modern portfolio theory, this is not suppoest to be a mid-term component, but rather a long term component that works well with proper use of detrended fluctuation analysis.
Dont hesitate to ask me if you have any questions
Again, I want to give credit to Everget and ChartPrime!
Code explanation as required by House Rules:
fastLimit = input.float(title='Fast Limit', step=0.01, defval=0.01, group = "Indicator Settings")
slowLimit = input.float(title='Slow Limit', step=0.01, defval=0.08, group = "Indicator Settings")
src = input(title='Source', defval=close, group = "Indicator Settings")
input.float: Used to create input fields for the user to set the fastLimit and slowLimit values.
input: General function to get user inputs, like the data source (close price) used for calculations.
norm_period = input.int(3, 'Normalization Period', 1, group = "Normalized Settings")
norm = input.bool(defval = true, title = "Use normalization", group = "Normalized Settings")
input.int: Creates an input field for the normalization period.
input.bool: Allows the user to toggle normalization on or off.
Color settings in the code:
col_up = input.color(#22ab94, group = "Color Settings")
col_dn = input.color(#f7525f, group = "Color Settings")
Constants and functions
var float PI = math.pi
laplace(src) =>
(0.5) * math.exp(-math.abs(src))
_computeComponent(src, mesaPeriodMult) =>
out = laplace(src) * mesaPeriodMult
out
_smoothComponent(src) =>
out = 0.2 * src + 0.8 * nz(src )
out
math.pi: Represents the mathematical constant π (pi).
laplace: A function that applies the Laplace transform to the source data.
_computeComponent: Computes a component of the data using the Laplace transform.
_smoothComponent: Smooths data by averaging the current value with the previous one (nz function is used to handle null values).
Alpha function:
_computeAlpha(src, fastLimit, slowLimit) =>
mesaPeriod = 0.0
mesaPeriodMult = 0.075 * nz(mesaPeriod ) + 0.54
...
alpha = math.max(fastLimit / deltaPhase, slowLimit)
out = alpha
out
_computeAlpha: Calculates the adaptive alpha value based on the fastLimit and slowLimit. This value is crucial for determining the MAMA and FAMA lines.
Calculating MAMA and FAMA:
mama = 0.0
mama := alpha * src + (1 - alpha) * nz(mama )
fama = 0.0
fama := alpha2 * mama + (1 - alpha2) * nz(fama )
Normalization:
lowest = ta.lowest(mama_fama_diff, norm_period)
highest = ta.highest(mama_fama_diff, norm_period)
normalized = (mama_fama_diff - lowest) / (highest - lowest) - 0.5
ta.lowest and ta.highest: Find the lowest and highest values of mama_fama_diff over the normalization period.
The oscillator is normalized to a range, making it easier to compare over different periods.
And finally, the plotting:
plot(norm == true ? normalized : na, style=plot.style_columns, color=col_wn, title = "mama_fama_diff Oscillator Normalized")
plot(norm == false ? mama_fama_diff : na, style=plot.style_columns, color=col_wnS, title = "mama_fama_diff Oscillator")
Example of Normalized settings:
Example for setup:
Try to make sure the lower timeframe follows the higher timeframe if you take a trade based on this indicator!
Fama
IchiMAMA (Experimental)Goichi Hosoda's "Ichimoku Kinkō Hyō" is a widely used Trend Following indicator and can be defined as a "system" rather than an indicator.
Published in the late 1960's, consisting of 5 lines.
TenkanSen (Conversion Line) = of the last 9 bars
KijunSen (Base Line) = of the last 26 bars
SenkouSpanA (Leading Span A) = Average of Tenkan&KijunSen shifted -> 26 bars
SenkouSpanB (Leading Span B) = of the last 52 bars
ChikouSpan (Lagging Span) = Price shifted <- 26 bars
On the other hand, Mesa Adaptive Moving Average developed by John Ehlers around early 2000's shows similarities with Hosoda's Tenkan and KijunSen using a different calculation method. For futher info: www.mesasoftware.com
I find MAMA superior to TenkanSen and KijunSen in terms of crossing signals.
Ichimoku:
Thus, decided to replace TenkanSen and KijunSen of regular Ichimoku with MAMA&FAMA of Ehlers and calculated SenkouSpanA accordingly. SenkouSpanB and ChikouSpan stays the same as per Ichimoku's logic. (Periods are 30 by default for cryptocurrencies. If stocks then 26)
IchiMAMA:
This is purely experimental and educational. Hope you'll like it :)
I'd like to thank @everget for MAMA&FAMA
and @KivancOzbilgic for Ichimoku Kinkō Hyō and Volume Based Colored Bars
Fama-French 3 Factor ModelFama-French 3 Factor Model
Extension of the Capital Asset Pricing Model (CAPM)
CAPM
Ra = Rfr +
where,
Ra = Return of the Asset
Rfr = Risk-Free Rate
βa = Beta Coefficient of the Asset
Rm - Rfr = Market Risk Premium
Fama-French 3 Factor
r = rf + β1*(rm - rf) + β2(smh) +β3(hml)
r = Expected rate of return
rf = Risk-free rate
ß = Factor’s coefficient (sensitivity)
(rm – rf) = Market risk premium
SMB (Small Minus Big) = Historic excess returns of small-cap companies over large-cap companies
HML (High Minus Low) = Historic excess returns of value stocks (high book-to-price ratio) over growth stocks (low book-to-price ratio)
Small is set to $EWSC
Invesco S&P SmallCap 600® Equal Weight ETF
Big is set to $EQLW
Invesco S&P 100 Equal Weight ETF
High is set to $IUSV
iShares Core S&P US Value ETF
Low is set to $IUSG
iShares Core S&P US Growth ETF
returns selections
'returns'
'logarithmic returns' (use for realized (historical) returns)
'geometric returns' (compounded returns)
risk-free rate selections:
$DTB3
$DGS2
$DGS5
$DGS10
$DGS30
tf = primary time-frame
rtf = reference time-frame
Ehlers Mother Of Adaptive Moving Averages [CC]The Mother Of Adaptive Moving Averages was created by John Ehlers (Rocket Science For Traders pgs 182-183) and this is definitely my favorite Ehlers moving average script. This works as a trend indicator and a typical moving average. When the mama is above the fama then the stock is in an uptrend and vice versa. Of course it is also good when the price is above the fama and mama lines. Buy when the indicator line is green and sell when it is red.
Let me know if there are other indicator scripts you would like to see me publish or if you want something custom done!
MAMA FAMA KAMA.. chameleon 🎵
Uses Kaufmann's Efficiency Ratio to generate adaptive inputs for Ehler's MAMA/FAMA. Alphas from the Hilbert transform are then used in place for the KAMA calculation.
Original MAMA/FAMA by everget : link
--------------------------------------
If you find it useful please consider a tip/donation :
BTC - 3BMEXEDyWJ58eXUEALYPadbn1wwWKmf6sA
MESA Adaptive Moving AverageIntro
One of Ehlers most well-known indicators! I've seen many variations of this on TradingView, however, none seem to be true to the original released by Ehlers himself.
I've taken it upon myself to simply translate the MAMA into Pinescript, instead of re-writing like some others have done.
You can use it as a very effective & adaptive moving average with other signals or
as a standalone signal.
In the case that you're going to use it for signals and not simple technical trading (non-quantitative),
I've also added a threshold parameter to filter out weak signals.
My MAMA indicator is different from others in very simple ways - I don't use the nz() command, which sets all "Not a Number" values to 0. In others' scripts, you immediately load the indicator with several 0 values,
causing a slight lag in future calculations since this code is recursive (refers to previous values it generated).
In my version, I simply wait until the script has access to all the bar data it needs, instead of instantly performing calculations and
setting erroneous values to 0. In this case, we start with the correct values (or closer to correct).
If you want to compare this indicator the current most popular MAMA by LazyBear, you'll notice it often gives buy and sell crosses one bar earlier than theirs.
Setting Parameters
Source - the data series to perform calculations on. (Initially, Ehlers himself favored hl/2, but conceded that there isn't empirical benefit over close.)
Fast Limit - controls how quickly the MAMA will "ratchet up" fast price action. (Higher values are faster)
Slow Limit - controls how closely the FAMA will follow the MAMA. (Again, higher is faster. You typically want the FAMA to be slower though.)
Crossover Threshold - simple error thresholding to limit the number of weak trade signals. (Lower means lower tolerance)
Show Crosses? - show/hide the arrows at moving average crosses
Ehlers MESA Adaptive Moving Averages (MAMA & FAMA)Ehlers MESA Adaptive Moving Averages (MAMA & FAMA) script.
These indicators was originally developed by John F. Ehlers (Stocks & Commodities V. 19:10: MESA Adaptive Moving Averages).
Fractal Dimension Adaptive Moving Average (D-AMA)etfhq.com
Overall the D-AMA produced results that were near identical to that of the FRAMA but the D-AMA is a slightly faster average.
It is very difficult to pick between the FRAMA and the D-AMA but becuase the FRAMA offers a slightly longer trade duration it the best Moving Average we have tested so far.
Fractal Adaptive Moving Average (real one)Ignore the other one (it contains some errors).
On this FRAMA you can play with length, SC and FC.
Just read on below links to understand more about this super useful moving average:
etfhq.com
etfhq.com
www.quantshare.com