1. Using the tools directly

There are some available package tools allow us to manage investment portfolio.

options(digits=4, scipen=100)
rm(list=ls(all=T))
Sys.setlocale('LC_ALL', 'C')
## [1] "C"
library(fPortfolio)
## Warning: package 'fPortfolio' was built under R version 4.0.5
## Warning: package 'timeDate' was built under R version 4.0.5
## Warning: package 'timeSeries' was built under R version 4.0.5
## Warning: package 'fBasics' was built under R version 4.0.5
## Warning: package 'fAssets' was built under R version 4.0.5
library(tseries)
## Warning: package 'tseries' was built under R version 4.0.5
library(quantmod)
library(modopt.matlab)
## Warning: package 'modopt.matlab' was built under R version 4.0.5
## Warning: package 'ROI.plugin.glpk' was built under R version 4.0.5

Select a group of stocks and set the observation period

DJ10 = c('MMM',  'AXP',  'AAPL', 'BA',  'CAT', 'CVX',
         'CSCO', 'KO',   'XOM', 'GE')
K = length(DJ10)
dd = as.Date(c('2015-10-01','2017-09-30'))

Download the historical stock prices and calculate the rate of return

mx =  sapply(DJ10, function(x) {
  G = getSymbols(x,from=dd[1],to=dd[2],auto.assign=F)
  as.numeric(Delt(G[,6])) })[-1,]
names(mx) = DJ10