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.
$\begingroup$
$\endgroup$
0
Add a comment
|
1 Answer
$\begingroup$
$\endgroup$
3
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}]
-
$\begingroup$ Wow! That's perfect! Thank you very much for the help. $\endgroup$– RayCCommented Jun 11, 2012 at 21:20
-
$\begingroup$ I was thinking of using
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... $\endgroup$ Commented Jun 12, 2012 at 1:19 -