This is a document to help those investors and people who are interested in stock market by using quantmod package in R. Quantmod basically is designed to assist the quantitative trader to quickly and cleanly explore and build trading model. Also, you could get more details in its official website – Quantitative Financial Modelling & Trading Framework for R and it provides a pdf file for its package introduction – Package ‘quantmod’.

This vignette will be divided into three parts:

  1. The installation of package
  2. How to get financial data
  3. A small example used to find out correlation among companies

1. Install the package

# install.packages("quantmod")
library(quantmod)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## Version 0.4-0 included new data defaults. See ?getSymbols.

2. Get financial data

2.1 Query Microsoft’s stock trading data (refereces: Yahoo! Finance)

args(getSymbols)
## function (Symbols = NULL, env = parent.frame(), reload.Symbols = FALSE, 
##     verbose = FALSE, warnings = TRUE, src = "yahoo", symbol.lookup = TRUE, 
##     auto.assign = getOption("getSymbols.auto.assign", TRUE), 
##     ...) 
## NULL
getSymbols("MSFT",src='yahoo')
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
## 
## This message is shown once per session and may be disabled by setting 
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
## [1] "MSFT"

2.2 Get the latest three-day transaction data

tail(MSFT,3)
##            MSFT.Open MSFT.High MSFT.Low MSFT.Close MSFT.Volume MSFT.Adjusted
## 2020-08-12    205.29    210.28   204.75     209.19    28041400        209.19
## 2020-08-13    209.44    211.35   208.15     208.70    22588900        208.70
## 2020-08-14    208.76    209.59   207.51     208.90    17950400        208.90

2.3 Get Microsoft’s dividend data (only three lines of data are displayed)

args(getSymbols)
## function (Symbols = NULL, env = parent.frame(), reload.Symbols = FALSE, 
##     verbose = FALSE, warnings = TRUE, src = "yahoo", symbol.lookup = TRUE, 
##     auto.assign = getOption("getSymbols.auto.assign", TRUE), 
##     ...) 
## NULL
tail(getDividends("MSFT"), 3)
##            MSFT.div
## 2019-11-20     0.51
## 2020-02-19     0.51
## 2020-05-20     0.51

2.4 Adjust stock prices based on dividends
adjustOHLC( ) function is used to calculate the adjusted OHLC (Open, High, Low and Close) prices for split and dividend. Here, it is used to adjust ex-dividend of Microsoft’s stock data.

getSymbols("MSFT", from="2020-01-01", src="yahoo")
## [1] "MSFT"
tail(MSFT.a <- adjustOHLC(MSFT),3)
##            MSFT.Open MSFT.High MSFT.Low MSFT.Close MSFT.Volume MSFT.Adjusted
## 2020-08-12    205.29    210.28   204.75     209.19    28041400        209.19
## 2020-08-13    209.44    211.35   208.15     208.70    22588900        208.70
## 2020-08-14    208.76    209.59   207.51     208.90    17950400        208.90

2.5 Get Microsoft’s split data

args(getSymbols)
## function (Symbols = NULL, env = parent.frame(), reload.Symbols = FALSE, 
##     verbose = FALSE, warnings = TRUE, src = "yahoo", symbol.lookup = TRUE, 
##     auto.assign = getOption("getSymbols.auto.assign", TRUE), 
##     ...) 
## NULL
tail(getSplits("MSFT"),3)
##            MSFT.spl
## 1998-02-23      0.5
## 1999-03-29      0.5
## 2003-02-18      0.5

2.6 Get exchange rate data
getFX( ) function is used to download exchange rates or metals prices from oanda. Here, the function is used to get the exchange rate between Australian Dollar and Chinese Yuan Renminbi.

getFX("AUD/CNY",from='2020-06-01')
## [1] "AUD/CNY"
tail(AUDCNY,3)
##             AUD.CNY
## 2020-08-12 4.961122
## 2020-08-13 4.973139
## 2020-08-14 4.973426

