Created
January 2, 2018 19:57
-
-
Save anonymous/af93f187a2a4ffc287011e00c7f133ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Get a list of the FTSE-100 companies | |
# e.g. by scraping a suitable web page | |
require(XML) | |
require(RCurl) | |
pagescrape = readHTMLTable(getURL('https://en.wikipedia.org/wiki/FTSE_100_Index')) | |
n.rows = unlist(lapply(pagescrape,function(tab)if(!is.null(dim(tab)[1]))dim(tab)[1] else 0)) | |
stocktable = pagescrape[[which.max(n.rows)]] # grab biggest table on the page | |
stocktable$Ticker = sub('^(.*)\\.(.+)$','\\1-\\2',stocktable$Ticker) # cope with BT.A | |
ftse100 = sub('^(.*?)\\.?$','\\1.L',stocktable$Ticker) # add .L to all stock names | |
# Now grab the historical data for the ftse100 stocks | |
require(quantmod) | |
getSymbols(ftse100,auto.assign=TRUE,src='yahoo',env=.GlobalEnv,from='2015-01-01') # get historical stock data from yahoo | |
# Build the list of daily returns | |
require(TTR) | |
roclist = do.call(cbind,lapply(ftse100,function(x){ROC(Cl(get(x)))})) | |
names(roclist) = ftse100 | |
roclist = tail(roclist, 256) # only keep last 256 days of data | |
# | |
# Some tidying up due to problems with Yahoo's data feed. | |
# It's a bit frightening how many stocks have missing data | |
# | |
roclist = roclist[, colSums(is.na(roclist)) < nrow(roclist)*0.1] # remove stocks with insufficient data | |
roclist = na.omit(roclist) # remove any days with missing data | |
# NB: The following arrays are daily means and variances | |
mean.return = colMeans(roclist,na.rm=T) | |
covariance.matrix = cov(roclist,use="pairwise.complete.obs") | |
View(mean.return) | |
View(covariance.matrix) | |
# create a portfolio by specifying the weight for each stock | |
# sum(portfolio) should be 1 | |
# The example here would be an equal-weighted portfolio of every ftse100 stock | |
portfolio = rep(1/ncol(roclist),ncol(roclist)) | |
names(portfolio) = names(roclist) | |
# | |
# Approximate yearly return and volatility of the portfolio, assuming 225 working days in year | |
# | |
return.of.portfolio = as.numeric(t(portfolio) %*% mean.return) * 225 | |
volatility.of.portfolio = sqrt(as.numeric(t(portfolio) %*% cov(roclist) %*% portfolio)) * sqrt(225) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment