计算数据框的每月回报

时间:2019-03-20 17:23:38

标签: r statistics gini

我被要求使用2000年以来的历史数据来计算18种行业ETF的基尼系数(分配权重的分散性)。以下是摘录:

> head(df)
        Date  .SXQR  .SXTR  .SXNR  .SXMR  .SXAR  .SX3R  .SX6R  .SXFR  .SXOR  .SXDR
1 2000-01-03 364.94 223.93 489.04 586.38 306.56 246.81 385.36 403.82 283.78 455.39
2 2000-01-04 345.04 218.90 474.05 566.15 301.13 239.24 374.64 390.41 275.93 434.92
3 2000-01-05 338.22 215.88 464.20 542.29 298.22 239.55 373.26 383.48 272.54 430.05
4 2000-01-06 343.13 218.18 470.82 529.33 300.69 249.75 377.26 383.48 272.47 434.15
5 2000-01-07 349.46 220.10 478.87 531.65 306.50 255.17 381.19 390.23 273.76 447.02
6 2000-01-10 356.20 223.01 484.07 581.82 310.84 252.75 387.74 393.75 278.76 453.80

如果您知道比我的尝试更简单的方法,我将很高兴听到它!

我的尝试

我知道索引 G 等于Enter the description of the image here

其中 E 是所研究的所有统计变量对的所有绝对值偏差的平均值:

enter the description of the image here

M 是平均收入:

introducir la descripción de la imagen aquí

但是,在计算portfolio_monthly_returns的平均值时, M 我遇到了这个错误:argument is not numeric or logical: returning NA

根据朋友的想法,我创建了portfolio_monthly_returns

library(quantmod)
portfolio_monthly_returns=lapply(xts(df[,-1],order.by = df$Date),monthlyReturn) # What is monthlyReturn here ?

我没有得到这段代码,看起来确实很奇怪:

enter image description here

> mean(portfolio_monthly_returns)
[1] NA
Warning message:
In mean.default(portfolio_monthly_returns) :
  argument is not numeric or logical: returning NA

数据

数据文件为here

为了获得df

library (dplyr)
library (lubridate)
   
df <- read.xlsx ("Data.xlsx", sheet = "Sector-STOXX600", startRow = 2, colNames = TRUE, detectDates = TRUE, skipEmptyRows = FALSE)
df [2:19] <- data.matrix (df [2:19])

备注

我不知道为什么它不涉及重量:

cov = cor(NewData)
# ERC algorithm
Sigma = cov
w = optimalPortfolio(Sigma = Sigma,control = list(type = 'erc', constraint = 'lo'))

w = matrix(w, 1, 18)
(Sigma %*% t(w)) * c(w)

1 个答案:

答案 0 :(得分:0)

我假设您要为Input: 6*(2+3) Result: Correct 的每一列计算 G 。在这种情况下,只要您对 E M 的方程式完全相同,应用于df每列的函数将为您提供 G 您想要的是什么以及 x k 是列的元素:

df

您可以在这里简单地在gini_calc <- function (x) { #Strip out NA elements x_no_na <- x[!is.na(x)] #This matrix calculation gives a matrix of all differences of the elements, after which E and M can be calculated mat <- matrix(rep(x_no_na, length(x_no_na)), ncol=length(x_no_na)) E <- sum(abs(mat-t(mat)))/length(x_no_na)^2 M <- mean(x_no_na) #Return G return(E/(2*M)) } 上使用lapply。假设您不想在任何计算中都包含df

我将确保此功能完全符合您的要求。我不清楚您为什么使用NA之类的东西。

相关问题