Question

I'm using Stata to estimate Value-at-risk (VaR) with the historical simulation method. Basically, I will create a rolling window with 100 observations, to estimate VaR for the next 250 days (repeat 250 times). Hence, as I've known, the rolling window with time series command in Stata would be useful in this case. Here is the process:

Input: 350 values 1. Ascending sort the very first 100 values (by magnitude). 2. Then I need to take the 5th smallest for each window. 3. Repeat 250 times. Output: a list of the 5th values (250 in total).

Sound simple, but I cannot do it the right way. This was my attempt below:

program his,rclass
         sort lnreturn
         return scalar actual=lnreturn in 5
         end
tsset stt
         time variable:  stt, 1 to 350
                delta:  1 unit

rolling actual=r(actual), window(100) saving(C:\result100.dta, replace) : his
(running his on estimation sample)

And the result is:

   Start  end      actual   
    1     100    -.047856   
    2     101    -.047856   
    3     102    -.047856   
    4     103    -.047856
   ....  .....    ......

   251    350    -.047856

What I want is 250 different 5th values in panel "actual", not the same like that.

Was it helpful?

Solution

If I understand this correctly, you want the 5th percentile of values in a window of 100. That should yield to summarize, detail or centile. I see no need to write a program.

Your bug is that your program his calculates the same thing each time it is called. There is no communication about windows other than what is explicit in your code. It is like saying

move here: now add 2 + 2

move there: now add 2 + 2

move to New York: now add 2 + 2

The result is invariant to your supposed position.

Note that I doubt that

return scalar actual=lnreturn in 5

really is your code. lnreturn[5] should work.

UPDATE You don't even need rolling here. Looping over data is easy enough. The data in this example are clearly fake.

clear

* sandpit 
set obs 500
set seed 2803
gen y = ceil(exp(rnormal(3,2)))
l y in 1/5

* initialise  
gen p5 = . 

* windows of length 100: 1..100, 101..200, ...  
quietly forval j = 1/401 { 
local J = `j' + 99 
su y in `j'/`J', detail 
replace p5 = r(p5) in `j' 
} 

* check first calculation 
su y in 1/100, detail 
l in 1/5 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top