2.7 Get financial statements of listed companies
Once, getFinancials() & viewFin() functions is used to download and view financial statements. However, this function is defunct, and Google Finance stopped providing data.

# getFin("AAPL")
# head(viewFin(AAPL.f),5)

Thus, I got a great replacement method to get financial statements online by using Tiingo. Package riingo is an R interface to the ‘Tinngo’ Stock Price API

# library(riingo)
# riingo_set_token(YOUR_OWN_API_TOKEN, inform = TRUE) # Toke -> Tiingo API Token
# riingo_fundamentals_statements(c("AAPL", "MSFT"))

3. Demo

This small program is to compare the stock market quotations in these four companies (i.e. Apple, Oracle. Microsoft, Google).

new.environment <- new.env()
# Get data (i.e. Apple, Oracle, Microsoft, Google) from yahoo and manage Symbols in specified environment
getSymbols(c("AAPL", "ORCL", "MSFT", "GOOG"), src = "yahoo", env = new.environment)
## [1] "AAPL" "ORCL" "MSFT" "GOOG"
# Get the information about the structure of object
str(get("AAPL", env = new.environment))
## An 'xts' object on 2007-01-03/2020-08-14 containing:
##   Data: num [1:3429, 1:6] 12.3 12 12.3 12.3 12.3 ...
##  - attr(*, "dimnames")=List of 2
##   ..$ : NULL
##   ..$ : chr [1:6] "AAPL.Open" "AAPL.High" "AAPL.Low" "AAPL.Close" ...
##   Indexed by objects of class: [Date] TZ: UTC
##   xts Attributes:  
## List of 2
##  $ src    : chr "yahoo"
##  $ updated: POSIXct[1:1], format: "2020-08-15 15:41:16"
str(get("ORCL", env = new.environment))
## An 'xts' object on 2007-01-03/2020-08-14 containing:
##   Data: num [1:3429, 1:6] 17.2 17.5 17.6 17.6 17.9 ...
##  - attr(*, "dimnames")=List of 2
##   ..$ : NULL
##   ..$ : chr [1:6] "ORCL.Open" "ORCL.High" "ORCL.Low" "ORCL.Close" ...
##   Indexed by objects of class: [Date] TZ: UTC
##   xts Attributes:  
## List of 2
##  $ src    : chr "yahoo"
##  $ updated: POSIXct[1:1], format: "2020-08-15 15:41:16"
str(get("MSFT", env = new.environment))
## An 'xts' object on 2007-01-03/2020-08-14 containing:
##   Data: num [1:3429, 1:6] 29.9 29.7 29.6 29.6 30 ...
##  - attr(*, "dimnames")=List of 2
##   ..$ : NULL
##   ..$ : chr [1:6] "MSFT.Open" "MSFT.High" "MSFT.Low" "MSFT.Close" ...
##   Indexed by objects of class: [Date] TZ: UTC
##   xts Attributes:  
## List of 2
##  $ src    : chr "yahoo"
##  $ updated: POSIXct[1:1], format: "2020-08-15 15:41:17"
str(get("GOOG", env = new.environment))
## An 'xts' object on 2007-01-03/2020-08-14 containing:
##   Data: num [1:3429, 1:6] 232 234 240 243 242 ...
##  - attr(*, "dimnames")=List of 2
##   ..$ : NULL
##   ..$ : chr [1:6] "GOOG.Open" "GOOG.High" "GOOG.Low" "GOOG.Close" ...
##   Indexed by objects of class: [Date] TZ: UTC
##   xts Attributes:  
## List of 2
##  $ src    : chr "yahoo"
##  $ updated: POSIXct[1:1], format: "2020-08-15 15:41:17"
# Return the first 6 lines of the object/data
head(get("AAPL", env = new.environment))
##            AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
## 2007-01-03  12.32714  12.36857 11.70000   11.97143   309579900      10.34498
## 2007-01-04  12.00714  12.27857 11.97429   12.23714   211815100      10.57460
## 2007-01-05  12.25286  12.31428 12.05714   12.15000   208685400      10.49929
## 2007-01-08  12.28000  12.36143 12.18286   12.21000   199276700      10.55114
## 2007-01-09  12.35000  13.28286 12.16429   13.22429   837324600      11.42763
## 2007-01-10  13.53571  13.97143 13.35000   13.85714   738220000      11.97450
head(get("ORCL", env = new.environment))
##            ORCL.Open ORCL.High ORCL.Low ORCL.Close ORCL.Volume ORCL.Adjusted
## 2007-01-03     17.22     17.78    17.10      17.51    52241700      15.10999
## 2007-01-04     17.55     17.87    17.30      17.68    33559800      15.25669
## 2007-01-05     17.62     17.76    17.44      17.64    36154800      15.22218
## 2007-01-08     17.63     17.93    17.45      17.86    31018100      15.41202
## 2007-01-09     17.93     17.98    17.65      17.82    31417000      15.37750
## 2007-01-10     17.66     17.80    17.55      17.77    27822400      15.33436
head(get("MSFT", env = new.environment))
##            MSFT.Open MSFT.High MSFT.Low MSFT.Close MSFT.Volume MSFT.Adjusted
## 2007-01-03     29.91     30.25    29.40      29.86    76935100      22.12369
## 2007-01-04     29.70     29.97    29.44      29.81    45774500      22.08664
## 2007-01-05     29.63     29.75    29.45      29.64    44607200      21.96068
## 2007-01-08     29.65     30.10    29.53      29.93    50220200      22.17555
## 2007-01-09     30.00     30.18    29.73      29.96    44636600      22.19778
## 2007-01-10     29.80     29.89    29.43      29.66    55017400      21.97551
head(get("GOOG", env = new.environment))
##            GOOG.Open GOOG.High GOOG.Low GOOG.Close GOOG.Volume GOOG.Adjusted
## 2007-01-03  232.1299  237.4400 229.6940   232.9220    15470700      232.9220
## 2007-01-04  233.6243  241.0714 233.3005   240.7277    15834200      240.7277
## 2007-01-05  240.3491  242.8398 238.1623   242.6853    13795600      242.6853
## 2007-01-08  242.9344  244.0204 240.1997   240.8871     9544400      240.8871
## 2007-01-09  241.8186  243.2134 239.7015   241.8435    10803000      241.8435
## 2007-01-10  241.3105  245.8535 240.1200   243.8161    11981700      243.8161

