Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# R code re: CapitalSpecator.com post on principal component analysis:
# "Portfolio Analysis in R: Part V | Risk Analysis Via Factors"
# http://www.capitalspectator.com/portfolio-analysis-in-r-part-v-risk-analysis-via-factors/#more-6777
# 29 Dec 2015
# By James Picerno
# http://www.capitalspectator.com/
# (c) 2015 by Beta Publishing LLC
# load packages
library(xts)
library(timeSeries)
library(tseries)
library(TTR)
library(quantmod)
library(PerformanceAnalytics)
library(FactoMineR)
# download prices
symbols <-c("SPY","IJS","EFA","EEM","IEF","LQD","VWEHX","RPIBX","PREMX","QRAAX","VGSIX")
getSymbols(symbols, src='yahoo', from='2000-12-31')
prices <- list()
for(i in 1:length(symbols)) {
prices[[i]] <- Ad(get(symbols[i]))
}
prices <- do.call(cbind, prices)
colnames(prices) <-c(symbols)
# generate daily returns
returns <-na.omit(ROC(prices,1,"discrete"))
# run factor analysis
ret.fa <-factanal(returns, factors=5)
# generate PCA data
returns.pc <-prcomp(returns)
# generate PCA analysis for correlation data
returns.pc.1 = PCA(returns,graph=FALSE)
returns.pc.1.cor <-returns.pc.1$var$coord
# plot variances of PCA results
plot(prcomp(returns),main="Principal Components: Variances")
# END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.