华东理工大学《Python与金融计算》

实验八:中国股市尾部风险测度的估计与检验

蒋志强、储丽娅

In [3]:
import numpy as np
import pandas as pd
import requests
from scipy.stats import norm, chi2, genpareto
import matplotlib.pyplot as plt
from arch import arch_model
%matplotlib inline
In [2]:
res = requests.get('http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=sh000001&scale=240&ma=no&datalen=10000')
# scale单位是分钟。这个地址数据很全,开盘、收盘、最高、最低、成交量。
# ma 移动平均参数
# datalen 数据量参数
data_json = res.json()
data = pd.DataFrame(data_json)
data.to_csv('data_ssec.csv')
print(data)
             day      open      high       low     close       volume
0     1990-12-19    96.050    99.980    95.790    99.980       126000
1     1990-12-20   104.300   104.390    99.980   104.390        19700
2     1990-12-21   109.070   109.130   103.730   109.130         2800
3     1990-12-24   113.570   114.550   109.130   114.550         3200
4     1990-12-25   120.090   120.250   114.550   120.250         1500
...          ...       ...       ...       ...       ...          ...
7417  2021-04-26  3484.107  3497.121  3438.572  3441.166  27697077100
7418  2021-04-27  3440.091  3443.854  3417.265  3442.611  25303239300
7419  2021-04-28  3432.161  3457.068  3423.325  3457.068  24738112000
7420  2021-04-29  3458.082  3478.228  3447.588  3474.901  27663138700
7421  2021-04-30  3468.302  3469.087  3426.902  3446.856  31266035400

[7422 rows x 6 columns]
In [4]:
data = pd.read_csv('data_ssec.csv')
data['return'] = np.log(data['close']) - np.log(data['close'].shift(periods=1))
data['day'] = pd.to_datetime(data['day'], format='%Y-%m-%d')
ind = data['day'] >= pd.to_datetime('2011-01-01', format='%Y-%m-%d')
r = data[ind]['return'].values*100
plt.plot(r)
plt.show()
In [6]:
# RiskMetrics方法
l = np.fix(len(r)/3).astype(int)
VaR_RM = np.zeros(len(r))
qalpha = norm.ppf(0.05)
for i in range(l, len(r)):
    mhat, shat = norm.fit(r[i-50:i])
    VaR_RM[i] = -(mhat + qalpha*shat)
plt.plot(r)
plt.plot(VaR_RM*-1)
plt.show()
In [8]:
l = np.fix(len(r)/3).astype(int)
VaR_GN = np.zeros(len(r))
qalpha = norm.ppf(0.05)
for i in range(l, len(r)):
    am_ar_garch = arch_model(r[:i], mean='ar', lags=1, vol='garch', dist='normal', p=2, q=2)
    res_ar_garch = am_ar_garch.fit()
    a = res_ar_garch.forecast(horizon=1, align='origin')
    mu = a.mean['h.1'].iloc[-1]
    sigma = a.variance['h.1'].iloc[-1]
    VaR_GN[i] = -(mu + qalpha * np.sqrt(sigma))
    
