Search code examples
rmathrolling-computation

Rolling 10 year return R


I want to calculate a rolling 10-year-return from 1965-2021. That means that the result should be a table or data frame with the returns over a period of 10 years (1965-1974, 1966-1975, 1967-1976, etc.) like this:

enter image description here

To calculate the 10-year-return, divide the last available stock price from 1974 (e.g. 12/30/1975) by the first available stock price in 1965 (eg. 01/04/1965) and subtract 1.

10-year-return = (last stockprice 1974/first stock price 1965) -1

This calculation is then to be calculated automatically for the following years (1966-1975, 1967-1976, 1968 - 1977 etc.).

I do not know how to implement this in R studio.

Following is my code. The stock prices are in the column N225Adjusted.

library(quantmod)
data.N225 <- getSymbols("^N225",from="1965-01-01", to="2022-03-30", auto.assign=FALSE, src='yahoo') # funktion getSymbols wenn wir Kapitalmarkt haben wollten 
class(data.N225)
data.N225[c(1:3, nrow(data.N225)),]

data.N225<- na.omit(data.N225)
N225 <- data.N225[,6]

N225$DiskreteRendite= Delt(N225$N225.Adjusted)
N225[c(1:3,nrow(N225)),]
options(digits=5)
N225$dailyretrunsplusone <- N225$DiskreteRendite+1

N225 <- fortify.zoo(N225)
N225 <- N225[,c(1,2,4)]

The greatest problem is that I need a code that includes the date.

I hope you can help me. Thank you so much in advance!


Solution

  • I used a few packages, but you don't really need scales.

    library(quantmod)
    library(scales)
    library(tidyverse)
    library(lubridate)
    
    data <- getSymbols("^N225", from = "1965-01-01", to = "2022-03-30", auto.assign = F, src = "yahoo")
    
    df <- as_tibble(data.frame(Date = index(data), coredata(data)))
    df %>%
      na.omit() %>% 
      group_by(year = year(Date)) %>% 
      summarise(fprice = first(N225.Adjusted), lprice = last(N225.Adjusted)) %>% 
      mutate(Returns = (lprice/lag(fprice, n = 9L))-1) %>%
      na.omit() %>% 
      mutate(year_from_to = paste(year-9, year, sep = "-"), Returns = percent(Returns)) %>% 
      select(year_from_to, Returns)
    

    Giving the following output

    #> # A tibble: 49 × 2
    #>    year_from_to Returns
    #>    <chr>        <chr>  
    #>  1 1965-1974    205.07%
    #>  2 1966-1975    203.61%
    #>  3 1967-1976    246.26%
    #>  4 1968-1977    284.04%
    #>  5 1969-1978    241.96%
    #>  6 1970-1979    173.40%
    #>  7 1971-1980    255.03%
    #>  8 1972-1981    183.22%
    #>  9 1973-1982    53.20% 
    #> 10 1974-1983    132.29%
    #> # … with 39 more rows
    

    As required.