【发布时间】:2021-01-01 21:14:31
【问题描述】:
我正在将投资组合优化作为线性规划问题进行。我有 500 只股票,我希望 - 有一组约束 - 最大化我的决策变量。
从下面的代码中,我得到了一个投资组合建议。但我还需要一个限制条件:投资组合至少可以有 20 种不同的股票。如何引入该约束?
我已经稍微更新了代码.. 但我无法让它工作...从下面的代码中,我希望得到 7 只股票的投资组合.. 代码背后的想法是下面的答案
df_temp <-temp <- data.frame(stock_number= seq(1:50), OPT= runif(50),
ctrl=1, alt=0)
df_temp_1 <- data.frame(stock_number= paste("a",seq(1:50)), OPT= 0,
ctrl=0, alt=1)
df_temp <- rbind(df_temp, df_temp_1)
require(lpSolveAPI)
example <- make.lp(1,NROW(df_temp))
row.add.mode(example,"on")
add.constraint(example,xt=df_temp$ctrl ,type="=",rhs=1,indices=c(1: nrow(df_temp)))
add.constraint(example,xt=df_temp$alt ,type="=",rhs=7,indices=c(1: nrow(df_temp)))
for (i in 1:50)
{
add.constraint(example,df_temp$ctrl[i] ,type="<=",rhs=0.2,indices=c(i))
add.constraint(example,df_temp$alt[i+50]*999 - df_temp$ctrl[i],type=">=",rhs=0,indices=c(i))
add.constraint(example,df_temp$alt[i+50]-df_temp$ctrl[i] ,type="<=",rhs=0,indices=c(i))
}
row.add.mode(example,"off")
set.type(example,c(1:50), "real" )
set.type(example,c(51:100), "binary" )
lp.control(example, sense="max")
set.objfn(example,obj=df_temp$OPT )
solve(example)
df_temp$PFW <- get.variables(example)
df_temp
【问题讨论】:
-
CVXR 可能是一种更容易表达投资组合模型的工具。它在更高层次上工作,因此您可以更自然地表达事物。此外,它还允许您形成二次模型(通常用于对风险进行建模)。
标签: r linear-programming