R語言中使用RCPP并行計算指數(shù)加權(quán)波動率
原文鏈接:http://tecdat.cn/?p=17829
?
指數(shù)加權(quán)波動率是一種波動率的度量,它使最近的觀察結(jié)果有更高權(quán)重。我們將使用以下公式計算指數(shù)加權(quán)波動率:
S [t] ^ 2 = SUM(1-a)* a ^ i *(r [t-1-i]-rhat [t])^ 2,i = 0…inf
其中rhat [t]是對應(yīng)的指數(shù)加權(quán)平均值
rhat [t] = SUM(1-a)* a ^ i * r [t-1-i],i = 0…inf
上面的公式取決于每個時間點的完整價格歷史記錄,并花了一些時間進行計算。因此,我想分享Rcpp和RcppParallel如何幫助我們減少計算時間。
我將使用匯率的歷史數(shù)據(jù)集??作為測試數(shù)據(jù)。
首先,我們計算平均滾動波動率
#*****************************************************************
# 計算對數(shù)收益率
#*****************************************************************
ret = diff(log(data$prices))
tic(5)
hist.vol = sqrt(252) * bt.apply.matrix(ret, runSD, n = 200)
toc(5)
經(jīng)過時間為0.17秒
接下來,讓我們編寫指數(shù)加權(quán)代碼邏輯
# 建立 RCPP 函數(shù)計算指數(shù)加權(quán)波動率
load.packages('Rcpp')
sourceCpp(code='
#include <Rcpp.h>
using namespace Rcpp;
using namespace std;
// [[Rcpp::plugins(cpp11)]]
//ema[1] = 0
//ema[t] = (1-a)*r[t-1] + (1-a)*a*ema[t-1]
// [[Rcpp::exp
{
if(!NumericVector::is_na(x[t])) break;
res[t] = NA_REAL;
}
int start_t = t;
-a) * a^i * (r[t-1-i] - rhat[t])^2, i=0 ... inf
// [[Rcpp::export]]
NumericVector run_esd_cpp(NumericVector x, double ratio) {
auto sz = x.siz
// find start index; first non NA item
for(t = 0; t < sz; t++) {
if(!Num
0;
for(t = start_t + 1; t < sz; t++) {
ema = (1-ratio) * ( x[t-1] + ratio * ema);
double sigma = 0;
for(int i = 0; i < (t - start_t); i++) {
sigma += pow(ratio,i) * pow(x[t-1-i] - ema, 2);
}
res[t] = (1-ratio) * sigma;
}
, n, ratio = n/(n+1)) run_ema_cpp(x, ratio)
run.esd = funct
?經(jīng)過時間為106.16秒。
執(zhí)行此代碼花了一段時間。但是,代碼可以并行運行。以下是RcppParallel版本。
# 建立 RCPP 并行函數(shù)計算指數(shù)加權(quán)波動率
load.packages('RcppParallel')
sourceCpp(code='
using namespace Rcpp;
using namespace s
s(cpp11)]]
// [[Rcpp::depends(R
to read from
const RMatrix<double> mat;
// internal variables
const double ratio
t;
// initialize from Rcpp input and output matrixes
run_esd_helper(const Nume
all operator that work for th
in, size_t end) {
for (size_t c1 = begin; c1 < end; c1++) {
int t;
// find start index; fir
經(jīng)過時間為14.65秒
運行時間更短。接下來,讓我們直觀地了解使用指數(shù)加權(quán)波動率的影響
dates = '2007::2010'
layout(1:2)
e='h', col='black', plotX=F)
plota.legend(paste('Dai
s,1],type='l',col='black')

?
?
不出所料,指數(shù)加權(quán)波動率在最近的觀察結(jié)果中占了更大的比重,是一種更具反應(yīng)性的風(fēng)險度量。

最受歡迎的見解
1.HAR-RV-J與遞歸神經(jīng)網(wǎng)絡(luò)(RNN)混合模型預(yù)測和交易大型股票指數(shù)的高頻波動率
2.WinBUGS對多元隨機波動率模型:貝葉斯估計與模型比較
3.波動率的實現(xiàn):ARCH模型與HAR-RV模型
4.R語言ARMA-EGARCH模型、集成預(yù)測算法對SPX實際波動率進行預(yù)測
5.使用R語言隨機波動模型SV處理時間序列中的隨機波動率
6.R語言多元COPULA GARCH 模型時間序列預(yù)測
7.R語言基于ARMA-GARCH過程的VAR擬合和預(yù)測
8.R語言隨機搜索變量選擇SSVS估計貝葉斯向量自回歸(BVAR)模型
9.R語言對S&P500股票指數(shù)進行ARIMA + GARCH交易策略