balipour

Moments (Mean,Variance,Skewness,Kurtosis) [pig]

Moments describe the shape features of a distribution. There are four essential Moments: Mean, Variance, Skewness, Kurtosis . The Moments of returns can provide a comprehensive view of the tendency, volatility , and risk of the market. It's important for traders to know these statistical properties of the instrument before trading them.

█ OVERVIEW

The mathmatical concept of Moments is relativly well undestood, but there are some common mistakes.There are already some existing scripts about moments on TradingView. I've gone through most of them, and it turns out there wasn't an accurate version of the moments function. Some have math errors in the formulas, and some use other formulas that are not commonly used in finance. There is also common confusion about Sample moments and Population moments. The correct moments used in finance are sample moments. But the TradingView built-in functions right now only have Population variance and standard deviation. Some scripts use Population variance and stdev functions in Sample skewness and kurtosis formulas. Some use the Population stdev to calculate the correct Population skewness and kurtosis , but then there is a degree-of-freedom issue that causes bias when the sample size is small. Therefore we decided to publish this so the community has at least one correct point of reference.

This script uses the formula that is most commonly used in professional statistical software packages such as Excel use. It uses sample variance and sample standard deviation and the adjusted Fisher-Pearson standardized Moment coefficient to find skewness and excess kurtosis . It provides an accurate adjusted unbiased estimation of the sample Moments.
We hope this script can provide people a better understanding of the Moments in the distribution and its formulas.

█ CONCEPTS

Log Returns:

We use log returns as the default input for source here. The reason why we use returns instead of price itself is that moments provide better information on the distribution of returns. Unlike traditional technical analysis , people in quantitative fianance rarely do their model calculations on price, they usually do them on returns. For example; the calculation of historical volatility . The price itself usually has a lower bound of 0, and it approximately follows a lognormal distribution. Therefore it always has a significant skewness. There are also trends and cycle components in price. It makes the time series non-stationary; therefore, models may provide unreliable information and lead to poor understanding and forecasting. For example, the autocorrelation of price is always positive because today's price is calculated based on yesterday's price. While returns are usually detrended and stationary, the moments of returns provide useful information about the shape of the distribution.

Here is a useful script made by everget that displays the return distribution.

Mean:

The first Raw Moment is the Mean. It indicates the central tendency of a distribution. People talk about the Mean a lot in trading when referring to moving averages and mean reversion. But when we talk about the mean in our previous scripts, we are talking about the mean of returns. So when indicators like the Hurst Exponent , Durbin Watson Stats or Variance Ratio Test show negative autocorrelation, which implies mean reversion, the mean we are refering to is the Mean of returns, not the Mean of price. When they target the mean to revert, they shouldn't be targeting the SMA of price. They should target the returns to the mean of returns. People usually use the mean of returns as an expected value of stock returns. They find the average for past performance and using that to get an idea of where the share price might go next.

The mean of returns vs The mean of price

When "Mean" is selected and "Show Returns "and "Show Bands" settings are ON, it displays the Mean with the Returns and Standard Deviation Band. The default setting shows a 95% confidence band around the mean. (Note: the confidence interval only works when returns follow a normal distribution, and it's better to use a longer look-back period when you display mean with returns and SD bands).

Variance:

The second Central Moment is the Variance. It indicates the spread of data around the Mean. People usually use Variance or the square root of Variance, which is the standard deviation to measure volatility . They sometimes define risk as the standard deviation of returns. While it may not be a measurement of risk (as we will explain later), it's a decent measurement of volatility . Since it's squared deviation from the Mean (second moment), the value is always positive, and power makes the smaller deviation smaller and the larger deviation larger. We should use sample variance and standard deviation, as I mentioned before. The difference is just divided by n or n -1. When "Variance" is selected, you can choose to display Variance or Standard Deviation by enabling "Show stdev instead").

Skewness:

The third Standardized Moment is Skewness. It measures the asymmetry of the distribution. The reason why it's called standardized moments is that it not only raised the deviation to the power of three in the nominator, it divides the standard deviation to the power of three to standardize the value. It's easier to compare the value of skewness with other distributions when it's standardized. The formula I just described is for population skewness. For sample skewness, it has to adjust the degrees of freedom to make it unbiased, which you can see in the code.

When skewness is 0, the distribution is perfectly symmetric. A normal distribution has a skewness of 0. (any symmetric distribution has a skewness of 0). But as you can see from the distribution chart, the returns are not perfectly symmetric. An easy way to know if the distribution is positively skewed (skewed right) or negatively skewed (skewed left) is by looking at its tails.
  • If extreme values happen more in the left tail, then it's left-skewed (longer left tail).
  • If the extreme value happens more in the right tail, then it's right-skewed (longer right tail).
A right-skewed distribution means there are more very large positive returns than negative returns in the sample. And left-skewed means there are more very large negative returns than positive returns in the sample.

Here is what skewed distributions look like. I used lognormal distribution and its reverse function with skewness of 1 (yellow lognormal) and -1 (green reverse lognormal) here (standard deviation 0.32). (Lognormal distribution are positively skewed)

Skewness Display, returns are more often negatively skewed because the market usually sell-off faster due to panic.

Kurtosis:

The fourth Standardize Moment is Kurtosis . It measures the "tailedness" in the distribution. As I mentioned in the skewness calculation, it also divides the fourth power of deviation by the fourth power of standard deviation to standardize the value. And it requires even more adjustments to degrees of freedom in order to make it unbiased for sample kurtosis .

The kurtosis value we display here is the excess kurtosis. The normal distribution has a kurtosis of 3. The excess kurtosis = kurtosis - 3.
  • When excess kurtosis is around 0, it has the same tail as normal distribution, and it's called Mesokurtic.
  • When excess kurtosis > 0, It has a fatter tail than normal distribution, and it's called Leptokurtic. There are more extremely large returns in the tails.
  • When excess kurtosis < 0. It has a thinner tail than the normal distribution, and it's called platykurtic. There are fewer extremely large returns in the tails.
Kurtosis doesn't have an upper bound, and the most platykurtic distribution is Bernoulli distribution with ex. kurtosis of -2. (even though the least platykurtic distribution kurtosis is -2, you can still get a value lower than -2 when you measure sample kurtosis .)
Kurtosis is sometimes referred to as volatility of volatility . It measures the tail risk or sometimes called kurtosis risk. Because a lot of statistical models assume a normal distribution, and when there's positive kurtosis , then they will underestimate the risk of fat tails. Market returns are usually leptokurtic due to volatility clustering (smaller returns cluster with smaller returns makes a higher peak, and extreme returns clusters make fatter tails). The kurtosis risk cannot be explained by variance or standard deviation because higher moments cannot be explained by lower moments. There can be two data sets with the same variance but different kurtosis . Therefore kurtosis explains more potential risk than the variance.

Normal Distribution vs Raised Consine Distribution (Ignore the value that goes back up in the tails)

There's a misconception about kurtosis . Many people think kurtosis measures the peakedness of a distribution. However, this is NOT the case. There are examples of distribution that has a lower peak than normal distribution but has higher kurtosis . In general, kurtosis measures mostly the tail of the distribution. It uses the fourth power in the calculation. Therefore a large value in the tail has much more effect on kurtosis than the small value in the middle.

Student T Distribution (degrees of freedom of 5) vs Laplace Distribution vs Normal distribution (Student T distribution has a lower peak than the normal distribution but has a high kurtosis due to its very fat tails)

Returns often have a significant positive kurtosis indicating fat tails.

Critical Values and Significance:

What value of skewness and kurtosis makes it significantly different from 0 and proves it's non-normally distributed? A way of finding this is to run a skewness and kurtosis Z test. The common way is to divide the skewness or kurtosis value by its standard error to get the z score and use an inverse cumulative normal distribution to find the p-value. For display convenience, we use the critical value instead of the p-value. Critical Value = Z Score * standard error . When the skew or kurtosis is above or below the critical value, we know it's significant. The standard error for skewness and kurtosis is based on the sample size and is calculated differently. (See the code for details).
The Z score for 95% confidence is 1.96. However, we have to use different Z scores according to the sample size here. As sample size increases, the standard error decreases which makes the Z score (Value/SE) larger. Therefore for N < 50, Z = 1.96, for N > 50, Z = 3.29. For N > 300, the test is not recommended. We can only use the rule of thumb abs(Skewness) > 2 and abs( kurtosis ) > 10 for reference.

When "Show Citicial Values" is on. Users can see the critical values of skewness and kurtosis . When the value of skewness and kurtosis is out of the crticial values range. We know the sample has a significant skewness or kurtosis that is different from normal distribution.

█ WAYS TO USE THIS INDICATOR

Using Moments Together:

The four moments of distributions tell us different properties in the shape of the distribution. When we understand what each moment tells us we can make some conclusions about the distribution. For example, a positive mean of return tells us about a positive expected value in the market and indicates a positive drift. A large variance tells us the volatility is high. A significant negative skewness tells us the distribution is asymmetric and most large returns are coming from negative returns than positive returns. And a significant positive kurtosis tells us the tails are fat and there are more occurrences of extremely large values (mostly coming from large negative returns as skewness implies).

Using Moments For Trend and Mean Reversion Trading:

  • Use the autocorrelation testing indicators to confirm trend or mean reversion. Then use log return, mean, and stdev bands to act accordingly.

  • Trend trading using mean and variance. When variance/stdev is high, take a trade based on the mean's direction.

  • Trend trading using skewness and kurtosis . When kurtosis is significantly positive, it indicates a large risk. But for trend trading strategies, they profit from extreme moves. Take a trade based on the direction of skewness if the kurtosis and skewness are both significant. Profit from extreme values in the direction of skewness.

  • Mean reversion strategies using kurtosis . When kurtosis is low, the risk of trading mean reversion is lower.

  • Mean reversion strategies using skewness. A positive skewness doesn't always mean bullish and a negative skewness doesn't always mean bearish . It only shows the shape of the distribution in the past. Skewness may sometimes even have a negative correlation with price. There are studies that show buying commodities with the most negative skewness and shorting commodities with the largest positive skewness can be profitable. And it could be applied not only in commodities . This is probably due to people's preference for longing positively-skewed securities. They tend to speculate a large profit from low probabilities. They will be overpricing the large positively-skewed securities and when the market underperforms, their expectation is that it will drop.

█ FEATURES

  • Select "Mean/Variance/Skewness/Kurtosis" in Moments Selection to display moments.
  • When Mean is selected and "Show Returns/Source" is ON, it shows the Source Input (Default Log Returns)
  • When Mean is selected and "Show Bands" is ON, it shows the standard deviation bands. The standard deviation multiplier can be adjusted in "Bands Multiplier".
  • When Variance is selected and "Show Stdev Instead" is ON, it shows standard deviation instead of variance.
  • When "Skewness" or "Kurtosis" is selected and Show Critical Value is ON. It shows the critical values for skewness or kurtosis . (Recommend Lookback < 300).
    "Lookback" is the sample size of the distribution
  • The User can choose "Original Source" in "Source Selection" and try other sources in source input. (Default Log Returns).
    Skewness (Source RSI )
  • When "Use Other Symbol" is on, the User can select other securities in "Symbol Input".
  • When "Show information Panel" is ON, it shows a panel with all four values of moments and provides the significance of skewness and kurtosis .
  • The User can the line thickness in "Line thickness" and turn off the dark background color in "Dark Background".
  • The User can adjust all the color settings in color inputs.

Our Website🅱🅰🐷: https://bapigindicator.com

Sign up on our website to get access to our indicators.

Join Our Discord for further discussions:

https://discord.gg/ink
Skript med en öppen källkod

In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in a publication is governed by House Rules. You can favorite it to use it on a chart.

Vill du använda det här skriptet i ett diagram?