3.1 Get the total trading volume of Apple’s stocks from 2020-01-01 to 2020-08-13

getSymbols("AAPL", src = "yahoo", from = "2020-01-01", to = "2020-08-13")
## [1] "AAPL"
# Verify the descriptive statistics of each price series and volume
summary(AAPL)
##      Index              AAPL.Open       AAPL.High        AAPL.Low    
##  Min.   :2020-01-02   Min.   :228.1   Min.   :228.5   Min.   :212.6  
##  1st Qu.:2020-02-27   1st Qu.:284.9   1st Qu.:290.2   1st Qu.:281.8  
##  Median :2020-04-23   Median :316.1   Median :319.2   Median :313.1  
##  Mean   :2020-04-23   Mean   :319.9   Mean   :325.0   Mean   :315.9  
##  3rd Qu.:2020-06-17   3rd Qu.:351.4   3rd Qu.:355.1   3rd Qu.:347.7  
##  Max.   :2020-08-12   Max.   :452.8   Max.   :457.6   Max.   :441.2  
##    AAPL.Close     AAPL.Volume        AAPL.Adjusted  
##  Min.   :224.4   Min.   : 19982500   Min.   :223.4  
##  1st Qu.:287.9   1st Qu.: 29268100   1st Qu.:286.6  
##  Median :316.9   Median : 36580700   Median :315.5  
##  Mean   :320.8   Mean   : 42156412   Mean   :319.7  
##  3rd Qu.:351.9   3rd Qu.: 49705400   3rd Qu.:351.3  
##  Max.   :455.6   Max.   :106721200   Max.   :454.8
# Calculate the total trading volume of stocks from 2020-01-01 to 2020-08-13
sum(Vo(AAPL))
## [1] 6534243900

