Reputation: 495
I am trying to implement an Excel Solver in R.
I have two vectors of weights. Old_Weights and New_Weights. I need to find New_Weights.
Objective Function: Max ( (Returns - Cost) / Risk)
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.
Upvotes: 1
Views: 955
Reputation: 297
You can use The optim()
function in R to compute this.
The general format for the optim()
function is 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
> r <- optim(c, f)
> r
Upvotes: 2