Lim Yang Sheng
Lim Yang Sheng

Reputation: 11

Is there a way I can fix my data/code to fit this NonLinearModelFit?

When I tried to run this code:

Data1 = FinancialData["^DJI", {{2003, 10, 21}, {2007, 10, 09}}];
Data2 = {{{{AbsoluteTime[#1] - AbsoluteTime[{2003, 10, 21}]}/
    86400}, #2} & @@@ Data1};
Data3 = Data2 //. {x_List} :> x;
Data4 = Data3 //. {x_List} :> x;
Data5 = Data4 //. {x_List} :> x;
Data6 = ArrayReshape[Data5 = Data4 //. {x_List} :> x, {1000, 2}];
NonlinearModelFit[Data6, {10^(a + b u^z + 
 c u^z Cos[\[Phi] + \[Omega] Log10[u]]), {b < 0, -1 < c < 1, 0.1` <= z <= 
0.9`, 4.8` <= \[Omega] <= 13,0 <= \[Phi] <= 2 \[Pi]}}, {a, b, c, z, \ 
[Omega], \[Phi]}, u]

I get these following error messages:

The gradient is not a vector of real numbers at {a,b,c,z,[Omega],[Phi]} = {1.,-1.,0.8,0.82,5.62,0.628319}. Evaluation of the gradient of function Experimental`NumericalFunction[<<1>>] failed at {1.,-1.,0.8,0.82,5.62,0.628319}.

What is causing this?

Upvotes: 1

Views: 353

Answers (1)

Rohit Namjoshi
Rohit Namjoshi

Reputation: 679

First[Data6]
(* {0, 9747.64} *}

Has u = 0 and the function being fitted has Log10[u]. Shift the u values by 1.

Data7 = {First[#] + 1, Last[#]} & /@ Data6

Add a constraint on a and fit

fit = NonlinearModelFit[
  Data7, {10^(a + b u^z + c u^z Cos[\[Phi] + \[Omega] Log10[u]]), {a <
      10, b < 0, -1 < c < 1, 0.1` <= z <= 0.9`, 
    4.8` <= \[Omega] <= 13, 0 <= \[Phi] <= 2 \[Pi]}}, {a, b, c, 
   z, \[Omega], \[Phi]}, u]

Plot data and fit

Show[Plot[fit[u], {u, 1, 1450}], ListPlot[Data7]]

It is a pretty poor fit. May be able to get a better fit by altering the constraints.

enter image description here

Upvotes: 1

Related Questions