Dear members,
I am working with panel data and would like to calculate a 5-day rolling window realized volatility for each firm. Here is a simulated data for illustration:
I tried using different codes with no luck. I keep getting errors for codes such as:
and also
I even tried a loop with no luck:
then i revered to the asrol code with no luck:
I then ran a simple code that worked:
but the does not produce the same realized volatility as if you would do it on excel:
I would appreciate any guidance
I am working with panel data and would like to calculate a 5-day rolling window realized volatility for each firm. Here is a simulated data for illustration:
Code:
* Example generated by -dataex-. To install: ssc install dataex clear input float Date str45 firm int firm_id float Logreturn 18536 "AAK" 1 0.0059992443 18539 "AAK" 1 -.002986188 18540 "AAK" 1 0.028037382 18541 "AAK" 1 .0.0090909088 18542 "AAK" 1 -0.029909907 18543 "AAK" 1 0.021545317 18546 "AAK" 1 0.002909088 18547 "AAK" 1 -0.0090645393 18548 "AAK" 1 0.021588003 18536 "BBA" 2 -0.015042983 18539 "BBA" 2 0.0061818208 18540 "BBA" 2 -0.018070113 18541 "BBA" 2 0.0095238099 18542 "BBA" 2 -0.006256904 18543 "BBA" 2 -0.018518519 18546 "BBA" 2 0.0094339624 18547 "BBA" 2 -0.02168224 18548 "BBA" 2 0.0030569325 end
Code:
gen squared_return = Logreturn^2 bysort firm_id (Date): egen realized_volatility = mean(squared_return), window(5)
Code:
by firm_id: gen vola5 = sqrt(rolling(sum) squared_return, window(5))
Code:
levelsof firm_id, local(firms) foreach firm of local firms { by firm_id: egen mean_squared_return = mean(squared_return) by firm_id: egen volat5_firm = sqrt(5 * mean_squared_return) replace volat5 = volat5_firm if firm_id == `firm' drop mean_squared_return volat5_firm }
Code:
gen volat5 =. levelsof firm_id, local(firms) foreach firm of local firms { by firm_id: asrol volat5_firm = squared_return, window(5) start(Date) keep(firm_id) replace volat5 = volat5_firm if firm_id == `firm' drop volat5_firm }
Code:
bysort firm_id (Date): gen rvol5=sqrt(5*sum( Logreturn^2))
Date | firm | firm_id | L. Return | Realized Vol |
30-Sep | AAK | 1 | 0.005999244 | |
1-Oct | AAK | 1 | -0.002981734 | |
4-Oct | AAK | 1 | 0.028037382 | 0.02764528 |
5-Oct | AAK | 1 | 0.009090909 | 0.027082311 |
6-Oct | AAK | 1 | -0.029909907 | 0.051175779 |
7-Oct | AAK | 1 | 0.021545317 | 0.046496322 |
8-Oct | AAK | 1 | 0.002909088 | 0.045122254 |
11-Oct | AAK | 1 | -0.009064539 | 0.026717411 |
12-Oct | AAK | 1 | 0.021588003 | 0.026756756 |
30-Sep | BBA | 2 | -0.015042983 | |
1-Oct | BBA | 2 | 0.006181821 | |
4-Oct | BBA | 2 | -0.018070113 | 0.018688785 |
5-Oct | BBA | 2 | 0.00952381 | 0.021297494 |
6-Oct | BBA | 2 | -0.006256904 | 0.019578963 |
7-Oct | BBA | 2 | -0.018518519 | 0.019880898 |
8-Oct | BBA | 2 | 0.009433962 | 0.019814908 |
11-Oct | BBA | 2 | -0.02168224 | 0.024218233 |
12-Oct | BBA | 2 | 0.003056933 | 0.023244435 |
Comment