hbtf.1046
hbtf.1046

Reputation: 1447

Calculation using loop in R

I just start using R for statistical analysis and I am still learning. I have an issue with creating loops in R. I have the following case and I was wondering if anyone can help me with it. For me it seems impossible but for some of you it is just a piece of cake. I have a dataset for different firms across different years. for each firm I have daily stock price data and I need to calculate the stock return for each firm for each day using the following equation= (Pt - Pt-1)/ Pt-1 where Pt is the stock price of the current day and Pt-1 is the stock price of the previous day. the dataset I have is just like the following:

Date      Firm    Price
1/1/2009   A       2    
2/1/2009   A       2.5   
3/1/2009   A       5
4/1/2009   A       4
1/1/2010   A       1.5
2/1/2010   A       1.8
3/1/2010   A       6
4/1/2010   A       7
1/1/2009   B       16    
2/1/2009   B       15   
3/1/2009   B       10
4/1/2010   B       11
1/1/2010   B       20
2/1/2010   B       13
3/1/2010   A       12
4/1/2010   A       10

the result I need is like the following

Date      Firm    Price   Return
1/1/2009   A       2      NA 
2/1/2009   A       2.5    0.25 
3/1/2009   A       5      1
4/1/2009   A       4      -0.2
1/1/2010   A       1.5    -0.625
2/1/2010   A       1.8    0.2
3/1/2010   A       6      2.33333
4/1/2010   A       7      0.166667
1/1/2009   B       16     NA 
2/1/2009   B       15     -0.0625
3/1/2009   B       10     -0.3333
4/1/2010   B       11      0.1
1/1/2010   B       20      0.81818
2/1/2010   B       13      -0.35
3/1/2010   A       12      -0.07692
4/1/2010   A       10      -166667

I hope you can help me with this issue. Thank you in advance.

Upvotes: 0

Views: 439

Answers (2)

staove7
staove7

Reputation: 580

I think this should work (I used this Calculating %changes with the By()):

# defining a function which calculates percent change

myFun <- function(x){
n <- nrow(x)
x$Change <- c(NA,diff(x$Price) / head(x$Price,n-1))
x
}

# applying it over the data frame by `Firm` type

do.call(rbind,by(df,df$Firm,FUN=myFun))

Upvotes: 0

GGamba
GGamba

Reputation: 13680

With dplyr:

library(dplyr)
df %>%
    group_by(Firm) %>%
    mutate(Return = (Price - lag(Price)) / lag(Price))

Upvotes: 2

Related Questions