简体   繁体   English

在 R 中实现 Excel 求解器

[英]Implementing Excel Solver in R

I am trying to implement an Excel Solver in R.我正在尝试在 R 中实现 Excel 求解器。

I have two vectors of weights.我有两个权重向量。 Old_Weights and New_Weights. Old_Weights 和 New_Weights。 I need to find New_Weights.我需要找到 New_Weights。

Objective Function: Max ( (Returns - Cost) / Risk)目标函数:Max((回报 - 成本)/风险)

Example:例子:

Old_Weights<-c(0.5,0.5,0)
New_Weights<-c(X,Y,Z)

Returns <- New_Weights * Market_Returns
Cost<- (New_Weights - Old_Weights) * 15
Risk <- t(New_Weights) * Var(Market_Returns) * New_Weights

So basically I need a function that would change the values of X,Y,Z that maximizes the Objective Function.所以基本上我需要一个函数来改变 X、Y、Z 的值,从而最大化目标函数。

You can use The optim() function in R to compute this.您可以使用 R 中的optim()函数来计算它。

The general format for the optim() function is optim(objective, constraints, bounds = NULL, types= NULL, maximum = FALSE) optim()函数的一般格式是optim(objective, constraints, bounds = NULL, types= NULL, maximum = FALSE)

You can first write a function including your parameters, for example,您可以先编写一个包含参数的函数,例如,

> f <- function(x) 15 * (x[1]-0.5) + 7 * (x[2]-3)^2 + 30 

Setting up the constraints next接下来设置约束

> c <- c(1, 1)

Then use optim(c, f) to get the optimized solution然后使用 optim(c, f) 得到优化的解

> r <- optim(c, f)

> r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM