2016年3月18日 星期五

Python 以歷史模擬法估計VAR值

歷史模擬法(History Simulation Method),是一種常見的估計風險值(value at risk)的方式。

優點為:計算相較其他方法簡單

缺點則為:需要龐大的歷史資料才會準確。

本篇以台灣股市之加權指數範例,回測期間為10年

滾動式窗(200天)之方式估算VAR值附圖及總穿透次數。

將會引用到Python 裏頭的 pandas numpy 模組


程式碼如下:
import pandas as pd
import numpy as np
'滾動天數'
rday=200

'信心水準95%'
Z=-1.645
cof=0.05

dat=2
'建立衰退因子及計數器'
dc=0.94
cont=0

'用pd這個函數讀資料excel檔'
Dat=pd.read_excel('fund_2.xlsx','sheet'+str(dat))
Dat.columns=[['date','close']]
Dat['return']=(Dat['close']/Dat['close'].shift(1)-1)
Dat['rstd']=pd.rolling_std(Dat['return'],window=int(rday))

a=[]
c=0
d=200
i=0
'滾動標準差'
while i if i < 200:

c=0
if i ==200:

c=Dat['rstd'][200]**2
if i >200:

c=((Dat['rstd'][i-1])**2)*dc+(1-dc)*(Dat['return'][i-2])**2

i+=1

a.append(c)
Dat['EWM']=a
Dat['EWMA']=abs(Dat['EWM'])**0.5*Z
Dat['minus']=Dat['return']-Dat['EWMA']

'計算穿透次數'
for j in range(len(Dat['minus'])):

if j>200 and Dat['minus'][j]<0: br="">
cont+=1

print('穿透次數為'+str(cont)+'次')
Dat[['return','EWMA',]][199:3102].plot(figsize=(12,8),lw=0.5,color=['b', 'r'],title='CVAR and VAR')


 

輸出結果如下:



結果來看,總資料比數 2902,穿透次數163次 大致接近95%信心水準。

沒有留言:

張貼留言