Principal Component Analysis – R Code

This is an implementation of the principal component analysis (“PCA”) method on stock prices log returns in R.

# Principal Component Analysis

# clear environment and console
rm(list = ls())
cat("\014")

# install and load required packages
# install.packages("stats")
library("stats")

data(EuStockMarkets)

# calculate log returns
log_prices <- log(EuStockMarkets[, 1:4])
ret = data.frame(diff(as.matrix(log_prices,lag=1,difference=1)))

# implement PCA on log returns of index levels
pca <- princomp(ret)

# plot method & print summary
plot(prcomp(ret))
biplot(prcomp(ret, scale = TRUE))
summary(prcomp(ret, scale = TRUE))

# view the scores for each date and the loadings for the components
pca$scores
pca$loadings

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s