9
$\begingroup$

I'm trying to run a regression using Fit on the output of FinancialData["SPY", "Jan. 1, 2011"]. However, the dates returned from FinancialData are not in a format that is recognized by Fit. The function returns dates in the format {y,m,d}, and I need the dates to be expressed in decimal form. I'm relatively new to Mathematica, but I've got to believe there's an easy way to transform the list provided by FinancialData into one that has the format of {<date in decimal>, price}. Any guidance would be most appreciated.

$\endgroup$
0

1 Answer 1

13
$\begingroup$
data = FinancialData["SPY", "Jan. 1, 2011"] /. {d_List, v_} :> {AbsoluteTime@d, v};
model = a x^4 + b x^3 + c x^2 + d  x + e;
fit = FindFit[data, model, {a, b, c, d, e}, x]
modelf = Function[{x}, Evaluate[model /. fit]]
Plot[modelf[x], {x, Min@data[[All, 1]], Max@data[[All, 1]]}, Epilog -> Map[Point, data]]

enter image description here

Edit

Better (tick labels showing dates)

data = FinancialData["SPY", "Jan. 1, 2011"] /. {d_List, v_} :> {AbsoluteTime@d, v};
model = a x^4 + b x^3 + c x^2 + d  x + e;
fit = FindFit[data, model, {a, b, c, d, e}, x]
modelf = Function[{x}, Evaluate[model /. fit]]

p = Plot[modelf[x], {x, Min@data[[All, 1]], Max@data[[All, 1]]}, 
       Epilog -> Map[Point, data]];
s = AbsoluteOptions[p, Ticks] /. {o_ -> s_List} :> s;
s1 = s /. {v__, w__} :> {(MapAt[
     If[# != "", 
          DateString[DateList[#], {"Month", "/", "YearShort"}], 
          Null] &, 
     #, {2}] & /@ v), w};
Show[p, Ticks -> s1]

enter image description here


Or, using DateListPlot, with the model sampled at the original dates:

DateListPlot[{data, Table[{d, modelf[d]}, {d, data[[All, 1]]}]}, 
   Joined -> {False, True}]

enter image description here

$\endgroup$
3
  • $\begingroup$ Wow! That's perfect! Thank you very much for the help. $\endgroup$
    – RayC
    Commented Jun 11, 2012 at 21:20
  • $\begingroup$ I was thinking of using Show[DateListPlot[data], Plot[(* stuff *)]] myself (and the AbsoluteTime[] transformation being done only within the fitting function) for the purpose of making the dates as tick, but this is nice. AbsoluteTime[] is a neat thing... $\endgroup$ Commented Jun 12, 2012 at 1:19
  • $\begingroup$ @Brett Nice edit. Thanks! $\endgroup$ Commented Jun 12, 2012 at 3:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.