rtidyversequantmodtidyquant

Is there a function similar to "periodReturn" in quantmod, that calculates plain differences?


I need to calculate differences of a time series (e.g. prices) for various periodicities (daily/weekly/monthly). In quantmod (and e.g. the tq_transmute wrapper in tidyquant) I can do something similar for arithmetic and logarithmic returns (using the function "periodReturn"). The nice effect here is that I get daily/monthly/weekly rows automatically. Is there a function that does something similar for pure differences?

I tried to search the documentation and did not find a suitable function.


Solution

  • Getting differences can be done by using the endpoints function from the xts library. Assuming you created an AAPL object using the getSymbols function:

    getSymbols('AAPL',from='2019-01-01', to = '2019-05-31’)
    

    Monthly differences:

    monthlyDif <- AAPL$AAPL.Adjusted -  lag(AAPL[endpoints(AAPL, on = 'months'),"AAPL.Adjusted"])
    
    monthlyDif
               AAPL.Adjusted
    2019-01-31            NA
    2019-02-28      7.392303
    2019-03-29     16.735565
    2019-04-30     10.678879
    2019-05-30    -21.600189
    

    Be aware that by using a combination of the on argument and the k argument you can also get differences from milliseconds to years or multiples like 2-week differences etc.

    i.e. to get 2-week differences:

        twoWeeksDif <- AAPL$AAPL.Adjusted -  lag(AAPL[endpoints(AAPL, on = 'weeks',k = 2),"AAPL.Adjusted"])
    
    twoWeeksDif
               AAPL.Adjusted
    2019-01-04            NA
    2019-01-18      8.490769
    2019-02-01      9.621521
    2019-02-15      4.593429
    2019-03-01      4.532547
    2019-03-15     11.107224
    2019-03-29      3.815307
    2019-04-12      8.885773
    2019-04-26      5.409180
    2019-05-10     -6.336273
    2019-05-24    -18.209992
    2019-05-30     -0.669998