plt.plot(r)
plt.plot(VaR_GN*-1)
plt.show()
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1775472581.7961023
Iteration:      2,   Func. Count:     20,   Neg. LLF: 40316.00309103527
Iteration:      3,   Func. Count:     31,   Neg. LLF: 409274.7063388923
Iteration:      4,   Func. Count:     42,   Neg. LLF: 1283.1835725355227
Iteration:      5,   Func. Count:     54,   Neg. LLF: 2086.695828891242
Iteration:      6,   Func. Count:     65,   Neg. LLF: 1270.3025237707686
Iteration:      7,   Func. Count:     73,   Neg. LLF: 1270.2815986700302
Iteration:      8,   Func. Count:     81,   Neg. LLF: 1270.2777492570012
Iteration:      9,   Func. Count:     89,   Neg. LLF: 1270.2762290205446
Iteration:     10,   Func. Count:     97,   Neg. LLF: 1270.276198587102
Iteration:     11,   Func. Count:    105,   Neg. LLF: 1270.2761966179305
Iteration:     12,   Func. Count:    113,   Neg. LLF: 1270.2761957595026
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1270.2761957595026
            Iterations: 12
            Function evaluations: 113
            Gradient evaluations: 12
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1742718017.8544846
Iteration:      2,   Func. Count:     20,   Neg. LLF: 44402.177406983865
Iteration:      3,   Func. Count:     31,   Neg. LLF: 148831.20057848905
Iteration:      4,   Func. Count:     42,   Neg. LLF: 1285.6679988285712
Iteration:      5,   Func. Count:     54,   Neg. LLF: 2177.203497447923
Iteration:      6,   Func. Count:     65,   Neg. LLF: 1271.235497065043
Iteration:      7,   Func. Count:     73,   Neg. LLF: 1271.2198754263236
Iteration:      8,   Func. Count:     81,   Neg. LLF: 1271.2176678829012
Iteration:      9,   Func. Count:     89,   Neg. LLF: 1271.216917387409
Iteration:     10,   Func. Count:     97,   Neg. LLF: 1271.2168825131848
Iteration:     11,   Func. Count:    105,   Neg. LLF: 1271.2168802851302
Iteration:     12,   Func. Count:    113,   Neg. LLF: 1271.216878749196
Iteration:     13,   Func. Count:    120,   Neg. LLF: 1271.2168787484711
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1271.216878749196
            Iterations: 13
            Function evaluations: 120
            Gradient evaluations: 13
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1760992445.8523707
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
Iteration:      2,   Func. Count:     20,   Neg. LLF: 41569.549294359604
Iteration:      3,   Func. Count:     31,   Neg. LLF: 306222.9773760098
Iteration:      4,   Func. Count:     42,   Neg. LLF: 1287.8489125864737
Iteration:      5,   Func. Count:     54,   Neg. LLF: 2130.420533294795
Iteration:      6,   Func. Count:     65,   Neg. LLF: 1272.170432960618
Iteration:      7,   Func. Count:     73,   Neg. LLF: 1272.1589483164062
Iteration:      8,   Func. Count:     81,   Neg. LLF: 1272.157122424151
Iteration:      9,   Func. Count:     89,   Neg. LLF: 1272.1570756331337
Iteration:     10,   Func. Count:     97,   Neg. LLF: 1272.1570060556853
Iteration:     11,   Func. Count:    105,   Neg. LLF: 1272.1570037225126
Iteration:     12,   Func. Count:    113,   Neg. LLF: 1272.1570022605752
Iteration:     13,   Func. Count:    120,   Neg. LLF: 1272.1570022598362
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1272.1570022605752
            Iterations: 13
            Function evaluations: 120
            Gradient evaluations: 13
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1759879789.0960488
Iteration:      2,   Func. Count:     20,   Neg. LLF: 55168.13123045802
Iteration:      3,   Func. Count:     31,   Neg. LLF: 828145.6805271177
Iteration:      4,   Func. Count:     41,   Neg. LLF: 1295.642089588694
Iteration:      5,   Func. Count:     53,   Neg. LLF: 2176.4994372917718
Iteration:      6,   Func. Count:     64,   Neg. LLF: 1273.2325602898013
Iteration:      7,   Func. Count:     72,   Neg. LLF: 1273.2252055235663
Iteration:      8,   Func. Count:     81,   Neg. LLF: 1273.2085312027511
Iteration:      9,   Func. Count:     89,   Neg. LLF: 1273.2068785972597
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
Iteration:     10,   Func. Count:     97,   Neg. LLF: 1273.2067285164026
Iteration:     11,   Func. Count:    105,   Neg. LLF: 1273.2067104196256
Iteration:     12,   Func. Count:    113,   Neg. LLF: 1273.2067094479653
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1273.2067094479653
            Iterations: 12
            Function evaluations: 113
            Gradient evaluations: 12
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1739575944.1926255
Iteration:      2,   Func. Count:     20,   Neg. LLF: 44391.089560647924
Iteration:      3,   Func. Count:     31,   Neg. LLF: 870807.8494423861
Iteration:      4,   Func. Count:     41,   Neg. LLF: 1298.637813159124
Iteration:      5,   Func. Count:     53,   Neg. LLF: 2141.0455138828966
Iteration:      6,   Func. Count:     64,   Neg. LLF: 1274.218868114051
Iteration:      7,   Func. Count:     72,   Neg. LLF: 1274.2107921643706
Iteration:      8,   Func. Count:     80,   Neg. LLF: 1274.1978710231158
Iteration:      9,   Func. Count:     88,   Neg. LLF: 1274.196006937019
Iteration:     10,   Func. Count:     96,   Neg. LLF: 1274.1958798085627
Iteration:     11,   Func. Count:    104,   Neg. LLF: 1274.1958708188542
Iteration:     12,   Func. Count:    112,   Neg. LLF: 1274.1958681347674
Iteration:     13,   Func. Count:    119,   Neg. LLF: 1274.1958681383842
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1274.1958681347674
            Iterations: 13
            Function evaluations: 119
            Gradient evaluations: 13
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1685625972.4312558
Iteration:      2,   Func. Count:     20,   Neg. LLF: 56983.14922170797
Iteration:      3,   Func. Count:     31,   Neg. LLF: 230469.61256936064
Iteration:      4,   Func. Count:     41,   Neg. LLF: 1301.7912007061154
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
Iteration:      5,   Func. Count:     53,   Neg. LLF: 2187.0784631937922
Iteration:      6,   Func. Count:     64,   Neg. LLF: 1275.3636853469736
Iteration:      7,   Func. Count:     72,   Neg. LLF: 1275.357767101828
Iteration:      8,   Func. Count:     80,   Neg. LLF: 1275.3473218835356
Iteration:      9,   Func. Count:     88,   Neg. LLF: 1275.3461905223276
Iteration:     10,   Func. Count:     96,   Neg. LLF: 1275.346099467325
Iteration:     11,   Func. Count:    104,   Neg. LLF: 1275.3460936509211
Iteration:     12,   Func. Count:    112,   Neg. LLF: 1275.3460919260306
Iteration:     13,   Func. Count:    119,   Neg. LLF: 1275.3460919288175
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1275.3460919260306
            Iterations: 13
            Function evaluations: 119
            Gradient evaluations: 13
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1691502213.1720862
Iteration:      2,   Func. Count:     20,   Neg. LLF: 55973.28186933303
Iteration:      3,   Func. Count:     31,   Neg. LLF: 530237.0684501444
Iteration:      4,   Func. Count:     41,   Neg. LLF: 1305.9756680660548
Iteration:      5,   Func. Count:     53,   Neg. LLF: 2131.885741124604
Iteration:      6,   Func. Count:     64,   Neg. LLF: 1276.2713032453316
Iteration:      7,   Func. Count:     72,   Neg. LLF: 1276.264691078562
Iteration:      8,   Func. Count:     80,   Neg. LLF: 1276.2552757640597
Iteration:      9,   Func. Count:     88,   Neg. LLF: 1276.2542846653696
Iteration:     10,   Func. Count:     96,   Neg. LLF: 1276.2542140569096
Iteration:     11,   Func. Count:    104,   Neg. LLF: 1276.254210442231
Iteration:     12,   Func. Count:    112,   Neg. LLF: 1276.2542090769593
Iteration:     13,   Func. Count:    119,   Neg. LLF: 1276.2542090789693
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1276.2542090769593
            Iterations: 13
            Function evaluations: 119
            Gradient evaluations: 13
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1690726304.016419
Iteration:      2,   Func. Count:     20,   Neg. LLF: 33856.078512119304
Iteration:      3,   Func. Count:     31,   Neg. LLF: 1813172.576547527
Iteration:      4,   Func. Count:     41,   Neg. LLF: 1309.9376628488421
Iteration:      5,   Func. Count:     53,   Neg. LLF: 2135.3077900710487
Iteration:      6,   Func. Count:     64,   Neg. LLF: 1277.3689918097157
Iteration:      7,   Func. Count:     72,   Neg. LLF: 1277.3621304975811
Iteration:      8,   Func. Count:     80,   Neg. LLF: 1277.3534969132593
Iteration:      9,   Func. Count:     88,   Neg. LLF: 1277.3526024841617
Iteration:     10,   Func. Count:     96,   Neg. LLF: 1277.3525438739375
Iteration:     11,   Func. Count:    104,   Neg. LLF: 1277.352541251017
Iteration:     12,   Func. Count:    112,   Neg. LLF: 1277.3525401964907
Iteration:     13,   Func. Count:    119,   Neg. LLF: 1277.3525401982197
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1277.3525401964907
            Iterations: 13
            Function evaluations: 119
            Gradient evaluations: 13
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1726481721.6684022
Iteration:      2,   Func. Count:     20,   Neg. LLF: 37738.23132356776
Iteration:      3,   Func. Count:     31,   Neg. LLF: 446153.8857436554
Iteration:      4,   Func. Count:     41,   Neg. LLF: 1315.0397814848686
Iteration:      5,   Func. Count:     53,   Neg. LLF: 2063.864978948071
Iteration:      6,   Func. Count:     64,   Neg. LLF: 1278.2748389015305
Iteration:      7,   Func. Count:     72,   Neg. LLF: 1278.2656100078957
Iteration:      8,   Func. Count:     80,   Neg. LLF: 1278.256167251689
Iteration:      9,   Func. Count:     88,   Neg. LLF: 1278.2549282863688
Iteration:     10,   Func. Count:     96,   Neg. LLF: 1278.254867024084
Iteration:     11,   Func. Count:    104,   Neg. LLF: 1278.2548641675048
Iteration:     12,   Func. Count:    112,   Neg. LLF: 1278.2548632665032
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1278.2548632665032
            Iterations: 12
            Function evaluations: 112
            Gradient evaluations: 12
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1760124248.563623
Iteration:      2,   Func. Count:     20,   Neg. LLF: 27616.31085006999
Iteration:      3,   Func. Count:     31,   Neg. LLF: 12679709.76128373
Iteration:      4,   Func. Count:     41,   Neg. LLF: 1319.8945897527371
Iteration:      5,   Func. Count:     52,   Neg. LLF: 2489.3070327577334
Iteration:      6,   Func. Count:     63,   Neg. LLF: 1279.3009956290248
Iteration:      7,   Func. Count:     71,   Neg. LLF: 1279.2994269878636
Iteration:      8,   Func. Count:     80,   Neg. LLF: 1279.265529713959
Iteration:      9,   Func. Count:     88,   Neg. LLF: 1279.2642539394376
Iteration:     10,   Func. Count:     96,   Neg. LLF: 1279.2642443989885
Iteration:     11,   Func. Count:    104,   Neg. LLF: 1279.2642429058712
Iteration:     12,   Func. Count:    111,   Neg. LLF: 1279.2642429104599
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1279.2642429058712
            Iterations: 12
            Function evaluations: 111
            Gradient evaluations: 12
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1807182139.7595272
Iteration:      2,   Func. Count:     20,   Neg. LLF: 28302.120386454284
Iteration:      3,   Func. Count:     31,   Neg. LLF: 1213794.5681271588
Iteration:      4,   Func. Count:     41,   Neg. LLF: 1325.7293855953415
Iteration:      5,   Func. Count:     52,   Neg. LLF: 2247.779965788817
Iteration:      6,   Func. Count:     63,   Neg. LLF: 1280.2064830250406
Iteration:      7,   Func. Count:     71,   Neg. LLF: 1280.199765489891
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
Iteration:      8,   Func. Count:     80,   Neg. LLF: 1280.1710703257388
Iteration:      9,   Func. Count:     88,   Neg. LLF: 1280.1683306707168
Iteration:     10,   Func. Count:     96,   Neg. LLF: 1280.16832212604
Iteration:     11,   Func. Count:    104,   Neg. LLF: 1280.1683209710484
Iteration:     12,   Func. Count:    111,   Neg. LLF: 1280.168320975117
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1280.1683209710484
            Iterations: 12
            Function evaluations: 111
            Gradient evaluations: 12
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1813529406.4363716
Iteration:      2,   Func. Count:     20,   Neg. LLF: 28354.02191688698
Iteration:      3,   Func. Count:     31,   Neg. LLF: 2664440.9018729604
Iteration:      4,   Func. Count:     41,   Neg. LLF: 1333.545087693818
Iteration:      5,   Func. Count:     52,   Neg. LLF: 2012.1483769632782
Iteration:      6,   Func. Count:     63,   Neg. LLF: 1281.0886467043051
Iteration:      7,   Func. Count:     71,   Neg. LLF: 1281.0743843769508
Iteration:      8,   Func. Count:     79,   Neg. LLF: 1281.055865694892
Iteration:      9,   Func. Count:     87,   Neg. LLF: 1281.0521983701522
Iteration:     10,   Func. Count:     95,   Neg. LLF: 1281.0520487069891
Iteration:     11,   Func. Count:    103,   Neg. LLF: 1281.0520432500257
Iteration:     12,   Func. Count:    110,   Neg. LLF: 1281.0520432548788
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1281.0520432500257
            Iterations: 12
            Function evaluations: 110
            Gradient evaluations: 12
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1829710416.5581865
Iteration:      2,   Func. Count:     20,   Neg. LLF: 26349.5079047504
Iteration:      3,   Func. Count:     31,   Neg. LLF: 3991875.441846581
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
Iteration:      4,   Func. Count:     41,   Neg. LLF: 1341.5468625178382
Iteration:      5,   Func. Count:     52,   Neg. LLF: 1789.1279955725167
Iteration:      6,   Func. Count:     63,   Neg. LLF: 1281.960426043036
Iteration:      7,   Func. Count:     71,   Neg. LLF: 1281.9326911533174
Iteration:      8,   Func. Count:     79,   Neg. LLF: 1281.918907700564
Iteration:      9,   Func. Count:     87,   Neg. LLF: 1281.9135775432555
Iteration:     10,   Func. Count:     95,   Neg. LLF: 1281.9134784278453
Iteration:     11,   Func. Count:    103,   Neg. LLF: 1281.9134744505527
Iteration:     12,   Func. Count:    110,   Neg. LLF: 1281.9134744523644
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1281.9134744505527
            Iterations: 12
            Function evaluations: 110
            Gradient evaluations: 12
Iteration:      1,   Func. Count:      9,   Neg. LLF: 1857619000.9443517
Iteration:      2,   Func. Count:     20,   Neg. LLF: 31046.080525338275
Iteration:      3,   Func. Count:     31,   Neg. LLF: 5013508.185155103
Iteration:      4,   Func. Count:     41,   Neg. LLF: 1350.6747508870035
Iteration:      5,   Func. Count:     52,   Neg. LLF: 1631.9229473907035
Iteration:      6,   Func. Count:     63,   Neg. LLF: 1282.8709137223643
Iteration:      7,   Func. Count:     71,   Neg. LLF: 1282.8137172898719
Iteration:      8,   Func. Count:     79,   Neg. LLF: 1282.804526029207
Iteration:      9,   Func. Count:     87,   Neg. LLF: 1282.7944108498311
Iteration:     10,   Func. Count:     95,   Neg. LLF: 1282.7942738223508
Iteration:     11,   Func. Count:    103,   Neg. LLF: 1282.7942664246216
Iteration:     12,   Func. Count:    110,   Neg. LLF: 1282.7942664209831
Optimization terminated successfully    (Exit mode 0)
            Current function value: 1282.7942664246216
            Iterations: 12
            Function evaluations: 110
            Gradient evaluations: 12
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
C:\ProgramData\Anaconda3\lib\site-packages\arch\__future__\_utility.py:11: FutureWarning: 
The default for reindex is True. After September 2021 this will change to
False. Set reindex to True or False to silence this message. Alternatively,
you can use the import comment

