CAPM.beta rollapply
我已经在我的CAPM.beta rollapply,r,xts,rollapply,performanceanalytics,rolling-computation,R,Xts,Rollapply,Performanceanalytics,Rolling Computation,我已经在我的xts对象中使用 x实际上,PerformanceAnalytics函数将给出相同的结果,但需要更长的时间。下面的代码使用2017-01-01至今的样本数据,AMZN和XOM作为股票,SPY作为市场回报的代理。滚动计算中使用了40个交易日的窗口。滚动贝塔值是使用PerformanceAnalytics中的CAPM.beta和Betacovance函数,并通过三种方法计算的,这三种方法直接计算协方差矩阵,然后取成对协方差与市场方差的比率。将显示这些方法的结果,以表明它们是相同的micr
xts
对象中使用
x实际上,PerformanceAnalytics
函数将给出相同的结果,但需要更长的时间。下面的代码使用2017-01-01至今的样本数据,AMZN和XOM作为股票,SPY作为市场回报的代理。滚动计算中使用了40个交易日的窗口。滚动贝塔值是使用PerformanceAnalytics
中的CAPM.beta
和Betacovance
函数,并通过三种方法计算的,这三种方法直接计算协方差矩阵,然后取成对协方差与市场方差的比率。将显示这些方法的结果,以表明它们是相同的<来自microbenchmark
包的code>microbenchmark
用于测量所有方法的执行时间。直接计算要快一到两个数量级
library(xts)
library(quantmod)
library(PerformanceAnalytics)
library(microbenchmark)
#
# get price time histories and calculate returns
# use SPY as proxy for S&P 500; SPY should be first symbol in assets
#
assets <- c("SPY", "AMZN", "XOM")
getSymbols( assets, from = "2017-01-01", auto.assign = TRUE)
asset_prices <- xts()
asset_prices <- Reduce(f=function(x,y) {y_sym=eval(as.name(y)); merge(x,y_sym[,paste0(y,".Adjusted")])},
x = assets, init=asset_prices)
asset_returns <- diff.xts(asset_prices, arithmetic = FALSE, na.pad=FALSE)-1
market_return <- asset_returns$SPY.Adjusted
stock_returns <- asset_returns[,-1]
#
# calculate rolling beta with a 40 trading-day window using CAPM.beta.roll
# For this amount of data and calculating daily betas (by = 1), calculation should take 5-10 seconds
#
width_cor = 40
CAPM.beta_roll <- rollapply(data=stock_returns, FUN=CAPM.beta, Rb= market_return, Rf = 2.5/252,
width = width_cor, by = 1, align = "right", by.column=TRUE)
#
# calculate rolling beta with a 40 trading-day window by calculating the covariance matrix and taking ratio of two elements
# For this amount of data and calculating daily betas (by = 1), calculation should be very quick
#
CovVar <- function(Ra, Rb) {R = merge.xts(Rb, Ra, join="inner"); cv=cov(x=R);
cv[1,-1]/cv[1,1,drop=TRUE]}
CovVar_roll <- rollapplyr(data=stock_returns, width=width_cor,
FUN= CovVar, Rb = market_return, by.column=FALSE)
#
# since rollapply does not apply the window to Rb, it is done in CovVar for each time window
# CovVar1 is a faster version which passes the merged market and stock return to cov directly
# Its single argument R must be the merged data matrix R
#
CovVar1 <- function(R){ cv=cov(x=R); cv[-1,1]/cv[1,1]}
CovVar1_roll <- rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar1, by.column=FALSE)
#
# CovVar2 is a faster version which passes the merged market and stock return to cov directly and
# calculates the covariances only between the market returns and stock_returns. For a small number of stocks,
# this is less efficient than calculating the entire covariance for a single matrix as in CovVar1 but it should become more
# efficient for a larger number of stocks.
# Its single argument R must be the merged data matrix R
#
CovVar2 <- function(R){ cv = cov(R[,1], R ); cv[,-1]/cv[1,1] }
CovVar2_roll <- rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar2, by.column=FALSE)
#
# Compare to verify that results are the same
#
print(tail(merge(CAPM.beta_roll, CovVar_roll, CovVar1_roll, CovVar2_roll )))
#
# Compare execution times for four above methods and third method using BetaCovariance function from PerformanceAnalytics
# This should take 25-35 seconds to run
#
elapsed_times <- microbenchmark(
CAPM.beta_roll = rollapplyr(data=stock_returns, width=width_cor,
FUN= CAPM.beta, Rb=market_return,by.column=FALSE),
BetaCoVar_roll = rollapplyr(data=stock_returns, width=width_cor,
FUN= BetaCoVariance, Rb=market_return,by.column=FALSE),
CovVar_roll = rollapplyr(data=stock_returns, width=width_cor,
FUN= CovVar, Rb = market_return, by.column=FALSE),
CovVar1_roll = rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar1, by.column=FALSE),
CovVar2_roll = rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar2, by.column=FALSE),
times = 3)
#
# Direct calculation using covariance matrix, CovVar, is 50 - 100 times faster than PerformanceAnalytics functions
#
print(elapsed_times)
CovVar1是最快的,因为至少对于少量的维度,R计算单个矩阵输入的协方差矩阵的效率要比计算两个矩阵输入的协方差矩阵的效率高得多,其中必须对齐矩阵。对于一些较大数量的维度,CovVar2应该更快。实际上,
PerformanceAnalytics
函数将给出相同的结果,但需要更长的时间。下面的代码使用2017-01-01至今的样本数据,AMZN和XOM作为股票,SPY作为市场回报的代理。滚动计算中使用了40个交易日的窗口。滚动贝塔值是使用PerformanceAnalytics
中的CAPM.beta
和Betacovance
函数,并通过三种方法计算的,这三种方法直接计算协方差矩阵,然后取成对协方差与市场方差的比率。将显示这些方法的结果,以表明它们是相同的<来自microbenchmark
包的code>microbenchmark用于测量所有方法的执行时间。直接计算要快一到两个数量级
library(xts)
library(quantmod)
library(PerformanceAnalytics)
library(microbenchmark)
#
# get price time histories and calculate returns
# use SPY as proxy for S&P 500; SPY should be first symbol in assets
#
assets <- c("SPY", "AMZN", "XOM")
getSymbols( assets, from = "2017-01-01", auto.assign = TRUE)
asset_prices <- xts()
asset_prices <- Reduce(f=function(x,y) {y_sym=eval(as.name(y)); merge(x,y_sym[,paste0(y,".Adjusted")])},
x = assets, init=asset_prices)
asset_returns <- diff.xts(asset_prices, arithmetic = FALSE, na.pad=FALSE)-1
market_return <- asset_returns$SPY.Adjusted
stock_returns <- asset_returns[,-1]
#
# calculate rolling beta with a 40 trading-day window using CAPM.beta.roll
# For this amount of data and calculating daily betas (by = 1), calculation should take 5-10 seconds
#
width_cor = 40
CAPM.beta_roll <- rollapply(data=stock_returns, FUN=CAPM.beta, Rb= market_return, Rf = 2.5/252,
width = width_cor, by = 1, align = "right", by.column=TRUE)
#
# calculate rolling beta with a 40 trading-day window by calculating the covariance matrix and taking ratio of two elements
# For this amount of data and calculating daily betas (by = 1), calculation should be very quick
#
CovVar <- function(Ra, Rb) {R = merge.xts(Rb, Ra, join="inner"); cv=cov(x=R);
cv[1,-1]/cv[1,1,drop=TRUE]}
CovVar_roll <- rollapplyr(data=stock_returns, width=width_cor,
FUN= CovVar, Rb = market_return, by.column=FALSE)
#
# since rollapply does not apply the window to Rb, it is done in CovVar for each time window
# CovVar1 is a faster version which passes the merged market and stock return to cov directly
# Its single argument R must be the merged data matrix R
#
CovVar1 <- function(R){ cv=cov(x=R); cv[-1,1]/cv[1,1]}
CovVar1_roll <- rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar1, by.column=FALSE)
#
# CovVar2 is a faster version which passes the merged market and stock return to cov directly and
# calculates the covariances only between the market returns and stock_returns. For a small number of stocks,
# this is less efficient than calculating the entire covariance for a single matrix as in CovVar1 but it should become more
# efficient for a larger number of stocks.
# Its single argument R must be the merged data matrix R
#
CovVar2 <- function(R){ cv = cov(R[,1], R ); cv[,-1]/cv[1,1] }
CovVar2_roll <- rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar2, by.column=FALSE)
#
# Compare to verify that results are the same
#
print(tail(merge(CAPM.beta_roll, CovVar_roll, CovVar1_roll, CovVar2_roll )))
#
# Compare execution times for four above methods and third method using BetaCovariance function from PerformanceAnalytics
# This should take 25-35 seconds to run
#
elapsed_times <- microbenchmark(
CAPM.beta_roll = rollapplyr(data=stock_returns, width=width_cor,
FUN= CAPM.beta, Rb=market_return,by.column=FALSE),
BetaCoVar_roll = rollapplyr(data=stock_returns, width=width_cor,
FUN= BetaCoVariance, Rb=market_return,by.column=FALSE),
CovVar_roll = rollapplyr(data=stock_returns, width=width_cor,
FUN= CovVar, Rb = market_return, by.column=FALSE),
CovVar1_roll = rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar1, by.column=FALSE),
CovVar2_roll = rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar2, by.column=FALSE),
times = 3)
#
# Direct calculation using covariance matrix, CovVar, is 50 - 100 times faster than PerformanceAnalytics functions
#
print(elapsed_times)
CovVar1是最快的,因为至少对于少量的维度,R计算单个矩阵输入的协方差矩阵的效率要比计算两个矩阵输入的协方差矩阵的效率高得多,其中必须对齐矩阵。对于一些较大数量的维度,CovVar2应该更快。这里有一个解决方案,如中所示,但比使用rollRegres
包的CovVar2
函数快16倍左右
库(xts)
图书馆(quantmod)
库(性能分析)
图书馆(微基准)
#设置
资产这里有一个解决方案,如中所示,但比使用rollRegres
包的CovVar2
函数快16倍左右
库(xts)
图书馆(quantmod)
库(性能分析)
图书馆(微基准)
#设置
资产你能提供样本数据来复制问题吗?你能提供样本数据来复制问题吗?啊,非常感谢。我认为这需要更长的时间,但结果确实和我看到的一样。跟进:在你的函数中,cv[1,-1]是成对股票和市场的协方差,对吗?rollapply如何知道它必须只对下一个股票列进行迭代,并保持市场列不变?在CovVar中,rollapply为函数提供了时间窗口的股票返回行Ra。但是,它没有窗口Rb、market_return,因此该函数使用merge.xts和join=“inner”来形成Rb和Ra通用日期的回报矩阵,即该迭代的窗口日期。在第二种方法CovVar_roll1中,市场回报率首先与股票回报率合并,然后提交给rollapply。对于这两种情况,市场回报率是回报矩阵的第一列,因此是cov矩阵的第一行和第一列。cv[1,-1]是股票在该时间窗口内随市场变化的协方差。好的,你知道为什么在我的滚动相关函数中,它被指定为(…),函数(x)cor(x[,1],x[,-1](…)
,因为我从stackoverflow获得了函数,但无法真正理解其背后的概念。它似乎需要第一列和矩阵之间的相关性,而不需要最后一列?x[,-1]从x中删除第一列,而不是最后的.cor(x[,1],x[,-1])计算x的第一列与其余列之间的相关性。我已按answer进行编辑,以显示此方法与我的第一列之间的相关性。上面的结果表明,对于数量较少的股票,计算单个矩阵输入的完全协方差更快。随着股票数目的增加,计算c应该更快只是市场和股票之间的差异。啊,非常感谢。我认为这需要更长的时间,但结果确实和我看到的一样。跟进:在你的职能中,cv[1,-1]是两两股票和市场的协方差,对吗?rollapply如何知道它必须只对下一个股票列进行迭代,并保持市场列不变?在CovVar中,rollapply为函数提供时间窗口的股票返回行Ra。但是,它没有窗口Rb,市场返回,因此函数使用merge.xtsh join=“内部”形成Rb和Ra共同日期的回报矩阵,即该迭代的窗口日期。在第二种方法中,CovVar_roll1,市场_回报首先与股票_回报合并,然后提交给rollapply。对于两者,市场_回报是回报矩阵的第一列,因此是cov矩阵的第一行和第一列。cv[1,-1]然后是股票在该时间窗口内与市场的协方差。好的,你知道为什么在我的滚动相关函数中,它被指定为(…)、函数(x)cor(x[,1],x[,-1](…)
,因为我从stackoverflow得到了这个函数,但我不能真正理解其背后的概念
library(xts)
library(quantmod)
library(PerformanceAnalytics)
library(microbenchmark)
#
# get price time histories and calculate returns
# use SPY as proxy for S&P 500; SPY should be first symbol in assets
#
assets <- c("SPY", "AMZN", "XOM")
getSymbols( assets, from = "2017-01-01", auto.assign = TRUE)
asset_prices <- xts()
asset_prices <- Reduce(f=function(x,y) {y_sym=eval(as.name(y)); merge(x,y_sym[,paste0(y,".Adjusted")])},
x = assets, init=asset_prices)
asset_returns <- diff.xts(asset_prices, arithmetic = FALSE, na.pad=FALSE)-1
market_return <- asset_returns$SPY.Adjusted
stock_returns <- asset_returns[,-1]
#
# calculate rolling beta with a 40 trading-day window using CAPM.beta.roll
# For this amount of data and calculating daily betas (by = 1), calculation should take 5-10 seconds
#
width_cor = 40
CAPM.beta_roll <- rollapply(data=stock_returns, FUN=CAPM.beta, Rb= market_return, Rf = 2.5/252,
width = width_cor, by = 1, align = "right", by.column=TRUE)
#
# calculate rolling beta with a 40 trading-day window by calculating the covariance matrix and taking ratio of two elements
# For this amount of data and calculating daily betas (by = 1), calculation should be very quick
#
CovVar <- function(Ra, Rb) {R = merge.xts(Rb, Ra, join="inner"); cv=cov(x=R);
cv[1,-1]/cv[1,1,drop=TRUE]}
CovVar_roll <- rollapplyr(data=stock_returns, width=width_cor,
FUN= CovVar, Rb = market_return, by.column=FALSE)
#
# since rollapply does not apply the window to Rb, it is done in CovVar for each time window
# CovVar1 is a faster version which passes the merged market and stock return to cov directly
# Its single argument R must be the merged data matrix R
#
CovVar1 <- function(R){ cv=cov(x=R); cv[-1,1]/cv[1,1]}
CovVar1_roll <- rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar1, by.column=FALSE)
#
# CovVar2 is a faster version which passes the merged market and stock return to cov directly and
# calculates the covariances only between the market returns and stock_returns. For a small number of stocks,
# this is less efficient than calculating the entire covariance for a single matrix as in CovVar1 but it should become more
# efficient for a larger number of stocks.
# Its single argument R must be the merged data matrix R
#
CovVar2 <- function(R){ cv = cov(R[,1], R ); cv[,-1]/cv[1,1] }
CovVar2_roll <- rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar2, by.column=FALSE)
#
# Compare to verify that results are the same
#
print(tail(merge(CAPM.beta_roll, CovVar_roll, CovVar1_roll, CovVar2_roll )))
#
# Compare execution times for four above methods and third method using BetaCovariance function from PerformanceAnalytics
# This should take 25-35 seconds to run
#
elapsed_times <- microbenchmark(
CAPM.beta_roll = rollapplyr(data=stock_returns, width=width_cor,
FUN= CAPM.beta, Rb=market_return,by.column=FALSE),
BetaCoVar_roll = rollapplyr(data=stock_returns, width=width_cor,
FUN= BetaCoVariance, Rb=market_return,by.column=FALSE),
CovVar_roll = rollapplyr(data=stock_returns, width=width_cor,
FUN= CovVar, Rb = market_return, by.column=FALSE),
CovVar1_roll = rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar1, by.column=FALSE),
CovVar2_roll = rollapplyr(data=merge(market_return, stock_returns), width=width_cor,
FUN= CovVar2, by.column=FALSE),
times = 3)
#
# Direct calculation using covariance matrix, CovVar, is 50 - 100 times faster than PerformanceAnalytics functions
#
print(elapsed_times)
Unit: milliseconds
expr min lq mean median uq max neval
CAPM.beta_roll 3007.34309 3009.92618 3016.57905 3012.50928 3021.19703 3029.88477 3
BetaCoVar_roll 3453.83531 3471.70954 3478.91433 3489.58377 3491.45383 3493.32390 3
CovVar_roll 69.19571 69.57012 69.83189 69.94453 70.14999 70.35544 3
CovVar1_roll 38.72437 39.17021 39.33052 39.61605 39.63359 39.65113 3
CovVar2_roll 60.75020 61.08255 61.36130 61.41490 61.66684 61.91878 3