This will be my first question in the community so I hope I can describe it in a way that it is understandable.
I have a data set with annual company returns and annual market (S&P) returns. I would like to calculate the covariance between the each company's returns and the market returns. Here is an extract from my data set:
Company_Name Data_Year Price SP_return Company_return
<chr> <dbl> <dbl> <dbl> <dbl>
1 A & M FOOD SERVICES INC 1984 3.75 0.0140 -0.659
2 A & M FOOD SERVICES INC 1985 10.1 0.263 0.993
3 A.A. IMPORTING CO INC 1984 2.75 0.0140 -0.647
.
.
.
8 AAR CORP 1981 7.62 -0.0973 -0.580
9 AAR CORP 1982 9.37 0.148 0.207
10 AAR CORP 1983 17.2 0.173 0.610
.
.
.
As you can see the same company is repeating itself for every year that we have a return for. I was trying to use the following code to then calculate the covariance between each company group and the market return:
group_by(Company_Name) %>%
mutate(Covariance = cov(df_companydata_yearly_complete$Company_return,
df_companydata_yearly_complete$SP_return))
However it doesn't return a different covariance by each company but one covariance between the whole column of Company_return and SP_return. So I only got one number that keeps repeating itself.
Company_Name Data_Year Price SP_return Company_return Covariance
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A & M FOOD SERVICES INC 1984 3.75 0.0140 -0.659 0.0257
.
.
.
9 AAR CORP 1982 9.37 0.148 0.207 0.0257
So I don't know what exactly the problem is because when I was calculating the return of each company then the group.by function worked like it should have but it doesn't work for the covariance function. Could you please help me?