Using R to Calculate Multiple Stock Correlations¶
Download Asset
Download the Jupyter Notebook
IPYNB — Jupyter Notebook
Download File
Download Asset
Download the Jupyter Notebook
IPYNB — Jupyter NotebookIn [2]:
#1. install quantmod if needed
# install.packages('quantmod')
In [3]:
#2. load quantmod
library('quantmod')
In [4]:
#3. get some data (you may get a warning here about the hyperparameter auto.assign)
amzn = getSymbols('AMZN', src='google', from='2016-06-15', auto.assign=FALSE)
In [5]:
#4. quick exploration of quantmod charting capabilities
chartSeries(amzn, theme=chartTheme('white'), TA = 'addSMA(50)')
In [6]:
#5. get comparison data for FB, GOOG, NFLX
fb = getSymbols('FB', src='google', from='2016-06-15', auto.assign=FALSE)
goog = getSymbols('GOOG', src='google', from='2016-06-15', auto.assign=FALSE)
nflx = getSymbols('NFLX', src='google', from='2016-06-15', auto.assign=FALSE)
In [7]:
#6. take a quick look at what the data looks like
head(nflx)
In [8]:
#7. merge data we want into new object, cast as data.frame
stocks = as.data.frame(merge(fb$FB.Close, amzn$AMZN.Close,nflx$NFLX.Close, goog$GOOG.Close))
In [9]:
#8. see what we have
head(stocks)
In [10]:
#9. change column names
names(stocks) = c('FB', 'AMZN', 'NFLX', 'GOOG')
In [11]:
#10. store daily returns in new dataframe
# quantmod also has a function periodReturn(stock, period='daily, monthly, etc.') and allReturns()
stocks_returns = data.frame(diff(as.matrix(log(stocks))))
In [12]:
#11. check transformed data
head(stocks_returns)
In [13]:
#12. get correlations
cor(stocks_returns)
In [19]:
#13. plot scatter matrix, top row second col x = fb, second row first col x = amzn, etc
In [14]:
plot(stocks_returns)
In [ ]:
Advertisement