Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at

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

Re: st: RE: Rolling Means and Standard Deviations

From   Richard Herron <>
Subject   Re: st: RE: Rolling Means and Standard Deviations
Date   Thu, 1 Dec 2011 20:57:15 -0500

@David -- Did you try my code? Also check out -mvsumm-, as Nick suggests.

If you reshape to a proper panel you will find these options much
faster than -rolling- (I wrestled this when I switched from R to Stata
about two months ago). If you can do the operation with summations and
differences, then rolling operations can be done _very quickly_.
(Also, I changed my variance calc to divide by n-1 instead of n).

If you prefer to stick with -rolling- my code below works.

* my program
capture program drop rolling_mean_sd
program rolling_mean_sd
    version 11.2
    syntax varlist(numeric min=1 max=1), window(real)

    * get dependent and indpendent vars from varlist
    tempvar x x2 xs x2s
    tokenize "`varlist'"
    generate `x' = `1'
    local w = `window'

    * generate sums
    generate `x2' = `x' * `x'
    generate `xs' = sum(`x')
    generate `x2s' = sum(`x2')

    * generate mean, variance, and sd
    generate meanx = s`w'.`xs' / `w'
    generate sdx = sqrt((s`w'.`x2s' - s`w'.`xs' * s`w'.`xs' / `w') ///
        / (`w' - 1))


* get data
tsset t
generate ibmadj = ibm - irx
generate spxadj = spx - irx

* call my program
rolling_mean_sd ibmadj, window(200)
list in -10/l

* call rolling
rolling sd = r(sd) mean = r(mean), window(200) nodots clear ///
    : summarize ibmadj
list in -10/l

On Wed, Nov 30, 2011 at 07:50, Nick Cox <> wrote:
> You do not define "not working".
> But why not check out -mvsumm- (SSC) instead as recommended very recently by Kit Baum?
> Nick
> David Ashcraft
> I am trying to find the rolling mean and standard deviation. I know that I can use -rolling- command but somehow lost my track. Please see the example below:
> use
> tsset t
> generate ibmadj = ibm - irx
> generate spxadj = spx - irx
> now I want to generate means and standard deviation of both ibmadj and spxadj with window of 200 days. I looked in the Stata manual, it mentioned about the command. I believe, I should do the following:
> rolling  _sd, window(200) saving(means, replace) keep(date): gen sd=r(sd)
> rolling  _mean, window(200) saving(means, append) keep(date): gen mean=r(mean)
> But this is not working. Any help will be greatly appreciated.
> *
> *   For searches and help try:
> *
> *
> *

*   For searches and help try:

© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index