<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/an-introduction-to-stock-market-data-analysis-with-r-part-1/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://ntguardian.wordpress.com/2017/03/27/introduction-stock-market-data-r-1/"> R – Curtis Miller's Personal Website</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><em>Around September of 2016 I wrote two articles on using Python for accessing, visualizing, and evaluating trading strategies (see <a target="_blank" rel="nofollow" href="https://ntguardian.wordpress.com/2016/09/19/introduction-stock-market-data-python-1/">part 1</a> and <a target="_blank" rel="nofollow" href="https://ntguardian.wordpress.com/2016/09/26/introduction-stock-market-data-python-2/">part 2</a>). These have been my most popular posts, up until I published my article <a target="_blank" rel="nofollow" href="https://ntguardian.wordpress.com/2017/03/13/on-programming-languages-why-my-dad-went-from-programming-to-driving-a-bus/">on learning programming languages</a> (featuring my dad’s story as a programmer), and has been translated into both Russian (which used to be on backtest.ru at a <a target="_blank" rel="nofollow" href="https://backtest.ru/blog/algotrejding-na-python/">link</a> that now appears to no longer work) and Chinese (<a target="_blank" rel="nofollow" href="https://yq.aliyun.com/articles/66878">here</a> and <a target="_blank" rel="nofollow" href="https://yq.aliyun.com/articles/66817">here</a>). R has excellent packages for analyzing stock data, so I feel there should be a “translation” of the post for using R for stock data analysis.</em></p>
<p><span></span></p>
<p><em>This post is the first in a two-part series on stock data analysis using R, based on a lecture I gave on the subject for <a target="_blank" rel="nofollow" href="http://datasciencecourse.net/2016/index.html">MATH 3900 (Data Science) at the University of Utah</a>. In these posts, I will discuss basics such as obtaining the data from Yahoo! Finance using pandas, visualizing stock data, moving averages, developing a moving-average crossover strategy, backtesting, and benchmarking. The final post will include practice problems. This first post discusses topics up to introducing moving averages.</em></p>
<p><strong>NOTE: The information in this post is of a general nature containing information and opinions from the author’s perspective. None of the content of this post should be considered financial advice. Furthermore, any code written here is provided without any form of guarantee. Individuals who choose to use it do so at their own risk.</strong></p>
<h2>Introduction</h2>
<p>Advanced mathematics and statistics have been present in finance for some time. Prior to the 1980s, banking and finance were well-known for being “boring”; investment banking was distinct from commercial banking and the primary role of the industry was handling “simple” (at least in comparison to today) financial instruments, such as loans. Deregulation under the Regan administration, coupled with an influx of mathematical talent, transformed the industry from the “boring” business of banking to what it is today, and since then, finance has joined the other sciences as a motivation for mathematical research and advancement. For example one of the biggest recent achievements of mathematics was the derivation of the <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_model">Black-Scholes formula</a>, which facilitated the pricing of stock options (a contract giving the holder the right to purchase or sell a stock at a particular price to the issuer of the option). That said, <a target="_blank" rel="nofollow" href="https://www.theguardian.com/science/2012/feb/12/black-scholes-equation-credit-crunch">bad statistical models, including the Black-Scholes formula, hold part of the blame for the 2008 financial crisis</a>.</p>
<p>In recent years, computer science has joined advanced mathematics in revolutionizing finance and <strong>trading</strong>, the practice of buying and selling of financial assets for the purpose of making a profit. In recent years, trading has become dominated by computers; algorithms are responsible for making rapid split-second trading decisions faster than humans could make (so rapidly, <a target="_blank" rel="nofollow" href="http://www.nature.com/news/physics-in-finance-trading-at-the-speed-of-light-1.16872">the speed at which light travels is a limitation when designing systems</a>). Additionally, <a target="_blank" rel="nofollow" href="http://www.ft.com/cms/s/0/9278d1b6-1e02-11e6-b286-cddde55ca122.html#axzz4G8daZxcl">machine learning and data mining techniques are growing in popularity</a> in the financial sector, and likely will continue to do so. In fact, a large part of algorithmic trading is <strong>high-frequency trading (HFT)</strong>. While algorithms may outperform humans, the technology is still new and playing an increasing role in a famously turbulent, high-stakes arena. HFT was responsible for phenomena such as the <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/2010_Flash_Crash">2010 flash crash</a> and a <a target="_blank" rel="nofollow" href="http://money.cnn.com/2013/04/24/investing/twitter-flash-crash/">2013 flash crash</a> prompted by a hacked <a target="_blank" rel="nofollow" href="http://money.cnn.com/2013/04/23/technology/security/ap-twitter-hacked/index.html?iid=EL">Associated Press tweet</a> about an attack on the White House.</p>
<p>My articles, however, will not be about how to crash the stock market with bad mathematical models or trading algorithms. Instead, I intend to provide you with basic tools for handling and analyzing stock market data with R. We will be using stock data as a first exposure to <strong>time series data</strong>, which is data considered dependent on the time it was observed (other examples of time series include temperature data, demand for energy on a power grid, Internet server load, and many, many others). I will also discuss moving averages, how to construct trading strategies using moving averages, how to formulate exit strategies upon entering a position, and how to evaluate a strategy with backtesting.</p>
<p><strong>DISCLAIMER: THIS IS NOT FINANCIAL ADVICE!!! Furthermore, I have ZERO experience as a trader (a lot of this knowledge comes from a one-semester course on stock trading I took at Salt Lake Community College)! This is purely introductory knowledge, not enough to make a living trading stocks. People can and do lose money trading stocks, and you do so at your own risk!</strong></p>
<h2>Getting and Visualizing Stock Data</h2>
<h3>Getting Data from Yahoo! Finance with quantmod</h3>
<p>Before we analyze stock data, we need to get it into some workable format. Stock data can be obtained from <a target="_blank" rel="nofollow" href="http://finance.yahoo.com/">Yahoo! Finance</a>, <a target="_blank" rel="nofollow" href="http://finance.google.com/">Google Finance</a>, or a number of other sources, and the <strong>quantmod</strong> package provides easy access to Yahoo! Finance and Google Finance data, along with other sources. In fact, <strong>quantmod</strong> provides a number of useful features for financial modelling, and we will be seeing those features throughout these articles. In this lecture, we will get our data from Yahoo! Finance.</p>
<pre><code># Get quantmod
if (!require(&quot;quantmod&quot;)) {
    install.packages(&quot;quantmod&quot;)
    library(quantmod)
}

