[英]R: Finding annualized average return in R
*你好。 我有一個作業,其中有以下問題:找到數據的平均年化回報。 我擁有的數據包括從 1981-01 到 2019-12 的月度回報。 我已經嘗試了幾個小時來找到可以幫助我找到平均年化回報的公式/代碼,但我只找到有關其他類型年化回報的信息。 大家有什么建議嗎?``
不確定您已經嘗試過什么或使用了哪個庫,請查看以下是否適合您:
> library(quantmod)
> getSymbols("AAPL", from = '2019-01-01', to = '2019-12-31')
[1] "AAPL"
> apple <- data.frame(AAPL)
> head(apple)
AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
2019-01-02 38.7225 39.7125 38.5575 39.4800 148158800 38.62910
2019-01-03 35.9950 36.4300 35.5000 35.5475 365248800 34.78135
2019-01-04 36.1325 37.1375 35.9500 37.0650 234428400 36.26614
2019-01-07 37.1750 37.2075 36.4750 36.9825 219111200 36.18543
2019-01-08 37.3900 37.9550 37.1300 37.6875 164101200 36.87523
2019-01-09 37.8225 38.6325 37.4075 38.3275 180396400 37.50143
> apple_adj <- apple['AAPL.Adjusted']
> head(apple_adj)
AAPL.Adjusted
2019-01-02 38.62910
2019-01-03 34.78135
2019-01-04 36.26614
2019-01-07 36.18543
2019-01-08 36.87523
2019-01-09 37.50143
> apple_adj$apple_daily_return <- ROC(apple_adj$AAPL.Adjusted, type = 'discrete')
> head(apple_adj)
AAPL.Adjusted apple_daily_return
2019-01-02 38.62910 NA
2019-01-03 34.78135 -0.09960740
2019-01-04 36.26614 0.04268928
2019-01-07 36.18543 -0.00222563
2019-01-08 36.87523 0.01906292
2019-01-09 37.50143 0.01698173
您可以從這里計算回報。
那這個呢? (未驗證)
library(quantmod)
library(PerformanceAnalytics)
library(data.table)
getSymbols("AAPL", from = '2010-01-01', to = '2019-12-31')
monthly <- to.monthly(AAPL, indexAt = "last", OHLC = FALSE)
monthly_returns <- Return.calculate(monthly, method = "log")
yearly_mean <- apply.yearly(monthly_returns, mean)
yearly_mean$Annu <- (yearly_mean$AAPL.Adjusted + 1)^12 - 1
年化平均回報只是每日回報的平均值,即通過簡單的 group_by year 和 summary 意味着您可以輕松獲得結果
library(quantmod)
library(tidyverse)
getSymbols("AAPL", from = '1981-01-01', to = '2019-12-31', periodicity = 'monthly')
apple <- data.frame( AAPL )
apple %>% rownames_to_column %>% mutate(Year = format(as.Date(rowname),'%Y'), monthly_returns= lag( AAPL.Adjusted)/AAPL.Adjusted - 1 ) %>% group_by(Year) %>% summarise(annual = mean(monthly_returns, na.rm=T))
# A tibble: 39 x 2
Year annual
<chr> <dbl>
1 1981 0.0383
2 1982 -0.0131
3 1983 0.0430
4 1984 -0.0104
5 1985 0.0295
6 1986 -0.0448
7 1987 -0.0403
8 1988 0.00526
9 1989 0.0164
10 1990 -0.0101
# … with 29 more rows
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.