Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Returns over Period of Time

I'm trying to get a time series of returns for holding a certain asset for a specific time.

My dataframe looks like this:

Date          Price
1998-01-01     20
1998-01-02     22
1998-01-03     21
1998-01-04     25
...
1998-01-20     25
1998-01-21     19
1998-01-21     20
....
1998-02-01     30
1998-02-02     28
1998-02-03     25
1998-02-04     26
etc.

I have 1 observation for each day and my time series goes from 1998-1999.

What I would like to do now is calculate a return for holding my asset for 20 days (i.e. buying it at the first day and selling it at day 20), and do this for each day. So I would like to calculate this:

1.day: Return(20days) = log (Price(t=20) / Price (t=0)),

2.day: Return(20days) = log (Price(t=21) / Price (t=1)),

3.day: Return(20days) = log (Price(t=22) / Price (t=2))

etc., i.e. do this for every day in my sample.

So, my resulting dataframe would look like this:

Date          Return
1998-01-01     0.2
1998-01-02     0.4
1998-01-03     0.6
1998-01-04     0.1
...
1998-01-20     0.1
1998-01-21     0.2
1998-01-21     0.5
....
1998-02-01     0.1
1998-02-02     0.2
1998-02-03     0.5
1998-02-04     0.01
etc.

Is there a way in R to say: take the first 20 observations, calculate the return. Take observation 2-21, calculate the return. Take observation 3-22, calculate the return etc.?

I'm totally stuck and would appreciate some help. Thanks! Dani

like image 763
Dani Avatar asked Dec 17 '10 16:12

Dani


1 Answers

You can use the ROC function in the TTR package, or you can just create your own function.

> library(quantmod)  # loads TTR
> getSymbols("SPY")
> tail(ROC(Cl(SPY),20))
            SPY.Close
2010-12-09 0.01350383
2010-12-10 0.02307920
2010-12-13 0.03563051
2010-12-14 0.03792853
2010-12-15 0.04904805
2010-12-16 0.05432540
> tail(log(Cl(SPY)/lag(Cl(SPY),20)))
            SPY.Close
2010-12-09 0.01350383
2010-12-10 0.02307920
2010-12-13 0.03563051
2010-12-14 0.03792853
2010-12-15 0.04904805
2010-12-16 0.05432540
like image 129
Joshua Ulrich Avatar answered Oct 16 '22 05:10

Joshua Ulrich