start &lt;- as.Date(&quot;2016-01-01&quot;)
end &lt;- as.Date(&quot;2016-10-01&quot;)

# Let's get Apple stock data; Apple's ticker symbol is AAPL. We use the
# quantmod function getSymbols, and pass a string as a first argument to
# identify the desired ticker symbol, pass 'yahoo' to src for Yahoo!
# Finance, and from and to specify date ranges

# The default behavior for getSymbols is to load data directly into the
# global environment, with the object being named after the loaded ticker
# symbol. This feature may become deprecated in the future, but we exploit
# it now.

getSymbols(&quot;AAPL&quot;, src = &quot;yahoo&quot;, from = start, to = end)
</code></pre>
<pre>##     As of 0.4-0, 'getSymbols' uses env=parent.frame() and
##  auto.assign=TRUE by default.
## 
##  This  behavior  will be  phased out in 0.5-0  when the call  will
##  default to use auto.assign=FALSE. getOption(&quot;getSymbols.env&quot;) and 
##  getOptions(&quot;getSymbols.auto.assign&quot;) are now checked for alternate defaults
## 
##  This message is shown once per session and may be disabled by setting 
##  options(&quot;getSymbols.warning4.0&quot;=FALSE). See ?getSymbols for more details.
</pre>
<pre>## [1] &quot;AAPL&quot;
</pre>
<pre><code># What is AAPL?
class(AAPL)
</code></pre>
<pre>## [1] &quot;xts&quot; &quot;zoo&quot;
</pre>
<pre><code># Let's see the first few rows
head(AAPL)
</code></pre>
<pre>##            AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume
## 2016-01-04    102.61    105.37   102.00     105.35    67649400
## 2016-01-05    105.75    105.85   102.41     102.71    55791000
## 2016-01-06    100.56    102.37    99.87     100.70    68457400
## 2016-01-07     98.68    100.13    96.43      96.45    81094400
## 2016-01-08     98.55     99.11    96.76      96.96    70798000
## 2016-01-11     98.97     99.06    97.34      98.53    49739400
##            AAPL.Adjusted
## 2016-01-04     102.61218
## 2016-01-05     100.04079
## 2016-01-06      98.08303
## 2016-01-07      93.94347
## 2016-01-08      94.44022
## 2016-01-11      95.96942
</pre>
<p>Let’s briefly discuss this. <code>getSymbols()</code> created in the global environment an object called AAPL (named automatically after the ticker symbol of the security retrieved) that is of the <code>xts</code> class (which is also a <code>zoo</code>-class object). <code>xts</code> objects (provided in the <strong>xts</strong> package) are seen as improved versions of the <code>ts</code> object for storing time series data. They allow for time-based indexing and provide custom attributes, along with allowing multiple (presumably related) time series with the same time index to be stored in the same object. <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/xts/vignettes/xts.pdf">(Here is a vignette describing <code>xts</code> objects.)</a> The different series are the columns of the object, with the name of the associated security (here, AAPL) being prefixed to the corresponding series.</p>
<p>Yahoo! Finance provides six series with each security. <strong>Open</strong> is the price of the stock at the beginning of the trading day (it need not be the closing price of the previous trading day), <strong>high</strong> is the highest price of the stock on that trading day, <strong>low</strong> the lowest price of the stock on that trading day, and <strong>close</strong> the price of the stock at closing time. <strong>Volume</strong> indicates how many stocks were traded. <strong>Adjusted close</strong> (abreviated as “adjusted” by <code>getSymbols()</code>) is the closing price of the stock that adjusts the price of the stock for corporate actions. While stock prices are considered to be set mostly by traders, <strong>stock splits</strong> (when the company makes each extant stock worth two and halves the price) and <strong>dividends</strong> (payout of company profits per share) also affect the price of a stock and should be accounted for.</p>
<h3>Visualizing Stock Data</h3>
<p>Now that we have stock data we would like to visualize it. I first use base R plotting to visualize the series.</p>
<pre><code>plot(AAPL[, &quot;AAPL.Close&quot;], main = &quot;AAPL&quot;)
</code></pre>
<p><img src="https://ntguardian.files.wordpress.com/2017/03/unnamed-chunk-2-1.png?w=456" data-recalc-dims="1"></p>
<p>A linechart is fine, but there are at least four variables involved for each date (open, high, low, and close), and we would like to have some visual way to see all four variables that does not require plotting four separate lines. Financial data is often plotted with a <strong>Japanese candlestick plot</strong>, so named because it was first created by 18th century Japanese rice traders. Use the function <code>candleChart()</code> from <strong>quantmod</strong> to create such a chart.</p>
<pre><code>candleChart(AAPL, up.col = &quot;black&quot;, dn.col = &quot;red&quot;, theme = &quot;white&quot;)
</code></pre>
<p><img src="https://ntguardian.files.wordpress.com/2017/03/unnamed-chunk-3-1.png?w=456" data-recalc-dims="1"></p>
<p>With a candlestick chart, a black candlestick indicates a day where the closing price was higher than the open (a gain), while a red candlestick indicates a day where the open was higher than the close (a loss). The wicks indicate the high and the low, and the body the open and close (hue is used to determine which end of the body is the open and which the close). Candlestick charts are popular in finance and some strategies in <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Technical_analysis">technical analysis</a> use them to make trading decisions, depending on the shape, color, and position of the candles. I will not cover such strategies today.</p>
<p>(Notice that the volume is tracked as a bar chart on the lower pane as well, with the same colors as the corresponding candlesticks. Some traders like to see how many shares are being traded; this can be important in trading.)</p>
<p>We may wish to plot multiple financial instruments together; we may want to compare stocks, compare them to the market, or look at other securities such as <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Exchange-traded_fund">exchange-traded funds (ETFs)</a>. Later, we will also want to see how to plot a financial instrument against some indicator, like a moving average. For this you would rather use a line chart than a candlestick chart. (How would you plot multiple candlestick charts on top of one another without cluttering the chart?)</p>
<p>Below, I get stock data for some other tech companies and plot their adjusted close together.</p>
<pre><code># Let's get data for Microsoft (MSFT) and Google (GOOG) (actually, Google is
# held by a holding company called Alphabet, Inc., which is the company
# traded on the exchange and uses the ticker symbol GOOG).
getSymbols(c(&quot;MSFT&quot;, &quot;GOOG&quot;), src = &quot;yahoo&quot;, from = start, to = end)
</code></pre>
<pre>## [1] &quot;MSFT&quot; &quot;GOOG&quot;
</pre>
<pre><code># Create an xts object (xts is loaded with quantmod) that contains closing
# prices for AAPL, MSFT, and GOOG
stocks &lt;- as.xts(data.frame(AAPL = AAPL[, &quot;AAPL.Close&quot;], MSFT = MSFT[, &quot;MSFT.Close&quot;], 
    GOOG = GOOG[, &quot;GOOG.Close&quot;]))
