Apart from loading data from external and local sources,Ā QuantmodĀ is also suitable for making beautiful charts. There are three types of charts: lines, bars and candlestick. We will learn how to create these charts to show historical data for SPY index.Ā In Quantmod, the function to create charts is calledĀ chartSeries. With theĀ typeĀ parameter we can change the chart type.
1# Use the chartSeries() function to create charts. With the type parameter we can change the chart type.23chartSeries(SPY,type="line")4
We can also subset the graph for a certain period using theĀ subsetĀ parameter. The following command produces a candlestick chart only for the 2019 data.
TheĀ QuantmodĀ package provides built in technical indicators that can be included in the charts. We will now see how to calculate technical indicators with Quantmod for the SPY index and finally, create an R dataframe with the close prices and the technical indicators as columns.
1#### Calculates Indicators: EMA,RSI, ADX, STOCHASTIC, ATR23EMA <-round(EMA(Cl(SPY),n=14),3)4RSI <-round(RSI(Cl(SPY),n=14),3)5ADX <-round(ADX(HLC(SPY),n=14),3)6ATR <-round(ATR(HLC(SPY),n=14),3)7STOCH <-round(stoch(HLC(SPY)),3)*10089# At this point it will be a good idea to explore these objects and view the data contained.10# You can use commands such as dim(), head(), and tail() to do this.1112# Combine the required indicators into a single data table.1314spyIndicators <- data.frame(cbind(Cl(SPY),RSI,ADX$ADX,ATR$atr,STOCH$fastK,STOCH$fastD))1516# Add custom column names for each column1718colnames(spyIndicators)<- c('SPY','RSI','ADX','ATR','KLine','DLine')1920# View last 15 rows of the data to get a feel of the data21tail(spyIndicators,15)# shows the last 15 rows of the data2223 SPY RSI ADX ATR KLine DLine
242019-05-15285.0644.15126.2213.61734.221.1252019-05-16287.7049.85824.5893.65551.736.3262019-05-17285.8446.27022.8503.64239.341.7272019-05-20283.9542.89321.8633.58526.839.3282019-05-21286.5148.38820.5883.54245.737.3292019-05-22285.6346.72419.5583.40239.637.3302019-05-23282.1440.73919.9173.52116.533.9312019-05-24282.7842.20119.8573.42026.227.4322019-05-28280.1538.04720.2983.4632.315.0332019-05-29278.2735.36721.4443.46112.513.7342019-05-30279.0337.29022.2253.37318.611.1352019-05-31275.2732.18723.4603.4030.210.4362019-06-03274.5731.32824.9813.4079.29.3372019-06-04280.5344.83424.8213.60046.218.5382019-06-05282.9649.22023.9373.53461.238.939
Add Indicators to ChartsĀ
In order to add technical indicators in a chart,Ā QuantmodĀ provides theĀ add{IndicatorName)()Ā function. We will use this function for plotting the RSI and the MACD of SPY prices. Both indicators are plotted with the default parameters which are specified below:
1### Charting with Technical Indicators 23chartSeries(SPY,type="line")4addRSI(n=14,maType="EMA")5addMACD(fast=12,slow=26,signal=9,type='EMA',histogram = TRUE)6
Unlock Premium Content
Upgrade your account to access the full article, downloads, and exercises.