StdDev (i) = SQRT (AMOUNT (j = i - N, i) / N)
AMOUNT (j = i - N, i) = SUM ((ApPRICE (j) - MA (ApPRICE (i), N, i)) ^ 2)
Where:
StdDev (i) — Standard Deviation of the current bar;
SQRT — square root;
AMOUNT(j = i - N, i) — sum of squares from j = i - N to i;
N — smoothing period;
ApPRICE (j) — the price of the j-th bar;
MA (ApPRICE (i), N, i) — any moving average of the current bar for N periods;
ApPRICE (i) — the price of the current bar.
- Code: Select all
function Init()
indicator:name("Standard Deviation Indicator");
indicator:description("Technical indicator named Standard Deviation (StdDev) measures the market volatility.");
indicator:requiredSource(core.Tick);
indicator:type(core.Oscillator);
indicator.parameters:addInteger("N", "N", "Period", 20);
indicator.parameters:addColor("clrStdDev", "Color of StdDev", "Color of StdDev", core.rgb(0, 255, 0));
end
local first;
local source = nil;
local MA;
local N;
function Prepare()
source = instance.source;
N=instance.parameters.N;
MA = core.indicators:create("MVA", source, N);
first = MA.DATA:first()+N;
local name = profile:id() .. "(" .. source:name() .. ", " .. N .. ")";
instance:name(name);
StdDev = instance:addStream("StdDev", core.Line, name .. ".StdDev", "StdDev", instance.parameters.clrStdDev, first);
end
function Update(period, mode)
MA:update(mode);
if (period>first+N) then
local dAmount=0.;
local dMovingAverage=MA.DATA[period];
local i;
for i=0,N,1 do
dAmount=dAmount+math.pow((source[period-i]-dMovingAverage),2);
end
StdDev[period]=math.sqrt(dAmount/N);
end
end