head(stocks)
</code></pre>
<pre>##            AAPL.Close MSFT.Close GOOG.Close
## 2016-01-04     105.35      54.80     741.84
## 2016-01-05     102.71      55.05     742.58
## 2016-01-06     100.70      54.05     743.62
## 2016-01-07      96.45      52.17     726.39
## 2016-01-08      96.96      52.33     714.47
## 2016-01-11      98.53      52.30     716.03
</pre>
<pre><code># Create a plot showing all series as lines; must use as.zoo to use the zoo
# method for plot, which allows for multiple series to be plotted on same
# plot
plot(as.zoo(stocks), screens = 1, lty = 1:3, xlab = &quot;Date&quot;, ylab = &quot;Price&quot;)
legend(&quot;right&quot;, c(&quot;AAPL&quot;, &quot;MSFT&quot;, &quot;GOOG&quot;), lty = 1:3, cex = 0.5)
</code></pre>
<p><img src="https://ntguardian.files.wordpress.com/2017/03/unnamed-chunk-4-1.png?w=456" data-recalc-dims="1"></p>
<p>What’s wrong with this chart? While absolute price is important (pricey stocks are difficult to purchase, which affects not only their volatility but <em>your</em> ability to trade that stock), when trading, we are more concerned about the relative change of an asset rather than its absolute price. Google’s stocks are much more expensive than Apple’s or Microsoft’s, and this difference makes Apple’s and Microsoft’s stocks appear much less volatile than they truly are (that is, their price appears to not deviate much).</p>
<p>One solution would be to use two different scales when plotting the data; one scale will be used by Apple and Microsoft stocks, and the other by Google.</p>
<pre><code>plot(as.zoo(stocks[, c(&quot;AAPL.Close&quot;, &quot;MSFT.Close&quot;)]), screens = 1, lty = 1:2, 
    xlab = &quot;Date&quot;, ylab = &quot;Price&quot;)
