sylvestermarx
sylvestermarx

Reputation: 93

Finding weekly returns from daily returns company-wise

I have data which look something like this

co_code company_name co_stkdate dailylogreturn
1        A           01-01-2000  0.76
1        A           02-01-2000  0.75
.
.
.
1        A           31-12-2019  0.54
2        B           01-01-2000  0.98
2        B           02-01-2000  0.45

. . And so on

I want to find weekly returns which is equal to sum of daily log return for one week.

output should look something like this

 co_code company_name co_stkdate weeklyreturns
    1        A           07-01-2000  1.34
    1        A           14-01-2000  0.95
    .
    .
    .
    1        A           31-12-2019  0.54
    2        B           07-01-2000  0.98
    2        B           14-01-2000  0.45

I tried to apply functions in quantmod package but those functions are applicable to only xts objects. Another issue in xts objects is that function "group_by()" can't be used. Thus, I want to work in usual dataframe only.

Code look something like this

library(dplyr)
### Reading txt file
df <- read.csv("33339_1_120_20190405_165913_dat.csv")

Calculating daily log returns

df <- mutate(df, "dailylogrtn"=log(nse_returns)) %>% as.data.frame()

Formatting date

df$co_stkdate<- as.Date(as.character(df$co_stkdate), format="%d-%m-%Y")

Upvotes: 3

Views: 634

Answers (2)

Humpelstielzchen
Humpelstielzchen

Reputation: 6441

Since we don't know how many days of every week you got a dailylogreturn, there might be NAs, I recommend grouping by week and year:

#sample data
df <-   data.frame(co_stkdate = rep(seq.Date(from = as.Date("2000-01-07"), to = as.Date("2000-02-07"), by = 1), 2),
                   dailylogreturn = abs(round(rnorm(64, 1, 1), 2)),
                   company_name = rep(c("A", "B"), each = 32))


df %>%
  mutate(co_stkdate = as.POSIXct(co_stkdate),
         year = strftime(co_stkdate, "%W"),
         week = strftime(co_stkdate, "%Y")) %>%
  group_by(company_name, year, week) %>%
  summarise(weeklyreturns = sum(dailylogreturn, na.rm = TRUE))

# A tibble: 12 x 4
# Groups:   company_name, year [12]
   company_name year  week  weeklyreturns
   <fct>        <chr> <chr>         <dbl>
 1 A            01    2000           6.31
 2 A            02    2000           6.11
 3 A            03    2000           6.02
 4 A            04    2000           8.27
 5 A            05    2000           4.92
 6 A            06    2000           0.5 
 7 B            01    2000           1.82
 8 B            02    2000           6.6 
 9 B            03    2000           7.55
10 B            04    2000           7.63
11 B            05    2000           7.54
12 B            06    2000           1.03


Upvotes: 1

LeMarque
LeMarque

Reputation: 783

Since I don't have sample data, I assume this should work:

df %>%
   group_by(group = ceiling((1:nrow(df)/ 7))) %>%
   summarise(mean = mean(weeklyreturns))

Upvotes: 1

Related Questions