Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: RE: Trailing 60-day standard deviation


From   "Nick Winter" <[email protected]>
To   <[email protected]>
Subject   st: RE: Trailing 60-day standard deviation
Date   Tue, 16 Jul 2002 14:39:30 -0400

> -----Original Message-----
> From: Susan Lewis [mailto:[email protected]] 
> Sent: Tuesday, July 16, 2002 1:19 PM
> To: [email protected]
> Subject: st: Trailing 60-day standard deviation
> 
> 
> Seems I must be missing something obvious, but I can't find a 
> compact way to calculate a trailing
> 60-day standard deviation. Data are in long format as follows:
> 
> 	Entity 1	Day 1		Value
> 	Entity 1	Day 2		Value
> 	Entity 1	Day 3		Value
>          .
> 	   .
> 	   .
> 	Entity 1	Day 365	Value
> 	Entity 2	Day 1		Value
> 	Entity 2	Day 2		Value
> 	   .
> 	   .
> 	   .
> 	Entity 100	Day 365	Value
> 
> Goal is to end up with:
> 
> 	Entity 1	Day 1		Value		(missing)
> 	Entity 1	Day 2		Value		(missing)
>          .
> 	   .
> 	   .
> 	Entity 1	Day 364	Value		SD ENTITY 1 DAYS 304-364
> 	Entity 1	Day 365	Value		SD ENTITY 1 DAYS 305-365
> 	   .
> 	   .
> 	   .
> 	Entity 100	Day 365	Value		SD ENTITY 100 
> DAYS 305-365
> 
> Any advice would be greatly appreciated.

Not so obvious - I don't think there's an official way to do it.  But I
believe the following gives you what you want:

	gen sum1=0
	gen sum2=0
	gen entity2=entity^2
	sort year day
	forval i=0/59 {
		qui by year: replace sum1=sum1+entity[_n-`i']
		qui by year: replace sum2=sum2+entity2[_n-`i']
	}
	gen sd_lag60 = sqrt( (1/59) * (sum2 - (sum1^2)/60) )

Basically, this creates x and x^2, then creates sum1 and sum2 in the
-forvalues- loop, which are the sum of (x) and the sum of (x^2) for the
sixty lagged observations.  Then the standard deviation is easy to
calculate.

Nick Winter
*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index