par(new = TRUE)
plot(as.zoo(stocks[, &quot;GOOG.Close&quot;]), screens = 1, lty = 3, xaxt = &quot;n&quot;, yaxt = &quot;n&quot;, 
    xlab = &quot;&quot;, ylab = &quot;&quot;)
axis(4)
mtext(&quot;Price&quot;, side = 4, line = 3)
legend(&quot;topleft&quot;, c(&quot;AAPL (left)&quot;, &quot;MSFT (left)&quot;, &quot;GOOG&quot;), lty = 1:3, cex = 0.5)
</code></pre>
<p><img src="https://ntguardian.files.wordpress.com/2017/03/unnamed-chunk-5-1.png?w=456" data-recalc-dims="1"></p>
<p>Not only is this solution difficult to implement well, it is seen as a bad visualization method; it can lead to confusion and misinterpretation, and cannot be read easily.</p>
<p>A “better” solution, though, would be to plot the information we actually want: the stock’s returns. This involves transforming the data into something more useful for our purposes. There are multiple transformations we could apply.</p>
<p>One transformation would be to consider the stock’s return since the beginning of the period of interest. In other words, we plot:</p>
<p><img title="\text{return}_{t,0} = \frac{\text{price}_t}{\text{price}_0}" alt="\text{return}_{t,0} = \frac{\text{price}_t}{\text{price}_0}" class="latex" src="https://s0.wp.com/latex.php?latex=%5Ctext%7Breturn%7D_%7Bt%2C0%7D+%3D+%5Cfrac%7B%5Ctext%7Bprice%7D_t%7D%7B%5Ctext%7Bprice%7D_0%7D&bg=ffffff&%23038;fg=444444&%23038;s=0"></p>
<p>This will require transforming the data in the <code>stocks</code> object, which I do next.</p>
<pre><code># Get me my beloved pipe operator!
if (!require(&quot;magrittr&quot;)) {
    install.packages(&quot;magrittr&quot;)
    library(magrittr)
}
</code></pre>
<pre>## Loading required package: magrittr
</pre>
<pre><code>stock_return % t %>% as.xts

