Given a TimeSeries, ts, how can I compute the percentage change from one period to the next? Percentage change is calculated as (x[n] - x[n-1])/x[n-1] * 100.0. I've tried experimenting with MovingMap and pure functions but without success.

I can get the percentage change as a list of values with:

pc = MovingMap[(#[[2]] - #[[1]])/#[[1]] * 100.0 &, ts["Values"], {2}]

pc can then be plotted with ListLinePlot, but I'd really like to get back a TimeSeries object that can be plotted with DateListPlot.


It matters if your TimeSeries is RegularlySampledQ or not. If it is, then you can use

f = If[PossibleZeroQ[#1], Missing["Indeterminate"], 100 (#2 - #1) / #1]&;
MovingMap[f @@ #Values &, ts, {1, Right}]

otherwise you can use

MovingMap[f @@ #Values &, ts, {Quantity[2, "Events"], Right}]

where f is defined as in the previous code block. This time though, you are calculating a percentage difference that is not commensurate along the series, as it corresponds to different time spans.

  • $\begingroup$ The TimeSeries comes from FinancialData and appears not to be RegularlySampledQ. Simplifying to: MovingMap[100 (#2 - #1) / #1 & @@ #Values &, ts, {Quantity[2, "Events"], Right}] works nicely. Thank you. $\endgroup$ – Lee Apr 9 '18 at 16:59

Not too hard:

ts = TimeSeries[FinancialData["SBUX", "2016"]];
pc = TimeSeries[100. Differences[#]/Most[#] &[ts["Values"]], {Rest[ts["Dates"]]}];

DateListPlot[{ts, pc}, PlotLegends -> {"SBUX Close", "% change"}]

time series and its percentage change

  • $\begingroup$ Thank you. The computation of pc is elegant and a nice expression of the Wolfram Language. $\endgroup$ – Lee Apr 9 '18 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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