This will then calculate the daily returns of AAPL and GOOG over the time period. The first day, as there is nothing to divide it by, will be NA. It generally makes sense to use this code instead to diverge from that problem.
1stockReturns <- Return.calculate(adjustedPrices)[-1]
2head(stockReturns)
3## AAPL.Adjusted GOOG.Adjusted
4## 2017-01-04 -0.001119178 0.0009667604
5## 2017-01-05 0.005085153 0.0090481583
6## 2017-01-06 0.011148442 0.0152766979
7## 2017-01-09 0.009159465 0.0006202319
8## 2017-01-10 0.001008411 -0.0023058897
9## 2017-01-11 0.005373393 0.0038767816
10
If one wants to calculate the returns of a portfolio, one can use the Return.portfolio
function with the returns of the stocks as one argument and the weights of the stocks as another. For this example, it will be an equal weight between AAPL and GOOG.
1portReturns <- Return.portfolio(stockReturns, c(0.5, 0.5))
2head(portReturns)
3## portfolio.returns
4## 2017-01-04 -7.620906e-05
5## 2017-01-05 7.068722e-03
6## 2017-01-06 1.321878e-02
7## 2017-01-09 4.868296e-03
8## 2017-01-10 -6.500634e-04
9## 2017-01-11 4.625730e-03
10
This does not rebalance the portfolio. To do this, just add the rebalance_on
argument. In this case, it is going to be done monthly.
1portReturnsRebalanced <- Return.portfolio(stockReturns, c(0.5, 0.5), rebalance_on = "months")
2head(portReturnsRebalanced)
3## portfolio.returns
4## 2017-01-04 -7.620906e-05
5## 2017-01-05 7.068722e-03
6## 2017-01-06 1.321878e-02
7## 2017-01-09 4.868296e-03
8## 2017-01-10 -6.500634e-04
9## 2017-01-11 4.625730e-03
10
You can also get an annual table of performance using the table.AnnualizedReturns
function. The arguments are an xts object of portfolio returns (can be multiple) and the risk-free rate, used to calculate the Sharpe ratio. In this example, the non-rebalanced portfolio will be compared to the monthly rebalanced portfolio.
1allPortReturns <- cbind(portReturns, portReturnsRebalanced)
2colnames(allPortReturns) <- c("Non-Rebalanced", "Monthly Rebalanced")
3table.AnnualizedReturns(allPortReturns, Rf = 0.1/252)
4## Non-Rebalanced Monthly Rebalanced
5## Annualized Return 0.1647 0.1769
6## Annualized Std Dev 0.2114 0.2104
7## Annualized Sharpe (Rf=10%) 0.2549 0.3085
8