【发布时间】:2021-04-06 04:17:39
【问题描述】:
我正在尝试使用 R 中的 optim() 函数来最小化矩阵运算的值。在这种情况下,我试图最小化一组股票的波动性,这些股票的个人回报彼此共变。被最小化的目标函数是calculate_portfolio_variance。
library(quantmod)
filter_and_sort_symbols <- function(symbols)
{
# Name: filter_and_sort_symbols
# Purpose: Convert to uppercase if not
# and remove any non valid symbols
# Input: symbols = vector of stock tickers
# Output: filtered_symbols = filtered symbols
# convert symbols to uppercase
symbols <- toupper(symbols)
# Validate the symbol names
valid <- regexpr("^[A-Z]{2,4}$", symbols)
# Return only the valid ones
return(sort(symbols[valid == 1]))
}
# Create the list of stock tickers and check that they are valid symbols
tickers <- filter_and_sort_symbols(c("AAPL", "NVDA", "MLM", "AA"))
benchmark <- "SPY"
# Set the start and end dates
start_date <- "2007-01-01"
end_date <- "2019-01-01"
# Gather the stock data using quantmod library
getSymbols(Symbols=tickers, from=start_date, to=end_date, auto.assign = TRUE)
getSymbols(benchmark, from=start_date, to=end_date, auto.assign = TRUE)
# Create a matrix of only the adj. prices
price_matrix <- NULL
for(ticker in tickers){price_matrix <- cbind(price_matrix, get(ticker)[,6])}
# Set the column names for the price matrix
colnames(price_matrix) <- tickers
benchmark_price_matrix <- NULL
benchmark_price_matrix <- cbind(benchmark_price_matrix, get(benchmark)[,6])
# Compute log returns
returns_matrix <- NULL
for(ticker in tickers){returns_matrix <- cbind(returns_matrix, annualReturn(get(ticker)))}
returns_covar <- cov(returns_matrix)
colnames(returns_covar) <- tickers
rownames(returns_covar) <- tickers
# get average returns for tickers and benchmark
ticker_avg <- NULL
for(ticker in tickers){ticker_avg <- cbind(ticker_avg, colMeans(annualReturn(get(ticker))))}
colnames(ticker_avg) <- tickers
benchmark_avg <- colMeans(annualReturn(get(benchmark)))
# create the objective function
calculate_portfolio_variance <- function(allocations, returns_covar, ticker_avg, benchmark_avg)
{
# Name: calculate_portfolio_variance
# Purpose: Computes expected portfolio variance, to be used as the minimization objective function
# Input: allocations = vector of allocations to be adjusted for optimality; returns_covar = covariance matrix of stock returns
# ticker_avg = vector of average returns for all tickers, benchmark_avg = benchmark avg. return
# Output: Expected portfolio variance
# get benchmark volatility
benchmark_variance <- (sd(annualReturn(get(benchmark))))^2
# scale allocations for 100% investment
allocations <- as.matrix(allocations/sum(allocations))
# get the naive allocations
naive_allocations <- rep(c(1/ncol(ticker_avg)), times=ncol(ticker_avg))
portfolio_return <- sum(t(allocations)*ticker_avg)
portfolio_variance <- t(allocations)%*%returns_covar%*%allocations
# constraints = portfolio expected return must be greater than benchmark avg. return and
# portfolio variance must be less than benchmark variance (i.e. a better reward at less risk)
if(portfolio_return < benchmark_avg | portfolio_variance > benchmark_variance)
{
allocations <- naive_allocations
}
portfolio_variance <- t(allocations)%*%returns_covar%*%allocations
return(portfolio_variance)
}
# Specify lower and upper bounds for the allocation percentages
lower <- rep(0, ncol(returns_matrix))
upper <- rep(1, ncol(returns_matrix))
# Initialize the allocations by evenly distributing among all tickers
set.seed(1234)
allocations <- rep(1/length(tickers), times=length(tickers))
当我手动调用目标函数时,它会按预期返回一个值:
> calculate_portfolio_variance(allocations, returns_covar, ticker_avg, benchmark_avg)
[,1]
[1,] 0.1713439
但是,当我使用 optim() 函数时,它会返回错误:
> optim_result <- optim(par=allocations, fn=calculate_portfolio_variance(allocations, ticker_avg, benchmark_avg), lower=lower, upper=upper, method="L-BFGS-B")
Error in t(allocations) %*% returns_covar : non-conformable arguments
我不确定原因,但可能与optim() 递归使用allocations 变量的方式有关。我能做些什么来解决这个问题?
编辑:FWIW,其他优化策略有效(差分进化,模拟退火),但我更喜欢使用梯度下降,因为它要快得多
【问题讨论】:
-
很清楚的告诉你
t(allocations)的列数和returns_covar的行数不相等。您应该做的是检查这一点并返回一条信息性错误消息,以便此功能的任何其他用户都将从您的远见中受益。另外fn=calculate_portfolio_variance(allocations, ticker_avg, benchmark_avg)不是函数,而是调用。 -
@IRTFM 我理解错误;我在问题中详细说明手动调用的原因是因为它不会导致此错误。因此,我的主要问题是为什么在 optim 函数中递归使用分配时维度可能会发生变化。我最初使用
optim_result <- optim(par=allocations, fn=calculate_portfolio_variance, lower=lower, upper=upper, allocations=allocations, ticker_avg=ticker_avg, benchmark_avg=benchmark_avg, method="L-BFGS-B")但这会导致相同的错误而没有其他详细信息 -
错误可能相同,但错误原因不同。在第一个实例中,您将 4x1 矩阵乘以 4x1 矩阵并且 cols(1)-rows(2) 不相等;在您评论的第二个实例中,您将 4x1 矩阵乘以 NULL 对象,因为在函数参数构造中没有
returns_covar的默认值。您应该在该函数中放置一条调试行,在引发错误的行之前打印对象的尺寸。 -
您还应该对您的功能进行一些测试。目前它对于
allocations的任何值都返回完全相同的值,因此即使它没有抛出错误也没有什么可以优化的。 -
@IRTFM,啊,是的,你说得对,我忘记了
returns_covar参数。谢谢你抓住那个。但是,我认为功能不是问题。它可以使用其他非梯度方法进行优化,并且我已经在 Excel 中确认了梯度优化器的结果。
标签: r optimization r-portfolioanalytics