Algorithms for calculating variance play a major role in computational statistics. A key difficulty in the design of good algorithms for this problem is that formulas for the variance may involve sums of squares, which can lead to numerical instability as well as to arithmetic overflow when dealing with large values.
It is often useful to be able to compute the variance in a single pass, inspecting each value only once for example, when the data are being collected without enough storage to keep all the values, or when costs of memory access dominate those of computation. For such an online algorithm, a recurrence relation is required between quantities from which the required statistics can be calculated in a numerically stable fashion.
(source:wikipedia).
Welford’s method is a usable single-pass method for computing the variance. It can be derived by looking at the differences between the sums of squared differences for N and N-1 samples. It’s really surprising how simple the difference turns out to be.
In my opinion, the Welford’s method (in green in the picture) to compute variance is less noisy and stable than the standard deviation formula (in blue). I let you do your homework with this code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//PRC_Variance (Welford's method) | indicator //04.07.2019 //Nicolas @ www.prorealcode.com //Sharing ProRealTime knowledge // --- settings inpVarPeriod = 14 // Variance period // --- end of settings value=close mperiod=inpVarPeriod m=0 s=0 oldm=0 for k=0 to mperiod-1 do oldm = m m = m+(value[k]-m)/(1.0+k) s = s+(value[k]-m)*(value[k]-oldm) next return(s/(mperiod-1)) |
Share this
No information on this site is investment advice or a solicitation to buy or sell any financial instrument. Past performance is not indicative of future results. Trading may expose you to risk of loss greater than your deposits and is only suitable for experienced investors who have sufficient financial means to bear such risk.
ProRealTime ITF files and other attachments :PRC is also on YouTube, subscribe to our channel for exclusive content and tutorials