QuantMod and financial data
This addition is not so much to show beautiful or clever plotting techniques, but rather to demonstrate how quick and easy it is to look at financial data in R.
I was able to retrieve the data and generate the plots below in under 10 minutes.
There is, of course, much more that can be done with financial data, so I’ll almost certainly upload a more in-depth project at a later date.
Note, for example, that the time range to be analyzed can be changed merely by modifying the ‘start’ and ‘end’ assignments in the first code chunk.
Load in Amazon stock market data with quantmod package and set period (2017)
library(quantmod)
start <- as.Date('2017-01-01')
end <- as.Date('2017-12-31')
getSymbols('AMZN', src = 'yahoo', from = start, to = end)
## [1] "AMZN"
Check out what we’ve got
class(AMZN)
## [1] "xts" "zoo"
head(AMZN)
## AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
## 2017-01-03 757.92 758.76 747.70 753.67 3521100
## 2017-01-04 758.39 759.68 754.20 757.18 2510500
## 2017-01-05 761.55 782.40 760.26 780.45 5830100
## 2017-01-06 782.36 799.44 778.48 795.99 5986200
## 2017-01-09 798.00 801.77 791.77 796.92 3440100
## 2017-01-10 796.60 798.00 789.54 795.90 2558400
## AMZN.Adjusted
## 2017-01-03 753.67
## 2017-01-04 757.18
## 2017-01-05 780.45
## 2017-01-06 795.99
## 2017-01-09 796.92
## 2017-01-10 795.90
This time just using base R, plot closing numbers for Amazon in 2017
plot(Cl(AMZN), main = 'AMZN')
Plot a candlechart of AMZN closings and trade volume
Note: in the lower chart, black candlesticks represent days on which AMZN closed higher than it opened (gains); red represents days on which AMZN.Open was higher than AMZN.Close (losses)
candleChart(AMZN, up.col = 'black', dn.col = 'red', theme = 'white')
Load in data for Netflix and Walmart
getSymbols(c('NFLX', 'WMT'), src = 'yahoo', from = start, to = end)
## [1] "NFLX" "WMT"
Bring together in one series: ‘closing’
closing <- as.xts(data.frame(AMZN = Cl(AMZN), NFLX = Cl(NFLX),
WMT = Cl(WMT)))
head(closing)
## AMZN.Close NFLX.Close WMT.Close
## 2017-01-03 753.67 127.49 68.66
## 2017-01-04 757.18 129.41 69.06
## 2017-01-05 780.45 131.81 69.21
## 2017-01-06 795.99 131.07 68.26
## 2017-01-09 796.92 130.95 68.71
## 2017-01-10 795.90 129.89 68.23
Plot the 3 series together for comparison
(taking into account the fact that in terms of absolute price, AMZN stock is many times higher than that of Netflix and Walmart)
plot(as.zoo(closing[, c('NFLX.Close', 'WMT.Close')]), screens = 1, lty = 1:2, col = c('red', 'blue'), xlab = 'Date', ylab = 'Price')
par(new = TRUE)
plot(as.zoo(closing[, 'AMZN.Close']), screens = 1, lty = 3, col = 'orange', xaxt = 'n', yaxt = 'n',
xlab = '', ylab = '')
axis(4)
mtext('Price', side = 4, line = 3)
title('Netflix, Walmart, Amazon - 2017')
legend('topleft', c('NFLX (left)', 'WMT (left)', 'AMZN (right)'), lty = 1:3, col = c('red', 'blue', 'orange'), cex = 0.5)