from arch.__future__ import reindexing

to globally set reindex to True and silence this warning.

  warnings.warn(
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-8-c0fe7f17dcea> in <module>
      4 for i in range(l, len(r)):
      5     am_ar_garch = arch_model(r[:i], mean='ar', lags=1, vol='garch', dist='normal', p=2, q=2)
----> 6     res_ar_garch = am_ar_garch.fit()
      7     a = res_ar_garch.forecast(horizon=1, align='origin')
      8     mu = a.mean['h.1'].iloc[-1]

C:\ProgramData\Anaconda3\lib\site-packages\arch\univariate\base.py in fit(self, update_freq, disp, starting_values, cov_type, show_warning, first_obs, last_obs, tol, options, backcast)
    659         assert backcast is not None
    660         self._backcast = backcast
--> 661         sv_volatility = v.starting_values(resids)
    662         self._var_bounds = var_bounds = v.variance_bounds(resids)
    663         v.compute_variance(sv_volatility, resids, sigma2, backcast, var_bounds)

C:\ProgramData\Anaconda3\lib\site-packages\arch\univariate\volatility.py in starting_values(self, resids)
   1136                 sv[1 + p + o : 1 + p + o + q] = agb / q
   1137             svs.append(sv)
-> 1138             llfs[i] = self._gaussian_loglikelihood(sv, resids, backcast, var_bounds)
   1139         loc = np.argmax(llfs)
   1140 

C:\ProgramData\Anaconda3\lib\site-packages\arch\univariate\volatility.py in _gaussian_loglikelihood(self, parameters, resids, backcast, var_bounds)
    746         sigma2 = np.zeros_like(resids)
    747         self.compute_variance(parameters, resids, sigma2, backcast, var_bounds)
--> 748         return float(self._normal.loglikelihood([], resids, sigma2))
    749 
    750     @abstractmethod

C:\ProgramData\Anaconda3\lib\site-packages\arch\univariate\distribution.py in loglikelihood(self, parameters, resids, sigma2, individual)
    384 
    385         """
--> 386         lls = -0.5 * (log(2 * pi) + log(sigma2) + resids ** 2.0 / sigma2)
    387         if individual:
    388             return lls

KeyboardInterrupt: 
In [9]:
# 历史模拟方法
l = np.fix(len(r)/3).astype(int)
VaR_HS = np.zeros(len(r))
qalpha = int(200*0.05)
for i in range(l, len(r)):
    his_sample = r[i-200:i]
    his_sample = np.sort(his_sample)
    VaR_HS[i] = -his_sample[qalpha-1]
plt.plot(r)
plt.plot(VaR_HS*-1)
plt.show()
In [11]:
# POT方法
l = np.fix(len(r)/3).astype(int)
VaR_EVT = np.zeros(len(r))
alpha = 0.05
for i in range(l, len(r)):
    his_sample = r[i-200:i]
    his_sample = np.sort(his_sample)
    ind = np.ceil(len(his_sample)*0.1).astype(int)
    evt_sample = np.abs(his_sample[:ind])
    u = evt_sample[-1]
    evt_sample = evt_sample - u
    evt_sample = np.delete(evt_sample, -1)

    n = len(his_sample)
    Nu = len(evt_sample)

    parmhat = genpareto.fit(evt_sample, floc=0)
    kHat = parmhat[0]; # Tail index parameter
    sigmaHat = parmhat[2]; # Scale parameter
    VaR_EVT[i] = u + sigmaHat / kHat * ((alpha * n / Nu) ** -kHat - 1)
plt.plot(r)
plt.plot(VaR_EVT*-1)
plt.show()
In [ ]:
data = pd.DataFrame({'return': r, 'VaR_RM': VaR_RM, 'VaR_GN': VaR_GN, 'VaR_HS': VaR_HS, 'VaR_EVT': VaR_EVT})
data.to_csv('Data_VaR.csv')
In [12]:
def myfun_Kupiec(r, VaR, pstar):
    N = np.sum(r > VaR)
    T = len(r)
    LRuc = -2*((T-N)*np.log(1-pstar)+N*np.log(pstar)) + 2*((T-N)*np.log(1-N/T)+N*np.log(N/T))
    pvalue_LRuc = 1 - chi2.cdf(LRuc, 1)
    return LRuc, pvalue_LRuc

def myfun_Christoffersen(r, VaR):
    ind = r > VaR
    ind1 = ind[:-1]
    ind2 = ind[1:]
    n00 = np.sum((ind1==0) & (ind2==0))
    n01 = np.sum((ind1==0) & (ind2==1))
    n10 = np.sum((ind1==1) & (ind2==0))
    n11 = np.sum((ind1==1) & (ind2==1))

    Pi01 = n01/(n01+n00)
    Pi11 = n11/(n10+n11)
    Pi2 = (n01+n11)/(n00+n01+n10+n11)

    LRind = (n00+n10)*np.log(1-Pi2) + (n01+n11)*np.log(Pi2) - \
            n00*np.log(1-Pi01) - n01*np.log(Pi01) - n10*np.log(1-Pi11) - n11*np.log(Pi11)
    LRind = LRind*-2
    pvalue_LRind = 1 - chi2.cdf(LRind, 1)
    return LRind, pvalue_LRind

def myfun_Kupiec_Christoffersen(LRuc, LRind):
    LRcc = LRuc + LRind
    pvalue_LRcc = 1 - chi2.cdf(LRcc, 2)
    return LRcc, pvalue_LRcc

data = pd.read_csv('Data_VaR.csv')
ind = data['VaR_RM'] > 0
r = data.loc[ind, ['return']].values*-1
VaR_RM = data.loc[ind, ['VaR_RM']].values
VaR_GN = data.loc[ind, ['VaR_GN']].values
VaR_HS = data.loc[ind, ['VaR_HS']].values
VaR_EVT = data.loc[ind, ['VaR_EVT']].values

pstar = 0.05;
[LRuc_RM, pvalue_LRuc_RM] = myfun_Kupiec(r, VaR_RM, pstar)
[LRind_RM, pvalue_LRind_RM] = myfun_Christoffersen(r, VaR_RM)
[LRcc_RM, pvalue_LRcc_RM] = myfun_Kupiec_Christoffersen(LRuc_RM, LRind_RM)

[LRuc_GN, pvalue_LRuc_GN] = myfun_Kupiec(r, VaR_GN, pstar)
[LRind_GN, pvalue_LRind_GN] = myfun_Christoffersen(r, VaR_GN)
[LRcc_GN, pvalue_LRcc_GN] = myfun_Kupiec_Christoffersen(LRuc_GN, LRind_GN)

[LRuc_HS, pvalue_LRuc_HS] = myfun_Kupiec(r, VaR_HS, pstar)
[LRind_HS, pvalue_LRind_HS] = myfun_Christoffersen(r, VaR_HS)
[LRcc_HS, pvalue_LRcc_HS] = myfun_Kupiec_Christoffersen(LRuc_HS, LRind_HS)

[LRuc_EVT, pvalue_LRuc_EVT] = myfun_Kupiec(r, VaR_EVT, pstar)
[LRind_EVT, pvalue_LRind_EVT] = myfun_Christoffersen(r, VaR_EVT)
[LRcc_EVT, pvalue_LRcc_EVT] = myfun_Kupiec_Christoffersen(LRuc_EVT, LRind_EVT)


print('{:12s}, {:>12s}, {:>12s}, {:>12s}, {:>12s}, {:>12s}, {:>12s}'.format('', 'LRuc', 'pLRuc', 'LRind', 'pLRind', 'LRcc', 'pLRcc'))
print('{:12s}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}'.format('RiskMetrics', LRuc_RM, pvalue_LRuc_RM, LRind_RM, pvalue_LRind_RM, LRcc_RM, pvalue_LRcc_RM))
print('{:12s}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}'.format('GarchNormal', LRuc_GN, pvalue_LRuc_GN, LRind_GN, pvalue_LRind_GN, LRcc_GN, pvalue_LRcc_GN))
print('{:12s}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}'.format('HisSim', LRuc_HS, pvalue_LRuc_HS, LRind_HS, pvalue_LRind_HS, LRcc_HS, pvalue_LRcc_HS))
print('{:12s}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}, {:12.4f}'.format('EVT GPD', LRuc_EVT, pvalue_LRuc_EVT, LRind_EVT, pvalue_LRind_EVT,LRcc_EVT, pvalue_LRcc_EVT))
            ,         LRuc,        pLRuc,        LRind,       pLRind,         LRcc,        pLRcc
RiskMetrics ,       1.2853,       0.2569,       3.9733,       0.0462,       5.2587,       0.0721
GarchNormal ,       0.2829,       0.5948,       0.4341,       0.5100,       0.7170,       0.6987
HisSim      ,       1.8203,       0.1773,      15.7443,       0.0001,      17.5646,       0.0002
EVT GPD     ,       1.0515,       0.3052,      12.1244,       0.0005,      13.1759,       0.0014