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.
Asked
Active
Viewed 355 times
9
J. M.'s missing motivation
- 124,525
- 11
- 401
- 574
RayC
- 91
- 1
1 Answers
13
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]]

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]

Or, using DateListPlot, with the model sampled at the original dates:
DateListPlot[{data, Table[{d, modelf[d]}, {d, data[[All, 1]]}]},
Joined -> {False, True}]

Brett Champion
- 20,779
- 2
- 64
- 121
Dr. belisarius
- 115,881
- 13
- 203
- 453
Show[DateListPlot[data], Plot[(* stuff *)]]myself (and theAbsoluteTime[]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... – J. M.'s missing motivation Jun 12 '12 at 01:19