head(stock_return)
</code></pre>
<pre>##            AAPL.Close MSFT.Close GOOG.Close
## 2016-01-04  1.0000000  1.0000000  1.0000000
## 2016-01-05  0.9749407  1.0045620  1.0009975
## 2016-01-06  0.9558614  0.9863139  1.0023994
## 2016-01-07  0.9155197  0.9520073  0.9791734
## 2016-01-08  0.9203607  0.9549271  0.9631052
## 2016-01-11  0.9352634  0.9543796  0.9652081
</pre>
<pre><code>plot(as.zoo(stock_return), screens = 1, lty = 1:3, xlab = &quot;Date&quot;, ylab = &quot;Return&quot;)
legend(&quot;topleft&quot;, c(&quot;AAPL&quot;, &quot;MSFT&quot;, &quot;GOOG&quot;), lty = 1:3, cex = 0.5)
</code></pre>
<p><img src="https://ntguardian.files.wordpress.com/2017/03/unnamed-chunk-6-1.png?w=456" data-recalc-dims="1"></p>
<p>This is a much more useful plot. We can now see how profitable each stock was since the beginning of the period. Furthermore, we see that these stocks are highly correlated; they generally move in the same direction, a fact that was difficult to see in the other charts.</p>
<p>Alternatively, we could plot the change of each stock per day. One way to do so would be to plot the percentage increase of a stock when comparing day <img title="t" alt="t" class="latex" src="https://s0.wp.com/latex.php?latex=t&bg=ffffff&%23038;fg=444444&%23038;s=0"> to day <img title="t + 1" alt="t + 1" class="latex" src="https://s0.wp.com/latex.php?latex=t+%2B+1&bg=ffffff&%23038;fg=444444&%23038;s=0">, with the formula:</p>
<p><img title="\text{growth}_t = \frac{\text{price}_{t + 1} - \text{price}_t}{\text{price}_t}" alt="\text{growth}_t = \frac{\text{price}_{t + 1} - \text{price}_t}{\text{price}_t}" class="latex" src="https://s0.wp.com/latex.php?latex=%5Ctext%7Bgrowth%7D_t+%3D+%5Cfrac%7B%5Ctext%7Bprice%7D_%7Bt+%2B+1%7D+-+%5Ctext%7Bprice%7D_t%7D%7B%5Ctext%7Bprice%7D_t%7D&bg=ffffff&%23038;fg=444444&%23038;s=0"></p>
<p>But change could be thought of differently as:</p>
<p><img title="\text{increase}_t = \frac{\text{price}_{t} - \text{price}_{t-1}}{\text{price}_t}" alt="\text{increase}_t = \frac{\text{price}_{t} - \text{price}_{t-1}}{\text{price}_t}" class="latex" src="https://s0.wp.com/latex.php?latex=%5Ctext%7Bincrease%7D_t+%3D+%5Cfrac%7B%5Ctext%7Bprice%7D_%7Bt%7D+-+%5Ctext%7Bprice%7D_%7Bt-1%7D%7D%7B%5Ctext%7Bprice%7D_t%7D&bg=ffffff&%23038;fg=444444&%23038;s=0"></p>
<p>These formulas are not the same and can lead to differing conclusions, but there is another way to model the growth of a stock: with log differences.</p>
<p><img title="\text{change}_t = \log(\text{price}_{t}) - \log(\text{price}_{t - 1})" alt="\text{change}_t = \log(\text{price}_{t}) - \log(\text{price}_{t - 1})" class="latex" src="https://s0.wp.com/latex.php?latex=%5Ctext%7Bchange%7D_t+%3D+%5Clog%28%5Ctext%7Bprice%7D_%7Bt%7D%29+-+%5Clog%28%5Ctext%7Bprice%7D_%7Bt+-+1%7D%29&bg=ffffff&%23038;fg=444444&%23038;s=0"></p>
<p>(Here, <img title="\log" alt="\log" class="latex" src="https://s0.wp.com/latex.php?latex=%5Clog&bg=ffffff&%23038;fg=444444&%23038;s=0"> is the natural log, and our definition does not depend as strongly on whether we use <img title="\log(\text{price}_{t}) - \log(\text{price}_{t - 1})" alt="\log(\text{price}_{t}) - \log(\text{price}_{t - 1})" class="latex" src="https://s0.wp.com/latex.php?latex=%5Clog%28%5Ctext%7Bprice%7D_%7Bt%7D%29+-+%5Clog%28%5Ctext%7Bprice%7D_%7Bt+-+1%7D%29&bg=ffffff&%23038;fg=444444&%23038;s=0"> or <img title="\log(\text{price}_{t+1}) - \log(\text{price}_{t})" alt="\log(\text{price}_{t+1}) - \log(\text{price}_{t})" class="latex" src="https://s0.wp.com/latex.php?latex=%5Clog%28%5Ctext%7Bprice%7D_%7Bt%2B1%7D%29+-+%5Clog%28%5Ctext%7Bprice%7D_%7Bt%7D%29&bg=ffffff&%23038;fg=444444&%23038;s=0">.) The advantage of using log differences is that this difference can be interpreted as the percentage change in a stock but does not depend on the denominator of a fraction.</p>
<p>We can obtain and plot the log differences of the data in <code>stocks</code> as follows:</p>
<pre><code>stock_change % log %>% diff
head(stock_change)
</code></pre>
<pre>##              AAPL.Close    MSFT.Close   GOOG.Close
## 2016-01-04           NA            NA           NA
## 2016-01-05 -0.025378648  0.0045516693  0.000997009
## 2016-01-06 -0.019763704 -0.0183323194  0.001399513
## 2016-01-07 -0.043121062 -0.0354019469 -0.023443064
## 2016-01-08  0.005273804  0.0030622799 -0.016546113
## 2016-01-11  0.016062548 -0.0005735067  0.002181138
</pre>
<pre><code>plot(as.zoo(stock_change), screens = 1, lty = 1:3, xlab = &quot;Date&quot;, ylab = &quot;Log Difference&quot;)
legend(&quot;topleft&quot;, c(&quot;AAPL&quot;, &quot;MSFT&quot;, &quot;GOOG&quot;), lty = 1:3, cex = 0.5)
</code></pre>
<p><img src="https://ntguardian.files.wordpress.com/2017/03/unnamed-chunk-7-1.png?w=456" data-recalc-dims="1"></p>
<p>Which transformation do you prefer? Looking at returns since the beginning of the period make the overall trend of the securities in question much more apparent. Changes between days, though, are what more advanced methods actually consider when modelling the behavior of a stock. so they should not be ignored.</p>
<h2>Moving Averages</h2>
<p>Charts are very useful. In fact, some traders base their strategies almost entirely off charts (these are the “technicians”, since trading strategies based off finding patterns in charts is a part of the trading doctrine known as <strong>technical analysis</strong>). Let’s now consider how we can find trends in stocks.</p>
<p>A <strong><img title="q" alt="q" class="latex" src="https://s0.wp.com/latex.php?latex=q&bg=ffffff&%23038;fg=444444&%23038;s=0">-day moving average</strong> is, for a series <img title="x_t" alt="x_t" class="latex" src="https://s0.wp.com/latex.php?latex=x_t&bg=ffffff&%23038;fg=444444&%23038;s=0"> and a point in time <img title="t" alt="t" class="latex" src="https://s0.wp.com/latex.php?latex=t&bg=ffffff&%23038;fg=444444&%23038;s=0">, the average of the past <img title="q" alt="q" class="latex" src="https://s0.wp.com/latex.php?latex=q&bg=ffffff&%23038;fg=444444&%23038;s=0"> days: that is, if <img title="MA^q_t" alt="MA^q_t" class="latex" src="https://s0.wp.com/latex.php?latex=MA%5Eq_t&bg=ffffff&%23038;fg=444444&%23038;s=0"> denotes a moving average process, then:</p>
<p><img title="MA^q_t = \frac{1}{q} \sum_{i = 0}^{q-1} x_{t - i}" alt="MA^q_t = \frac{1}{q} \sum_{i = 0}^{q-1} x_{t - i}" class="latex" src="https://s0.wp.com/latex.php?latex=MA%5Eq_t+%3D+%5Cfrac%7B1%7D%7Bq%7D+%5Csum_%7Bi+%3D+0%7D%5E%7Bq-1%7D+x_%7Bt+-+i%7D&bg=ffffff&%23038;fg=444444&%23038;s=0"></p>
<p>Moving averages smooth a series and helps identify trends. The larger <img title="q" alt="q" class="latex" src="https://s0.wp.com/latex.php?latex=q&bg=ffffff&%23038;fg=444444&%23038;s=0"> is, the less responsive a moving average process is to short-term fluctuations in the series <img title="x_t" alt="x_t" class="latex" src="https://s0.wp.com/latex.php?latex=x_t&bg=ffffff&%23038;fg=444444&%23038;s=0">. The idea is that moving average processes help identify trends from “noise”. <strong>Fast</strong> moving averages have smaller <img title="q" alt="q" class="latex" src="https://s0.wp.com/latex.php?latex=q&bg=ffffff&%23038;fg=444444&%23038;s=0"> and more closely follow the stock, while <strong>slow</strong> moving averages have larger <img title="q" alt="q" class="latex" src="https://s0.wp.com/latex.php?latex=q&bg=ffffff&%23038;fg=444444&%23038;s=0">, resulting in them responding less to the fluctuations of the stock and being more stable.</p>
<p><strong>quantmod</strong> allows for easily adding moving averages to charts, via the <code>addSMA()</code> function.</p>
<pre><code>candleChart(AAPL, up.col = &quot;black&quot;, dn.col = &quot;red&quot;, theme = &quot;white&quot;)
addSMA(n = 20)
</code></pre>
<p><img src="https://ntguardian.files.wordpress.com/2017/03/unnamed-chunk-8-2.png?w=456" data-recalc-dims="1"></p>
<p>Notice how late the rolling average begins. It cannot be computed until 20 days have passed. This limitation becomes more severe for longer moving averages. Because I would like to be able to compute 200-day moving averages, I’m going to extend out how much AAPL data we have. That said, we will still largely focus on 2016.</p>
<pre><code>start = as.Date(&quot;2010-01-01&quot;)
getSymbols(c(&quot;AAPL&quot;, &quot;MSFT&quot;, &quot;GOOG&quot;), src = &quot;yahoo&quot;, from = start, to = end)
</code></pre>
<pre>## [1] &quot;AAPL&quot; &quot;MSFT&quot; &quot;GOOG&quot;
</pre>
<pre><code># The subset argument allows specifying the date range to view in the chart.
# This uses xts style subsetting. Here, I'm using the idiom
# 'YYYY-MM-DD/YYYY-MM-DD', where the date on the left-hand side of the / is
# the start date, and the date on the right-hand side is the end date. If
# either is left blank, either the earliest date or latest date in the
# series is used (as appropriate). This method can be used for any xts
# object, say, AAPL
candleChart(AAPL, up.col = &quot;black&quot;, dn.col = &quot;red&quot;, theme = &quot;white&quot;, subset = &quot;2016-01-04/&quot;)
addSMA(n = 20)
</code></pre>
<p><img src="https://ntguardian.files.wordpress.com/2017/03/unnamed-chunk-9-2.png?w=456" data-recalc-dims="1"></p>
<p>You will notice that a moving average is much smoother than the actual stock data. Additionally, it’s a stubborn indicator; a stock needs to be above or below the moving average line in order for the line to change direction. Thus, crossing a moving average signals a possible change in trend, and should draw attention.</p>
<p>Traders are usually interested in multiple moving averages, such as the 20-day, 50-day, and 200-day moving averages. It’s easy to examine multiple moving averages at once.</p>
<pre><code>candleChart(AAPL, up.col = &quot;black&quot;, dn.col = &quot;red&quot;, theme = &quot;white&quot;, subset = &quot;2016-01-04/&quot;)
addSMA(n = c(20, 50, 200))
</code></pre>
<p><img src="https://ntguardian.files.wordpress.com/2017/03/unnamed-chunk-10-2.png?w=456" data-recalc-dims="1"></p>
<p>The 20-day moving average is the most sensitive to local changes, and the 200-day moving average the least. Here, the 200-day moving average indicates an overall <strong>bearish</strong> trend: the stock is trending downward over time. The 20-day moving average is at times bearish and at other times <strong>bullish</strong>, where a positive swing is expected. You can also see that the crossing of moving average lines indicate changes in trend. These crossings are what we can use as <strong>trading signals</strong>, or indications that a financial security is changing direction and a profitable trade might be made.</p>
<p><em>Visit next week to read about how to design and test a trading strategy using moving averages.</em></p>
<pre><code># Package/system information
sessionInfo()
</code></pre>
<pre>## R version 3.3.3 (2017-03-06)
## Platform: i686-pc-linux-gnu (32-bit)
## Running under: Ubuntu 15.10
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
## 
## attached base packages:
## [1] methods   stats     graphics  grDevices utils     datasets  base     
## 
## other attached packages:
## [1] magrittr_1.5     quantmod_0.4-7   TTR_0.23-1       xts_0.9-7       
## [5] zoo_1.7-14       RWordPress_0.2-3 optparse_1.3.2   knitr_1.15.1    
## 
## loaded via a namespace (and not attached):
##  [1] lattice_0.20-34 XML_3.98-1.5    bitops_1.0-6    grid_3.3.3     
##  [5] formatR_1.4     evaluate_0.10   highr_0.6       stringi_1.1.3  
##  [9] getopt_1.20.0   tools_3.3.3     stringr_1.2.0   RCurl_1.95-4.8 
## [13] XMLRPC_0.3-0
</pre>
<p> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ntguardian.wordpress.com/2453/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/ntguardian.wordpress.com/2453/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://ntguardian.wordpress.com/2017/03/27/introduction-stock-market-data-r-1/"> R – Curtis Miller's Personal Website</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/dBqM2f180EM"></a></div>