Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
1  
Welcome to the site! –  belisarius Jun 11 '12 at 21:59
add comment

1 Answer 1

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

share|improve this answer
    
Wow! That's perfect! Thank you very much for the help. –  RayC Jun 11 '12 at 21:20
    
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... –  J. M. Jun 12 '12 at 1:19
    
@Brett Nice edit. Thanks! –  belisarius Jun 12 '12 at 3:19
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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