Standard Deviation from Moving Average

Is there a way to calculate the standard deviation price is from a stated moving average like the 50DMA?
Is it possible to create a script for that?
Thank you very much for your help.

Sure. Here’s a 20 period Standard Deviation of price from a 50 MA. Change the first 2 lines to adjust the lookback variables:

//Set lookbacks;
#$MA = 50;
#$SD = 20;
//Calc MA;
MA1 = MA(BARS=$MA, CALC=Close);
//Calc % diff;
DIFF = ((CLOSE() - MA1) / MA1)*100;
//Std Dev of Diff;
STD(DIFF, BARS=$SD)

Here’s the value in a watchlist column and a Show View histogram:

Capture

Thank you, Darren!
This is great.

Hi,

I want add to this forum thread and want ask the following question:

Is it possible to use as the time period to calculate the STD a start date e.g. 01/01/1950 and not the fixed time period of e.g. 20 bars?

Lets say I have a csv file with monthly data and the calculation for the STD should always start at 01/01/1950 and should include all monthly data from 01/01/1950 to the last date in the monthly csv file. This means the length for the calculation of the STD becomes one month/one time unit more every month. So the length of the calculation of the STD varies.

Thanks,
Thomas

Hi,

Yes, this should be possible using the following adjusted script:

//Set lookbacks;
#$MA = 50;
$SD = BARCOUNT(Month(PERIODAMOUNT=1));
//Calc MA;
MA1 = MA(BARS=$MA, CALC=Close);
//Calc % diff;
DIFF = ((CLOSE() - MA1) / MA1)*100;
//Std Dev of Diff;
STD(DIFF, BARS=$SD)

This script adjusts the $SD line to use a Monthly Bar Count total. As the monthly bar count changes, so will the STD Bar lookback period.