[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to calculate STDev?



PureBytes Links

Trading Reference Links

> I messed around with this StdDev of individual trade
> returns stuff about 2 years ago. I was unable to do it
> without using an array to store the individual trade
> results, so I was skeptical when you claimed success
> w/ no arrays. 
> 
> So I plugged your math into an old piece of system
> stat exporter code I wrote awhile back, and lo &
> behold, it does indeed match the results calculated in
> Excel. Now I wish I'd paid better attention in math class. 

Heh.  I sort of remembered there was a way to do it, so I juggled 
equations and tested in Excel until I figured it out.

I started with the basic root-mean-square definition of SD that 
subtracts the average from each value of X, so it does indeed 
require arrays.  (You have to store all the X values, calculate 
the average, and then subtract the average from the X values.)

  SD = sqrt( sum((Xn - Avg)^2) / (Length-1) )

(Or you might divide by Length; that's apparently a detail that 
statisticians argue about.)

Then we start the hocus-pocus:

  (Xn - Avg)^2 = Xn^2 - 2*Xn*Avg + Avg^2

If you sum up that value for all Xn's, you get

  sum(Xn^2) - 2*sum(Xn)*Avg + Length*Avg^2

So you just accumulate SumX and SumX2 as I did in my code.  Then, 
since Avg = SumX / Length, the equation turns into

  sumX2 - 2*SumX*(SumX/Length) 
                  + Length*(SumX/Length)*(SumX/Length)
= sumX2 - 2*SumX^2/Length + SumX^2/Length
= SumX2 - SumX^2/Length

...so SD = sqrt( (SumX2 - SumX^2/Length) / (Length-1) )

No arrays required.  Now who's gonna buy the prof a beer??  :-)
Gary