3.2 Get the correlation among four companies
Find out the point when these stocks soared or plummeted. For example, price in opening or in closing rose or fell more than 2% than the last day’s price. Moreover, we could use search engine or other ways to find out the reason that caused these situation and then observe the data or use programs to analyse the data. Then, we could figure out where there is a trading rule among these and get some business opportunities.

3.2.1 View the situation where each company’s the trading volume has risen or fallen than 2%
Delt( ) is used to calculate the percent change;
CL( ) is used to get ‘CLose’ column (other columns like Op=Open, Hi=High, Lo=Low, Vo=Volume, Ad=Adjusted);
which( ) return the position of the element

# Apple
AAPL <- Delt(Cl(get("AAPL", env = new.environment)))
length(AAPL[which(AAPL > 0.02), ])
## [1] 407
plot(AAPL[which(AAPL > 0.02), ])

# Oracle
ORCL <- Delt(Cl(get("ORCL", env = new.environment)))
length(ORCL[which(ORCL > 0.02), ])
## [1] 290
plot(ORCL[which(ORCL > 0.02), ])

# Microsoft
MSFT <- Delt(Cl(get("MSFT", env = new.environment)))
length(MSFT[which(MSFT > 0.02), ])
## [1] 309
plot(MSFT[which(MSFT > 0.02), ])

# Google
GOOG <- Delt(Cl(get("GOOG", env = new.environment)))
length(GOOG[which(GOOG > 0.02), ])
## [1] 289
plot(GOOG[which(GOOG > 0.02), ])

Arrange the daily adjusted prices of four companies’ stocks in a data frame.

# 
m <- cbind(Ad(get("AAPL", env = new.environment)), Ad(get("ORCL", env = new.environment)), 
           Ad(get("MSFT", env = new.environment)), Ad(get("GOOG", env = new.environment)))

Use the coor.test( ) function to calculate the correlation coefficients and probabilities of adjusted prices among four companies’ stocks.

library(psych)
corr.test(as.data.frame(m))
## Call:corr.test(x = as.data.frame(m))
## Correlation matrix 
##               AAPL.Adjusted ORCL.Adjusted MSFT.Adjusted GOOG.Adjusted
## AAPL.Adjusted          1.00          0.91          0.97          0.95
## ORCL.Adjusted          0.91          1.00          0.86          0.94
## MSFT.Adjusted          0.97          0.86          1.00          0.94
## GOOG.Adjusted          0.95          0.94          0.94          1.00
## Sample Size 
## [1] 3429
## Probability values (Entries above the diagonal are adjusted for multiple tests.) 
##               AAPL.Adjusted ORCL.Adjusted MSFT.Adjusted GOOG.Adjusted
## AAPL.Adjusted             0             0             0             0
## ORCL.Adjusted             0             0             0             0
## MSFT.Adjusted             0             0             0             0
## GOOG.Adjusted             0             0             0             0
## 
##  To see confidence intervals of the correlations, print with the short=FALSE option

Draw the correlation coefficient graph

library(corrplot)
## corrplot 0.84 loaded
corrplot.mixed(cor(m), lower = "ellipse", upper = "circle")

It is quite easy to find that the correlation coefficient among these four are all over 80% which means there is a strong correlation among them.

Conclusion

Obviously, ‘quantmod’ is a significantly powerful and useful package in building and analysing quantitative financial trading strategies. Although this vignette only consists of some simple functions that ‘quantmod’ has, it has several common ones such as getSymbols, getDividends and etc. that we could use in stocks data analysis. If you already get interests in this package, I highly recommend you finding out more in its APIs document.

References

  1. https://www.quantmod.com/
  2. https://cran.r-project.org/web/packages/quantmod/quantmod.pdf
  3. https://blog.csdn.net/jiabiao1602/article/details/39134719?utm_source=blogxgwz1
  4. https://api.tiingo.com/