Search code examples
roptimizationmodeling

R fit function returning only starting number


I am automating my trading in R. I am trying to use the nls and fit function to optimise my formula, however only get returned the initial starting parameter which I enter. Instead of using trial and error I am trying to find a way to use a function to be returned the optimal value for my strategy.

I have tried entering various values for the variables "a" and "b" however only get returned the starting values I enter and no optimisation is taking place. I am not sure if I am using the wrong function or if there is a more appropriate one I should be using. The code below shows what I have tried, the variable values (given by the model, not the ones I am trying to optimise have been generated randomly as I do not know how to get the market data uploaded into this question post.

# VARIABLES         
x <- 1:1000 # number instead of date 
y <- round((runif(1000, min=0, max=50)), digits=2) # highest price of the day minus the opening price of the day
z <- round((runif(1000, min=0.001, max=0.040)), digits=6) # implied volatility for the day 
w <- sample(2000:2800, 1000, replace=TRUE) # opening price for the day 

# FORMULA
# OPEN PRICE OF THE DAY - MULTIPLIED - BY IMPLIED VOLATILITY FOR THE DAY = (APPROXIMATLY) HIGHEST PRICE OF THE DAY - MINUS - OPEN PRICE FOR THE DAY 
( w * (1 + z)) - w = y 

# OPTMISED FORMULA FORMAT 
(( w * ((1 + z) * a)) * b) - w = y # ATTEMPTING TO OPTMISE MY FORMULA TO IMPROVE THE ACCURACY OF RESULT FOR EXPECTED HIGH (y)
# TRYING WITH STARTING VALUES 
a <- 0.000001
b <- 0.000001

# USING nls function and fit 
m<-nls( y~ (( w * ((1 + z) * a)) - w)) + b 
# OR
m<-nls( y~(( w * ((1 + z) * a)) * b)) - w

I am trying to get the values of the variables "a" and "b" which best suit either version of my formulas, so that the expected high approximates the realised high better. Thanks in advance for any help you guys might be able to offer.


Solution

  • It is difficult to understand your function to be optimized. Try something like this

    m<-nls( y~ w * (1 + z) * a  - b* w,start=list(a=a,b=b))
    m
    
    > m
    Nonlinear regression model
      model: y ~ w * (1 + z) * a - b * w
       data: parent.frame()
             a          b 
     0.0089771 -0.0008416 
     residual sum-of-squares: 221244
    
    Number of iterations to convergence: 1 
    Achieved convergence tolerance: 1.944e-07
    
    >  coef(m)
                a             b 
     0.0089771178 -0.0008416359