Disclaimer: The content of this RMarkdown note came from a course called Analyzing Financial Data and Implementing Financial Models Using R.

Troubleshooting for R Markdown

For a few computers, a new R Markdown file wouldn’t pop up when prompted. This likely has to do with the broswer setting. Disable the pop-up blocker, close the browser, and reopen the browswer. Or you might want to try a different browser.

Chapter 1: Prices

price versus value

The price of a security is at the core of investment analysis.

In this chapter, we will show:

1.1 Importing Daily Stock Price Data

Two alternatives

  • CSV upload code is the most stable approach
  • the getSymbols command in the quantmod package is less stable and may be ususable when Yahoo Finance changes some specifications of the data.

1.2 Importing Price Data from Yahoo Finance

# Step 1: Import CSV File from Yahoo Finance
# 1: Enter the following website address: http://finance.yahoo.com.
# 2: Enter the ticker symbol AMZN in the "Quote Lookup" or "Enter Symbol" box.
#    Use Chrome or Firefox. Internet Explorer doesn't seem to work well with Yahoo Finance.
# 3: Click on the Historical Prices link.
# 4: Enter the date range December 31, 2010 to December 31, 2013.
# 5: Click on Apply. Don't change Frequency. 
# 6: Click on Download Data, and save it as AMZN Yahoo.csv.
# 7: Upload it to the Workbench.

# Step 2: Import Data into R

# install necessary packages
#install.packages("xts")
#install.packages("quantmod")

# Load packages


# To clean up the memory of your current R session run the following line
rm(list=ls(all=TRUE))

# Load csv file
data.AMZN <- read.csv("data/AMZN Yahoo.csv", header = TRUE)
head(data.AMZN)
##         Date   Open   High    Low  Close  Volume Adj.Close
## 1 2013-12-31 394.58 398.83 393.80 398.79 1996500    398.79
## 2 2013-12-30 399.41 399.92 392.45 393.37 2487100    393.37
## 3 2013-12-27 404.65 405.63 396.25 398.08 1986900    398.08
## 4 2013-12-26 401.79 404.52 396.81 404.39 1868500    404.39
## 5 2013-12-24 402.52 403.72 396.37 399.20 1380400    399.20
## 6 2013-12-23 403.69 405.00 399.20 402.92 2659500    402.92
tail(data.AMZN)
##           Date   Open   High    Low  Close  Volume Adj.Close
## 750 2011-01-07 187.88 188.45 183.74 185.49 5221700    185.49
## 751 2011-01-06 186.50 187.41 185.25 185.86 3179700    185.86
## 752 2011-01-05 184.10 187.45 184.07 187.42 3418800    187.42
## 753 2011-01-04 186.15 187.70 183.78 185.01 5031800    185.01
## 754 2011-01-03 181.37 186.00 181.21 184.22 5331400    184.22
## 755 2010-12-31 181.96 182.30 179.51 180.00 3451900    180.00

# Step 3: Convert the date variable from a Factor to a Date
class(data.AMZN$Date)
## [1] "factor"
date <- as.Date(data.AMZN$Date, format = "%Y-%m-%d")
class(date)
## [1] "Date"

# Step 3a: Combine date and data.AMZN
data.AMZN <- cbind(date, data.AMZN[, -1])
head(data.AMZN)
##         date   Open   High    Low  Close  Volume Adj.Close
## 1 2013-12-31 394.58 398.83 393.80 398.79 1996500    398.79
## 2 2013-12-30 399.41 399.92 392.45 393.37 2487100    393.37
## 3 2013-12-27 404.65 405.63 396.25 398.08 1986900    398.08
## 4 2013-12-26 401.79 404.52 396.81 404.39 1868500    404.39
## 5 2013-12-24 402.52 403.72 396.37 399.20 1380400    399.20
## 6 2013-12-23 403.69 405.00 399.20 402.92 2659500    402.92
tail(data.AMZN)
##           date   Open   High    Low  Close  Volume Adj.Close
## 750 2011-01-07 187.88 188.45 183.74 185.49 5221700    185.49
## 751 2011-01-06 186.50 187.41 185.25 185.86 3179700    185.86
## 752 2011-01-05 184.10 187.45 184.07 187.42 3418800    187.42
## 753 2011-01-04 186.15 187.70 183.78 185.01 5031800    185.01
## 754 2011-01-03 181.37 186.00 181.21 184.22 5331400    184.22
## 755 2010-12-31 181.96 182.30 179.51 180.00 3451900    180.00

# Step 4: Sort the data in chronological order
data.AMZN <- data.AMZN[order(data.AMZN$date),]
head(data.AMZN)
##           date   Open   High    Low  Close  Volume Adj.Close
## 755 2010-12-31 181.96 182.30 179.51 180.00 3451900    180.00
## 754 2011-01-03 181.37 186.00 181.21 184.22 5331400    184.22
## 753 2011-01-04 186.15 187.70 183.78 185.01 5031800    185.01
## 752 2011-01-05 184.10 187.45 184.07 187.42 3418800    187.42
## 751 2011-01-06 186.50 187.41 185.25 185.86 3179700    185.86
## 750 2011-01-07 187.88 188.45 183.74 185.49 5221700    185.49
tail(data.AMZN)
##         date   Open   High    Low  Close  Volume Adj.Close
## 6 2013-12-23 403.69 405.00 399.20 402.92 2659500    402.92
## 5 2013-12-24 402.52 403.72 396.37 399.20 1380400    399.20
## 4 2013-12-26 401.79 404.52 396.81 404.39 1868500    404.39
## 3 2013-12-27 404.65 405.63 396.25 398.08 1986900    398.08
## 2 2013-12-30 399.41 399.92 392.45 393.37 2487100    393.37
## 1 2013-12-31 394.58 398.83 393.80 398.79 1996500    398.79

# Step 5: Convert data.frame object to xts object
class(data.AMZN)
## [1] "data.frame"
library(xts)
data.AMZN <- xts(data.AMZN[, 2:7], order.by = data.AMZN[, 1])
class(data.AMZN)
## [1] "xts" "zoo"

# Step 6: Rename variables
names(data.AMZN)
## [1] "Open"      "High"      "Low"       "Close"     "Volume"    "Adj.Close"
names(data.AMZN) <- paste(c("AMZN.Open", "AMZN.High", "AMZN.Low", 
                            "AMZN.Close", "AMZN.Volume", "AMZN.Adjusted"))
head(data.AMZN)
##            AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
## 2010-12-31    181.96    182.30   179.51     180.00     3451900
## 2011-01-03    181.37    186.00   181.21     184.22     5331400
## 2011-01-04    186.15    187.70   183.78     185.01     5031800
## 2011-01-05    184.10    187.45   184.07     187.42     3418800
## 2011-01-06    186.50    187.41   185.25     185.86     3179700
## 2011-01-07    187.88    188.45   183.74     185.49     5221700
##            AMZN.Adjusted
## 2010-12-31        180.00
## 2011-01-03        184.22
## 2011-01-04        185.01
## 2011-01-05        187.42
## 2011-01-06        185.86
## 2011-01-07        185.49
tail(data.AMZN)
##            AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
## 2013-12-23    403.69    405.00   399.20     402.92     2659500
## 2013-12-24    402.52    403.72   396.37     399.20     1380400
## 2013-12-26    401.79    404.52   396.81     404.39     1868500
## 2013-12-27    404.65    405.63   396.25     398.08     1986900
## 2013-12-30    399.41    399.92   392.45     393.37     2487100
## 2013-12-31    394.58    398.83   393.80     398.79     1996500
##            AMZN.Adjusted
## 2013-12-23        402.92
## 2013-12-24        399.20
## 2013-12-26        404.39
## 2013-12-27        398.08
## 2013-12-30        393.37
## 2013-12-31        398.79

alternative way to import Yahoo Fiance into R

library(quantmod)
alt.data.AMZN <- getSymbols("AMZN", from = "2010-12-31", to = "2014-01-01", auto.assign = FALSE)
#to = "2013-12-31" in the book was replaced by to = "2014-01-01"
#B/c that code doesn't produce the output that includes stock price of 2013-12-31the date. 
class(alt.data.AMZN)
head(alt.data.AMZN)
tail(alt.data.AMZN)

1.3 Checking the Data

1.3.1 Plotting the data

plot(data.AMZN$AMZN.Close)

1.3.2 Checking the dimension

dim(data.AMZN) 
## [1] 755   6
#stock price data should have 6 variables and # of rows roughly = 252 times # of years 

1.3.3 Outputting summary statistics

summary(data.AMZN)
##      Index              AMZN.Open       AMZN.High        AMZN.Low    
##  Min.   :2010-12-31   Min.   :161.2   Min.   :163.5   Min.   :160.6  
##  1st Qu.:2011-09-29   1st Qu.:192.8   1st Qu.:195.4   1st Qu.:190.2  
##  Median :2012-06-29   Median :226.6   Median :230.7   Median :224.6  
##  Mean   :2012-06-30   Mean   :238.2   Mean   :241.0   Mean   :235.2  
##  3rd Qu.:2013-04-03   3rd Qu.:266.7   3rd Qu.:269.4   3rd Qu.:263.8  
##  Max.   :2013-12-31   Max.   :404.6   Max.   :405.6   Max.   :399.2  
##    AMZN.Close     AMZN.Volume       AMZN.Adjusted  
##  Min.   :161.0   Min.   :  984400   Min.   :161.0  
##  1st Qu.:193.3   1st Qu.: 2660750   1st Qu.:193.3  
##  Median :227.3   Median : 3706200   Median :227.3  
##  Mean   :238.3   Mean   : 4319524   Mean   :238.3  
##  3rd Qu.:266.4   3rd Qu.: 5160950   3rd Qu.:266.4  
##  Max.   :404.4   Max.   :24134200   Max.   :404.4

1.3.4 Checking the ticker symbol

1.4 Basic Data Manipulation Techniques

1.4.1 Keeping and deleting one row

AMZN.onlyFirst <- data.AMZN[1, ]
AMZN.onlyFirst
##            AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
## 2010-12-31    181.96     182.3   179.51        180     3451900
##            AMZN.Adjusted
## 2010-12-31           180

AMZN.delFirst <- data.AMZN[-1, ]
head(AMZN.delFirst)
##            AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
## 2011-01-03    181.37    186.00   181.21     184.22     5331400
## 2011-01-04    186.15    187.70   183.78     185.01     5031800
## 2011-01-05    184.10    187.45   184.07     187.42     3418800
## 2011-01-06    186.50    187.41   185.25     185.86     3179700
## 2011-01-07    187.88    188.45   183.74     185.49     5221700
## 2011-01-10    185.04    185.29   182.51     184.68     3375900
##            AMZN.Adjusted
## 2011-01-03        184.22
## 2011-01-04        185.01
## 2011-01-05        187.42
## 2011-01-06        185.86
## 2011-01-07        185.49
## 2011-01-10        184.68

1.4.2 Keeping first and last rows

data.AMZN[c(1, nrow(data.AMZN)), ]
##            AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
## 2010-12-31    181.96    182.30   179.51     180.00     3451900
## 2013-12-31    394.58    398.83   393.80     398.79     1996500
##            AMZN.Adjusted
## 2010-12-31        180.00
## 2013-12-31        398.79

1.4.3 Keeping contiguous rows

AMZN.first.week <- data.AMZN[2:6, ] # first of week January 2011
AMZN.first.week
##            AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
## 2011-01-03    181.37    186.00   181.21     184.22     5331400
## 2011-01-04    186.15    187.70   183.78     185.01     5031800
## 2011-01-05    184.10    187.45   184.07     187.42     3418800
## 2011-01-06    186.50    187.41   185.25     185.86     3179700
## 2011-01-07    187.88    188.45   183.74     185.49     5221700
##            AMZN.Adjusted
## 2011-01-03        184.22
## 2011-01-04        185.01
## 2011-01-05        187.42
## 2011-01-06        185.86
## 2011-01-07        185.49

AMZN.last30 <- data.AMZN[(nrow(data.AMZN)-29):nrow(data.AMZN), ]
AMZN.last30
##            AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
## 2013-11-18    370.28    373.49   364.67     366.18     2737400
## 2013-11-19    365.82    368.78   362.50     364.94     1904800
## 2013-11-20    367.56    367.56   360.45     362.57     1771500
## 2013-11-21    364.05    369.25   363.30     368.92     1964600
## 2013-11-22    370.00    374.50   366.31     372.31     2965500
## 2013-11-25    373.82    377.79   373.18     376.64     2972300
## 2013-11-26    377.61    382.50   374.82     381.37     2724400
## 2013-11-27    383.50    387.00   382.61     386.71     2269700
## 2013-11-29    389.10    394.10   388.62     393.62     2406000
## 2013-12-02    399.00    399.00   389.10     392.30     4714000
## 2013-12-03    390.11    390.95   383.10     384.66     3702900
## 2013-12-04    383.50    389.69   381.49     385.96     2355300
## 2013-12-05    386.65    386.65   381.37     384.49     1906500
## 2013-12-06    388.35    388.35   383.83     386.95     1984700
## 2013-12-09    388.11    388.21   382.57     384.89     2761800
## 2013-12-10    383.74    389.06   383.02     387.78     2736800
## 2013-12-11    387.34    388.98   382.00     382.19     2451300
## 2013-12-12    381.26    385.00   379.50     381.25     2123700
## 2013-12-13    385.32    389.42   383.80     384.24     3025000
## 2013-12-16    385.03    391.70   385.00     388.97     2251700
## 2013-12-17    390.65    391.36   386.50     387.65     2343900
## 2013-12-18    389.23    396.30   383.10     395.96     3489100
## 2013-12-19    394.27    397.29   392.60     395.19     2427200
## 2013-12-20    396.55    404.72   395.78     402.20     5033900
## 2013-12-23    403.69    405.00   399.20     402.92     2659500
## 2013-12-24    402.52    403.72   396.37     399.20     1380400
## 2013-12-26    401.79    404.52   396.81     404.39     1868500
## 2013-12-27    404.65    405.63   396.25     398.08     1986900
## 2013-12-30    399.41    399.92   392.45     393.37     2487100
## 2013-12-31    394.58    398.83   393.80     398.79     1996500
##            AMZN.Adjusted
## 2013-11-18        366.18
## 2013-11-19        364.94
## 2013-11-20        362.57
## 2013-11-21        368.92
## 2013-11-22        372.31
## 2013-11-25        376.64
## 2013-11-26        381.37
## 2013-11-27        386.71
## 2013-11-29        393.62
## 2013-12-02        392.30
## 2013-12-03        384.66
## 2013-12-04        385.96
## 2013-12-05        384.49
## 2013-12-06        386.95
## 2013-12-09        384.89
## 2013-12-10        387.78
## 2013-12-11        382.19
## 2013-12-12        381.25
## 2013-12-13        384.24
## 2013-12-16        388.97
## 2013-12-17        387.65
## 2013-12-18        395.96
## 2013-12-19        395.19
## 2013-12-20        402.20
## 2013-12-23        402.92
## 2013-12-24        399.20
## 2013-12-26        404.39
## 2013-12-27        398.08
## 2013-12-30        393.37
## 2013-12-31        398.79

1.4.10 Subsetting Using Dates

# Data is an XTS object
class(data.AMZN)
## [1] "xts" "zoo"
xts.2012 <- subset(data.AMZN[, 4], 
                   index(data.AMZN) >= "2012-01-01" &
                   index(data.AMZN) <= "2012-12-31")
xts.2012[c(1:3, nrow(xts.2012)), ]
##            AMZN.Close
## 2012-01-03     179.03
## 2012-01-04     177.51
## 2012-01-05     177.61
## 2012-12-31     250.87

# Data is a data.frame object

# Convert xts.2012 to a data.frame object
data.frame(xts.2012)
##            AMZN.Close
## 2012-01-03     179.03
## 2012-01-04     177.51
## 2012-01-05     177.61
## 2012-01-06     182.61
## 2012-01-09     178.56
## 2012-01-10     179.34
## 2012-01-11     178.90
## 2012-01-12     175.93
## 2012-01-13     178.42
## 2012-01-17     181.66
## 2012-01-18     189.44
## 2012-01-19     194.45
## 2012-01-20     190.93
## 2012-01-23     186.09
## 2012-01-24     187.00
## 2012-01-25     187.80
## 2012-01-26     193.32
## 2012-01-27     195.37
## 2012-01-30     192.15
## 2012-01-31     194.44
## 2012-02-01     179.46
## 2012-02-02     181.72
## 2012-02-03     187.68
## 2012-02-06     183.14
## 2012-02-07     184.19
## 2012-02-08     185.48
## 2012-02-09     184.98
## 2012-02-10     185.54
## 2012-02-13     191.59
## 2012-02-14     191.30
## 2012-02-15     184.47
## 2012-02-16     179.93
## 2012-02-17     182.50
## 2012-02-21     182.26
## 2012-02-22     180.58
## 2012-02-23     178.89
## 2012-02-24     179.13
## 2012-02-27     178.53
## 2012-02-28     183.80
## 2012-02-29     179.69
## 2012-03-01     180.04
## 2012-03-02     179.30
## 2012-03-05     180.26
## 2012-03-06     181.09
## 2012-03-07     183.77
## 2012-03-08     187.64
## 2012-03-09     184.32
## 2012-03-12     183.39
## 2012-03-13     184.59
## 2012-03-14     182.26
## 2012-03-15     184.43
## 2012-03-16     185.05
## 2012-03-19     185.52
## 2012-03-20     192.33
## 2012-03-21     191.73
## 2012-03-22     192.40
## 2012-03-23     195.04
## 2012-03-26     202.87
## 2012-03-27     205.44
## 2012-03-28     201.16
## 2012-03-29     204.61
## 2012-03-30     202.51
## 2012-04-02     198.05
## 2012-04-03     199.66
## 2012-04-04     193.99
## 2012-04-05     194.39
## 2012-04-09     191.87
## 2012-04-10     186.98
## 2012-04-11     187.97
## 2012-04-12     190.69
## 2012-04-13     188.46
## 2012-04-16     185.50
## 2012-04-17     188.39
## 2012-04-18     191.07
## 2012-04-19     191.10
## 2012-04-20     189.98
## 2012-04-23     188.24
## 2012-04-24     190.33
## 2012-04-25     194.42
## 2012-04-26     195.99
## 2012-04-27     226.85
## 2012-04-30     231.90
## 2012-05-01     230.04
## 2012-05-02     230.25
## 2012-05-03     229.45
## 2012-05-04     223.99
## 2012-05-07     225.16
## 2012-05-08     223.90
## 2012-05-09     222.98
## 2012-05-10     226.69
## 2012-05-11     227.68
## 2012-05-14     222.93
## 2012-05-15     224.39
## 2012-05-16     224.06
## 2012-05-17     218.36
## 2012-05-18     213.85
## 2012-05-21     218.11
## 2012-05-22     215.33
## 2012-05-23     217.28
## 2012-05-24     215.24
## 2012-05-25     212.89
## 2012-05-29     214.75
## 2012-05-30     209.23
## 2012-05-31     212.91
## 2012-06-01     208.22
## 2012-06-04     214.57
## 2012-06-05     213.21
## 2012-06-06     217.64
## 2012-06-07     218.80
## 2012-06-08     218.48
## 2012-06-11     216.50
## 2012-06-12     216.42
## 2012-06-13     214.73
## 2012-06-14     214.45
## 2012-06-15     218.35
## 2012-06-18     222.66
## 2012-06-19     224.03
## 2012-06-20     223.02
## 2012-06-21     220.57
## 2012-06-22     222.16
## 2012-06-25     220.07
## 2012-06-26     225.61
## 2012-06-27     225.62
## 2012-06-28     221.31
## 2012-06-29     228.35
## 2012-07-02     229.32
## 2012-07-03     229.53
## 2012-07-05     227.06
## 2012-07-06     225.05
## 2012-07-09     225.05
## 2012-07-10     219.50
## 2012-07-11     218.37
## 2012-07-12     215.36
## 2012-07-13     218.39
## 2012-07-16     216.01
## 2012-07-17     216.93
## 2012-07-18     217.47
## 2012-07-19     226.17
## 2012-07-20     228.29
## 2012-07-23     226.01
## 2012-07-24     223.04
## 2012-07-25     217.05
## 2012-07-26     220.01
## 2012-07-27     237.32
## 2012-07-30     236.09
## 2012-07-31     233.30
## 2012-08-01     232.09
## 2012-08-02     230.81
## 2012-08-03     234.97
## 2012-08-06     233.99
## 2012-08-07     236.56
## 2012-08-08     234.38
## 2012-08-09     234.06
## 2012-08-10     232.75
## 2012-08-13     232.44
## 2012-08-14     233.19
## 2012-08-15     237.42
## 2012-08-16     241.55
## 2012-08-17     241.17
## 2012-08-20     240.35
## 2012-08-21     239.45
## 2012-08-22     243.10
## 2012-08-23     241.20
## 2012-08-24     245.74
## 2012-08-27     243.92
## 2012-08-28     246.11
## 2012-08-29     247.12
## 2012-08-30     246.22
## 2012-08-31     248.27
## 2012-09-04     247.88
## 2012-09-05     246.22
## 2012-09-06     251.38
## 2012-09-07     259.14
## 2012-09-10     257.09
## 2012-09-11     255.67
## 2012-09-12     255.63
## 2012-09-13     260.24
## 2012-09-14     261.27
## 2012-09-17     258.00
## 2012-09-18     258.75
## 2012-09-19     261.68
## 2012-09-20     260.81
## 2012-09-21     257.47
## 2012-09-24     254.80
## 2012-09-25     252.46
## 2012-09-26     249.67
## 2012-09-27     256.59
## 2012-09-28     254.32
## 2012-10-01     252.01
## 2012-10-02     250.60
## 2012-10-03     255.92
## 2012-10-04     260.47
## 2012-10-05     258.51
## 2012-10-08     259.06
## 2012-10-09     250.96
## 2012-10-10     244.99
## 2012-10-11     244.22
## 2012-10-12     242.36
## 2012-10-15     244.18
## 2012-10-16     243.94
## 2012-10-17     247.49
## 2012-10-18     244.85
## 2012-10-19     240.00
## 2012-10-22     233.78
## 2012-10-23     234.31
## 2012-10-24     228.49
## 2012-10-25     222.92
## 2012-10-26     238.24
## 2012-10-31     232.89
## 2012-11-01     232.14
## 2012-11-02     232.42
## 2012-11-05     234.33
## 2012-11-06     237.56
## 2012-11-07     232.06
## 2012-11-08     227.35
## 2012-11-09     226.31
## 2012-11-12     226.47
## 2012-11-13     226.60
## 2012-11-14     222.95
## 2012-11-15     220.60
## 2012-11-16     225.23
## 2012-11-19     229.71
## 2012-11-20     233.78
## 2012-11-21     238.03
## 2012-11-23     239.88
## 2012-11-26     243.62
## 2012-11-27     243.40
## 2012-11-28     247.11
## 2012-11-29     251.27
## 2012-11-30     252.05
## 2012-12-03     250.33
## 2012-12-04     252.49
## 2012-12-05     253.96
## 2012-12-06     253.37
## 2012-12-07     253.27
## 2012-12-10     247.77
## 2012-12-11     250.69
## 2012-12-12     251.76
## 2012-12-13     251.25
## 2012-12-14     249.19
## 2012-12-17     253.86
## 2012-12-18     260.40
## 2012-12-19     257.99
## 2012-12-20     261.50
## 2012-12-21     256.92
## 2012-12-24     258.62
## 2012-12-26     248.63
## 2012-12-27     248.31
## 2012-12-28     245.18
## 2012-12-31     250.87
# Note that this code turns the date column into the row name, which can't be used to subset
# So we need to create a date column
AMZN.2012 <- cbind(index(data.AMZN), data.frame(data.AMZN[, 4]))
AMZN.2012[c(1:3, nrow(AMZN.2012)), ]
##            index(data.AMZN) AMZN.Close
## 2010-12-31       2010-12-31     180.00
## 2011-01-03       2011-01-03     184.22
## 2011-01-04       2011-01-04     185.01
## 2013-12-31       2013-12-31     398.79
# Change names
names(AMZN.2012)[1] <- "date"
rownames(AMZN.2012) <- c(1:nrow(AMZN.2012))
AMZN.2012[c(1:3, nrow(AMZN.2012)), ]
##           date AMZN.Close
## 1   2010-12-31     180.00
## 2   2011-01-03     184.22
## 3   2011-01-04     185.01
## 755 2013-12-31     398.79

# subset
AMZN.2012 <- subset(AMZN.2012, 
                    AMZN.2012$date >= "2012-01-01" &
                    AMZN.2012$date <= "2012-12-31")
AMZN.2012[c(1:3, nrow(AMZN.2012)), ]
##           date AMZN.Close
## 254 2012-01-03     179.03
## 255 2012-01-04     177.51
## 256 2012-01-05     177.61
## 503 2012-12-31     250.87

1.4.11 Converting Daily Prices to Weekly and Monthly Prices

# Converting to Weekly Prices
wk <- data.AMZN
data.weekly <- to.weekly(wk)
data.weekly[c(1:3, nrow(data.weekly)), ]
##            wk.Open wk.High wk.Low wk.Close wk.Volume wk.Adjusted
## 2010-12-31  181.96  182.30 179.51   180.00   3451900      180.00
## 2011-01-07  181.37  188.45 181.21   185.49  22183400      185.49
## 2011-01-14  185.04  188.94 182.51   188.75  15899000      188.75
## 2013-12-31  399.41  399.92 392.45   398.79   4483600      398.79

# To check that the data was actually converted properly the to.weekly commend
data.AMZN[2:6, ]
##            AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
## 2011-01-03    181.37    186.00   181.21     184.22     5331400
## 2011-01-04    186.15    187.70   183.78     185.01     5031800
## 2011-01-05    184.10    187.45   184.07     187.42     3418800
## 2011-01-06    186.50    187.41   185.25     185.86     3179700
## 2011-01-07    187.88    188.45   183.74     185.49     5221700
##            AMZN.Adjusted
## 2011-01-03        184.22
## 2011-01-04        185.01
## 2011-01-05        187.42
## 2011-01-06        185.86
## 2011-01-07        185.49
sum(data.AMZN[2:6, 5])
## [1] 22183400

# Converting to Monthly Prices
mo <- data.AMZN
data.monthly <- to.monthly(mo)
data.monthly[c(1:3, nrow(data.monthly)), ]
##          mo.Open mo.High mo.Low mo.Close mo.Volume mo.Adjusted
## Dec 2010  181.96  182.30 179.51   180.00   3451900      180.00
## Jan 2011  181.37  191.60 166.90   169.64 113611300      169.64
## Feb 2011  170.52  191.40 169.51   173.29  95776400      173.29
## Dec 2013  399.00  405.63 379.50   398.79  55686700      398.79

# Plotting a Candlestick Chart Using Monthly Data
library(quantmod)
OHLC <- data.monthly[-1, -6] # Drop the 2010-12-31 observation and the adjusted close
AMZN.ohlc <- as.quantmod.OHLC(OHLC,
                              col.names = c("Open", "High", "Low", "Close", "Volume"))
class(AMZN.ohlc)
## [1] "quantmod.OHLC" "zoo"
AMZN.ohlc[c(1:3, nrow(AMZN.ohlc)), ]
##          OHLC.Open OHLC.High OHLC.Low OHLC.Close OHLC.Volume
## Jan 2011    181.37    191.60   166.90     169.64   113611300
## Feb 2011    170.52    191.40   169.51     173.29    95776400
## Mar 2011    173.53    181.57   160.59     180.13   118979100
## Dec 2013    399.00    405.63   379.50     398.79    55686700
chartSeries(AMZN.ohlc,
            theme = "white.mono",
            name = "AMZN OHLC")

1.5 Comparing Capital Gains of Multiple Securities Over Time

AABA replaced YHOO in the textbook. The shares of what used to be known as Yahoo under the ticker symbol YHOO started trading Monday as Altaba (think alternative Alibaba) and trade under the symbol AABA.Jun 19, 2017.

# See what objects are in the R memory
ls()
##  [1] "AMZN.2012"       "AMZN.delFirst"   "AMZN.first.week"
##  [4] "AMZN.last30"     "AMZN.ohlc"       "AMZN.onlyFirst" 
##  [7] "data.AMZN"       "data.monthly"    "data.weekly"    
## [10] "date"            "mo"              "OHLC"           
## [13] "wk"              "xts.2012"

# Delete all these objects
rm(list = ls())
ls()
## character(0)

# AABA replaced YHOO in the textbook
# The shares of what used to be known as Yahoo under the ticker symbol YHOO started trading #Monday as Altaba (think alternative Alibaba) and trade under the symbol AABA.Jun 19, 2017

# Compare the capital gains of multiple securities over time - AMZN, IBM, AABA, ^GSPC
# Which of these investments performed better from 12/31/2010 to 12/31/2013
# based soley on price appreciation?

data.AMZN <- getSymbols("AMZN", from = "2010-12-31", to = "2014-01-01", auto.assign = FALSE)
data.AABA <- getSymbols("AABA", from = "2010-12-31", to = "2014-01-01", auto.assign = FALSE)
data.IBM <- getSymbols("IBM", from = "2010-12-31", to = "2014-01-01", auto.assign = FALSE)
data.GSPC <- getSymbols("^GSPC", from = "2010-12-31", to = "2014-01-01", auto.assign = FALSE)


# Combine Data into One Data Object
Close.Prices <- data.AMZN$AMZN.Close # Need to create a new data object before cbinding
Close.Prices <- cbind(Close.Prices, data.GSPC$GSPC.Close,
                      data.AABA$AABA.Close, data.IBM$IBM.Close)
Close.Prices[c(1:3, nrow(Close.Prices)), ]
##            AMZN.Close GSPC.Close AABA.Close IBM.Close
## 2010-12-31     180.00    1257.64      16.63    146.76
## 2011-01-03     184.22    1271.87      16.75    147.48
## 2011-01-04     185.01    1270.20      16.59    147.64
## 2013-12-31     398.79    1848.36      40.44    187.57

# Convert Data into a data.frame
multi.df <- cbind(index(Close.Prices), 
                  data.frame(Close.Prices))
names(multi.df) <- c("date", "AMZN", "GSPC", "AABA", "IBM")
row.names(multi.df) <- seq(1, nrow(multi.df), 1)
multi.df[c(1:3, nrow(multi.df)), ]
##           date   AMZN    GSPC  AABA    IBM
## 1   2010-12-31 180.00 1257.64 16.63 146.76
## 2   2011-01-03 184.22 1271.87 16.75 147.48
## 3   2011-01-04 185.01 1270.20 16.59 147.64
## 755 2013-12-31 398.79 1848.36 40.44 187.57

# Calculate Normalized Values for Each Security
multi.df$AMZN.idx <- multi.df$AMZN / multi.df$AMZN[1]
multi.df$GSPC.idx <- multi.df$GSPC / multi.df$GSPC[1]
multi.df$AABA.idx <- multi.df$AABA / multi.df$AABA[1]
multi.df$IBM.idx <- multi.df$IBM / multi.df$IBM[1]
options(digits = 5)
multi.df[c(1:3, nrow(multi.df)), ]
##           date   AMZN   GSPC  AABA    IBM AMZN.idx GSPC.idx AABA.idx
## 1   2010-12-31 180.00 1257.6 16.63 146.76   1.0000   1.0000  1.00000
## 2   2011-01-03 184.22 1271.9 16.75 147.48   1.0234   1.0113  1.00722
## 3   2011-01-04 185.01 1270.2 16.59 147.64   1.0278   1.0100  0.99759
## 755 2013-12-31 398.79 1848.4 40.44 187.57   2.2155   1.4697  2.43175
##     IBM.idx
## 1    1.0000
## 2    1.0049
## 3    1.0060
## 755  1.2781
options(digits = 7)

# Plot the Capital Appreciation of Each Security

# GSPC first
plot(x = multi.df$date,
     y = multi.df$GSPC.idx,
     type = "l",
     xlab = "Date",
     ylab = "Value of Investment ($)",
     col = "black",
     lty = 1,
     lwd = 2,
     main = "Value of $1 Investment in 
        AMZN, IBM, AABA, and the S&P 500 Index
        December 1, 2010 - December 31, 2013")
     

# Add a line for AMZN, AABA, IBM

lines(x = multi.df$date,
      y = multi.df$AMZN.idx,
      col = "black",
      lty = 2,
      lwd = 1)
lines(x = multi.df$date,
      y = multi.df$AABA.idx,
      col = "gray",
      lty = 2,
      lwd = 1)
lines(x = multi.df$date,
      y = multi.df$IBM.idx,
      col = "gray",
      lty = 1,
      lwd = 1)
abline(h = 1, lty = 1, col = "black")
legend("topleft",
       c("AMZN", "IBN", "AABA", "S&P 500 Index"),
       col = c("black", "gray", "gray", "black"),
       lty = c(2, 2, 1, 1),
       lwd = c(1, 1, 1, 2))

y.range <- range(multi.df[, 6:9]) # this should go into the plot command

# all together

plot(x = multi.df$date,
     y = multi.df$GSPC.idx,
     type = "l",
     xlab = "Date",
     ylim = y.range,
     ylab = "Value of Investment ($)",
     col = "black",
     lty = 1,
     lwd = 2,
     main = "Value of $1 Investment in 
     AMZN, IBM, AABA, and the S&P 500 Index
     December 1, 2010 - December 31, 2013")
lines(x = multi.df$date,
      y = multi.df$AMZN.idx,
      col = "black",
      lty = 2,
      lwd = 1)
lines(x = multi.df$date,
      y = multi.df$AABA.idx,
      col = "gray",
      lty = 2,
      lwd = 1)
lines(x = multi.df$date,
      y = multi.df$IBM.idx,
      col = "gray",
      lty = 1,
      lwd = 1)
abline(h = 1, lty = 1, col = "black")
legend("topleft",
       c("S&P 500 Index", "AMZN", "AABA", "IBM"), # order must be consistent for all arg
       col = c("black", "black", "gray", "gray"),
       lty = c(1, 2, 2, 1),
       lwd = c(2, 1, 1, 1))

1.5.1 Alternative Presentation of Normalized Price Chart

# four mini charts into one big chart
par(oma = c(0, 0, 3, 0)) # To have enough space for the chart title, the arg is for top margin
par(mfrow = c(2, 2)) # 2(rows) by 2(columns) layout for the next four plots

# Amazon Stock as subject
plot(x = multi.df$date,
     y = multi.df$AABA.idx,
     xlab = "",
     ylim = y.range,
     ylab = "",
     type = "l",
     col = "gray",
     main = "Amazon Stock")
lines(x = multi.df$date, y = multi.df$GSPC.idx, col = "gray")
lines(x = multi.df$date, y = multi.df$IBM.idx, col = "gray")
lines(x = multi.df$date, y = multi.df$AMZN.idx, col = "black", lwd = 2)
abline(h = 1)

# IBM Stock as subject
plot(x = multi.df$date,
     y = multi.df$AABA.idx,
     xlab = "",
     ylim = y.range,
     ylab = "",
     type = "l",
     col = "gray",
     main = "IBM Stock")
lines(x = multi.df$date, y = multi.df$GSPC.idx, col = "gray")
lines(x = multi.df$date, y = multi.df$AMZN.idx, col = "gray")
lines(x = multi.df$date, y = multi.df$IBM.idx, col = "black", lwd = 2)
abline(h = 1)

# AABA Stock as subject
plot(x = multi.df$date,
     y = multi.df$AMZN.idx,
     xlab = "",
     ylim = y.range,
     ylab = "",
     type = "l",
     col = "gray",
     main = "Altaba Stock")
lines(x = multi.df$date, y = multi.df$GSPC.idx, col = "gray")
lines(x = multi.df$date, y = multi.df$IBM.idx, col = "gray")
lines(x = multi.df$date, y = multi.df$AABA.idx, col = "black", lwd = 2)
abline(h = 1)

# S&P 500 as subject
plot(x = multi.df$date,
     y = multi.df$AABA.idx,
     xlab = "",
     ylim = y.range,
     ylab = "",
     type = "l",
     col = "gray",
     main = "S&P 500 Index")
lines(x = multi.df$date, y = multi.df$AMZN.idx, col = "gray")
lines(x = multi.df$date, y = multi.df$IBM.idx, col = "gray")
lines(x = multi.df$date, y = multi.df$GSPC.idx, col = "black", lwd = 2)
abline(h = 1)

# Creat a Global Title for the Charts
title1 = "Value of $1 Invested in Amazon, IBM, Altaba, and the Market"
title2 = "December 31, 2010 - December 31, 2013"
title(main = paste(title1, "\n", title2), outer = TRUE)

1.6 Technical Analysis Examples

Technical analysis is for the purpose of forecasting future trends Profiting from technical analysis relies on the ability to

  1. id trends and
  2. catch on during the early states of the trend

three broad groups of technical indicators

  1. trend (moving average crossover);
  2. volatility (Bollinger Bands);
  3. momentum (rel strenth)

1.6.1 Trend: Simple Moving Average Crossover

Crossover b/c we use two SMA lines, a shorter-term and a longer-term, and make trading decisions whe the lines cross

Demonstrate how to implement an SMA corssover for Amazon.com stock from 2012 to 2013

  • bullish crossover if the 50-day MA cross above the 200-day MA
  • bearish crossover if the 50-day MA cross below the 200-day MA
# Step1: Obtain Closing Prices for Amazon.com Stock
AMZN.sma <- data.AMZN[, 4]
AMZN.sma[c(1:3, nrow(AMZN.sma)), ]
##            AMZN.Close
## 2010-12-31     180.00
## 2011-01-03     184.22
## 2011-01-04     185.01
## 2013-12-31     398.79

# Step2: Calculate the Rolling 50-Day and 200-Day Average Price
AMZN.sma$sma50 <- rollmeanr(AMZN.sma$AMZN.Close, k = 50)
AMZN.sma$sma200 <- rollmeanr(AMZN.sma$AMZN.Close, k = 200)
AMZN.sma[c(1:3, nrow(AMZN.sma)), ] #sma50 (sma200) only reports the 50th (200th) obs
##            AMZN.Close    sma50   sma200
## 2010-12-31     180.00       NA       NA
## 2011-01-03     184.22       NA       NA
## 2011-01-04     185.01       NA       NA
## 2013-12-31     398.79 372.9076 306.0776
AMZN.sma[48:52, ]
##            AMZN.Close    sma50 sma200
## 2011-03-10     166.14       NA     NA
## 2011-03-11     168.07       NA     NA
## 2011-03-14     166.73 179.2034     NA
## 2011-03-15     165.08 178.9050     NA
## 2011-03-16     164.70 178.5146     NA
AMZN.sma[198:202, ]
##            AMZN.Close    sma50   sma200
## 2011-10-12     236.81 212.7294       NA
## 2011-10-13     236.15 213.2532       NA
## 2011-10-14     246.71 214.1578 195.3837
## 2011-10-17     242.33 214.9504 195.6953
## 2011-10-18     243.88 215.9540 195.9936

# Step 3: Subset to Only Show 2012 and 2013 Data
AMZN.sma2012 <- subset(AMZN.sma,
                   index(AMZN.sma) >= "2012-01-01")
AMZN.sma2012[c(1:3, nrow(AMZN.sma2012)), ]
##            AMZN.Close    sma50   sma200
## 2012-01-03     179.03 197.8458 201.5382
## 2012-01-04     177.51 196.7004 201.6032
## 2012-01-05     177.61 195.5004 201.6782
## 2013-12-31     398.79 372.9076 306.0776

# Step 4: Plot the SMA
y.range <- range(AMZN.sma2012, na.rm = TRUE)
y.range
## [1] 175.93 404.39

par(mfrow = c(1, 1))
plot(x = index(AMZN.sma2012),
     y = AMZN.sma2012$AMZN.Close,
     xlab = "Date",
     ylim = y.range,
     ylab = "Price ($)",
     type = "l",
     main = "Amazon - Simple Moving Average
        January 1, 2012 - December 31, 2013")
lines(x = index(AMZN.sma2012), y = AMZN.sma2012$sma50)
lines(x = index(AMZN.sma2012), y = AMZN.sma2012$sma200, lty = 2)
legend("topleft",
       c("Amazon Price", "50-Day Moving Averge", "200-Day Moving Average"),
       lty = c(1, 1, 2)) # cex = 0.5 to reduce legend size 

1.6.2 Volatility: Bollinger Bands

Demonstrate how to apply Bollinger Bands to Amazon.com stock in 2013

  • If the stock price is right around the upper band, the stock may be considered overbought
  • If the stock price is right around the lower band, the stock may be considered oversold
# Step 1: Obtain Closing Prices for Amazon.com Stock
AMZN.bb <- data.AMZN[, 4]
AMZN.bb[c(1:3, nrow(AMZN.bb)), ]
##            AMZN.Close
## 2010-12-31     180.00
## 2011-01-03     184.22
## 2011-01-04     185.01
## 2013-12-31     398.79

# Step2: Calculatue Rolling 20-Day Mean and Standard Deviation
AMZN.bb$avg <- rollmeanr(AMZN.bb$AMZN.Close, k = 20)
AMZN.bb$sd <- rollapply(AMZN.bb$AMZN.Close, width = 20, FUN = sd)
AMZN.bb[c(1:3, nrow(AMZN.bb)), ]
##            AMZN.Close      avg       sd
## 2010-12-31     180.00       NA       NA
## 2011-01-03     184.22       NA       NA
## 2011-01-04     185.01       NA       NA
## 2013-12-31     398.79 391.4565 7.519367
AMZN.bb[18:22, ]
##            AMZN.Close      avg       sd
## 2011-01-26     175.39       NA       NA
## 2011-01-27     184.45       NA       NA
## 2011-01-28     171.14 182.8705 5.061730
## 2011-01-31     169.64 182.3525 5.841057
## 2011-02-01     172.11 181.7470 6.250598

# Step3: Subset to Only Show 2013 Data
AMZN.bb2013 <- subset(AMZN.bb,
                      index(AMZN.bb) >= "2013-01-01")
AMZN.bb2013[c(1:3, nrow(AMZN.bb2013)), ]
##            AMZN.Close      avg       sd
## 2013-01-02     257.31 253.1670 4.457978
## 2013-01-03     258.48 253.4665 4.608764
## 2013-01-04     259.15 253.7260 4.780912
## 2013-12-31     398.79 391.4565 7.519367

# Step 4: Calculate the Bollinger Bands
AMZN.bb2013$sd2up <- AMZN.bb2013$avg + 2*AMZN.bb2013$sd
AMZN.bb2013$sd2down <- AMZN.bb2013$avg - 2*AMZN.bb2013$sd
AMZN.bb2013[c(1:3, nrow(AMZN.bb2013)), ]
##            AMZN.Close      avg       sd    sd2up  sd2down
## 2013-01-02     257.31 253.1670 4.457978 262.0830 244.2510
## 2013-01-03     258.48 253.4665 4.608764 262.6840 244.2490
## 2013-01-04     259.15 253.7260 4.780912 263.2878 244.1642
## 2013-12-31     398.79 391.4565 7.519367 406.4952 376.4178

# Step 5: Plot the Bollinger Bands
y.range = range(AMZN.bb2013[, c(1:2, 4:5)])
y.range
## [1] 242.3923 406.4952

plot(x = index(AMZN.bb2013),
     y = AMZN.bb2013$AMZN.Close,
     xlab ="Date",
     ylim = y.range,
     ylab = "Price ($)",
     type = "l",
     lwd = 3,
     main = " Amazon - Bollinger Bands (20 days, 2 deviations)
        January 1, 2013 - December 31, 2013")
lines(x = index(AMZN.bb2013), y = AMZN.bb2013$avg, lwd = 1, lty = 2)
lines(x = index(AMZN.bb2013), y = AMZN.bb2013$sd2up, lwd = 1)
lines(x = index(AMZN.bb2013), y = AMZN.bb2013$sd2down, lwd = 1)
legend("topleft",
       c("Amazon Price", "20-Day Moving Average", "Upper Band", "Lower Band"),
       lty = c(1, 1, 2, 2),
       lwd = c(3, 1, 1, 1)) # cex = 0.5 to reduce legend size 

1.6.3 Momentum: Relative Strength Index

options(digits = 2)

# Step 1: Obtain Closing Prices for Amazon.com Stock
AMZN.RSI <- data.AMZN[, 4]
AMZN.RSI$delta <- diff(AMZN.RSI$AMZN.Close)
AMZN.RSI[c(1:3, nrow(AMZN.RSI)), ]
##            AMZN.Close delta
## 2010-12-31        180    NA
## 2011-01-03        184  4.22
## 2011-01-04        185  0.79
## 2013-12-31        399  5.42

# Step 2: Create Dummy Variables to Indicate Whether Price Went Up or Price Went Down
AMZN.RSI$up <- ifelse(AMZN.RSI$delta > 0, 1, 0)
AMZN.RSI$down <- ifelse(AMZN.RSI$delta < 0, 1, 0)
AMZN.RSI[c(1:3, nrow(AMZN.RSI)), ]
##            AMZN.Close delta up down
## 2010-12-31        180    NA NA   NA
## 2011-01-03        184  4.22  1    0
## 2011-01-04        185  0.79  1    0
## 2013-12-31        399  5.42  1    0

# Step 3: Calculate Prices for Up Days and Prices for Down Days
AMZN.RSI$up.val <- AMZN.RSI$delta * AMZN.RSI$up
AMZN.RSI$down.val <- -AMZN.RSI$delta * AMZN.RSI$down
AMZN.RSI <- AMZN.RSI[-1, ]
AMZN.RSI[c(1:3, nrow(AMZN.RSI)), ]
##            AMZN.Close delta up down up.val down.val
## 2011-01-03        184  4.22  1    0   4.22        0
## 2011-01-04        185  0.79  1    0   0.79        0
## 2011-01-05        187  2.41  1    0   2.41        0
## 2013-12-31        399  5.42  1    0   5.42        0

# Step 4: Calcualte Initial Up and Down 14-Day Averages
AMZN.RSI$up.first.avg <- rollapply(AMZN.RSI$up.val, 
                                   width = 14, FUN = mean, fill = NA, na.rm = TRUE)
AMZN.RSI$down.first.avg <- rollapply(AMZN.RSI$down.val, 
                                   width = 14, FUN = mean, fill = NA, na.rm = TRUE)
AMZN.RSI[c(1:15, nrow(AMZN.RSI)), ]
##            AMZN.Close delta up down up.val down.val up.first.avg
## 2011-01-03        184  4.22  1    0   4.22     0.00           NA
## 2011-01-04        185  0.79  1    0   0.79     0.00           NA
## 2011-01-05        187  2.41  1    0   2.41     0.00           NA
## 2011-01-06        186 -1.56  0    1   0.00     1.56           NA
## 2011-01-07        185 -0.37  0    1   0.00     0.37           NA
## 2011-01-10        185 -0.81  0    1   0.00     0.81           NA
## 2011-01-11        184 -0.34  0    1   0.00     0.34           NA
## 2011-01-12        184 -0.26  0    1   0.00     0.26           NA
## 2011-01-13        186  1.45  1    0   1.45     0.00           NA
## 2011-01-14        189  3.22  1    0   3.22     0.00           NA
## 2011-01-18        191  2.50  1    0   2.50     0.00           NA
## 2011-01-19        187 -4.38  0    1   0.00     4.38           NA
## 2011-01-20        182 -4.91  0    1   0.00     4.91           NA
## 2011-01-21        177 -4.54  0    1   0.00     4.54         1.04
## 2011-01-24        177 -0.57  0    1   0.00     0.57         0.74
## 2013-12-31        399  5.42  1    0   5.42     0.00         2.46
##            down.first.avg
## 2011-01-03             NA
## 2011-01-04             NA
## 2011-01-05             NA
## 2011-01-06             NA
## 2011-01-07             NA
## 2011-01-10             NA
## 2011-01-11             NA
## 2011-01-12             NA
## 2011-01-13             NA
## 2011-01-14             NA
## 2011-01-18             NA
## 2011-01-19             NA
## 2011-01-20             NA
## 2011-01-21            1.2
## 2011-01-24            1.3
## 2013-12-31            1.7

# Step 5: Calculate the Wilder Exponential Moving Average to Cacluate final Up and Down 14-D Avg
# up.avg = up.first.avg, except that, instead of giving all up.val the weight of 1/14,
# up.avg has the weight schemes such that 13/14 * up.first.avg(t-1) + 1/14 * up.val (t)
# or, (13 * (1/14*(up.val(t-14)+up.val(t-13) +...+ up.val(t-2)+up.val(t-1))) + up.val(t)) / 14
# So up.avg is different than up.first.avg in that:
# up.val gets the weight (1 * 1/14) greater than 
# up.val of (t-1 through t-14) that has weight of (13/14 * 1/14)

up.val <- as.numeric(AMZN.RSI$up.val)
down.val <- as.numeric(AMZN.RSI$down.val)

AMZN.RSI$up.avg <- AMZN.RSI$up.first.avg
for (i in 15:nrow(AMZN.RSI)) {
  AMZN.RSI$up.avg[i] <- (AMZN.RSI$up.avg[i-1]*13 + up.val[i]) / 14
}

AMZN.RSI$down.avg <- AMZN.RSI$down.first.avg
for (i in 15:nrow(AMZN.RSI)) {
  AMZN.RSI$down.avg[i] <- (AMZN.RSI$down.avg[i-1]*13 + down.val[i]) / 14
}

AMZN.RSI[c(1:20, nrow(AMZN.RSI)), ]
##            AMZN.Close  delta up down up.val down.val up.first.avg
## 2011-01-03        184   4.22  1    0   4.22     0.00           NA
## 2011-01-04        185   0.79  1    0   0.79     0.00           NA
## 2011-01-05        187   2.41  1    0   2.41     0.00           NA
## 2011-01-06        186  -1.56  0    1   0.00     1.56           NA
## 2011-01-07        185  -0.37  0    1   0.00     0.37           NA
## 2011-01-10        185  -0.81  0    1   0.00     0.81           NA
## 2011-01-11        184  -0.34  0    1   0.00     0.34           NA
## 2011-01-12        184  -0.26  0    1   0.00     0.26           NA
## 2011-01-13        186   1.45  1    0   1.45     0.00           NA
## 2011-01-14        189   3.22  1    0   3.22     0.00           NA
## 2011-01-18        191   2.50  1    0   2.50     0.00           NA
## 2011-01-19        187  -4.38  0    1   0.00     4.38           NA
## 2011-01-20        182  -4.91  0    1   0.00     4.91           NA
## 2011-01-21        177  -4.54  0    1   0.00     4.54         1.04
## 2011-01-24        177  -0.57  0    1   0.00     0.57         0.74
## 2011-01-25        177  -0.15  0    1   0.00     0.15         0.68
## 2011-01-26        175  -1.31  0    1   0.00     1.31         0.51
## 2011-01-27        184   9.06  1    0   9.06     0.00         1.16
## 2011-01-28        171 -13.31  0    1   0.00    13.31         1.16
## 2011-01-31        170  -1.50  0    1   0.00     1.50         1.16
## 2013-12-31        399   5.42  1    0   5.42     0.00         2.46
##            down.first.avg up.avg down.avg
## 2011-01-03             NA     NA       NA
## 2011-01-04             NA     NA       NA
## 2011-01-05             NA     NA       NA
## 2011-01-06             NA     NA       NA
## 2011-01-07             NA     NA       NA
## 2011-01-10             NA     NA       NA
## 2011-01-11             NA     NA       NA
## 2011-01-12             NA     NA       NA
## 2011-01-13             NA     NA       NA
## 2011-01-14             NA     NA       NA
## 2011-01-18             NA     NA       NA
## 2011-01-19             NA     NA       NA
## 2011-01-20             NA     NA       NA
## 2011-01-21            1.2   1.04      1.2
## 2011-01-24            1.3   0.97      1.2
## 2011-01-25            1.3   0.90      1.1
## 2011-01-26            1.4   0.83      1.1
## 2011-01-27            1.3   1.42      1.0
## 2011-01-28            2.2   1.32      1.9
## 2011-01-31            2.2   1.23      1.9
## 2013-12-31            1.7   2.58      1.7

# Step 6: Calculate the RSI
# Note that:
# if up.avg = down.avg, RS = 1, and thus RSI = 50
# if up.avg > down.avg, RS > 1, and thus RSI > 50 (indicative of market where demand > supply)
# if up.avg < down.avg, RS < 1, and thus RSI < 50 (indicative of market where demand < supply)

AMZN.RSI$RS <- AMZN.RSI$up.avg / AMZN.RSI$down.avg
AMZN.RSI$RSI <- 100 - (100 / (1 + AMZN.RSI$RS))
AMZN.RSI[c(14:20, nrow(AMZN.RSI)), ]
##            AMZN.Close  delta up down up.val down.val up.first.avg
## 2011-01-21        177  -4.54  0    1    0.0     4.54         1.04
## 2011-01-24        177  -0.57  0    1    0.0     0.57         0.74
## 2011-01-25        177  -0.15  0    1    0.0     0.15         0.68
## 2011-01-26        175  -1.31  0    1    0.0     1.31         0.51
## 2011-01-27        184   9.06  1    0    9.1     0.00         1.16
## 2011-01-28        171 -13.31  0    1    0.0    13.31         1.16
## 2011-01-31        170  -1.50  0    1    0.0     1.50         1.16
## 2013-12-31        399   5.42  1    0    5.4     0.00         2.46
##            down.first.avg up.avg down.avg   RS RSI
## 2011-01-21            1.2   1.04      1.2 0.85  46
## 2011-01-24            1.3   0.97      1.2 0.82  45
## 2011-01-25            1.3   0.90      1.1 0.81  45
## 2011-01-26            1.4   0.83      1.1 0.74  43
## 2011-01-27            1.3   1.42      1.0 1.37  58
## 2011-01-28            2.2   1.32      1.9 0.69  41
## 2011-01-31            2.2   1.23      1.9 0.65  39
## 2013-12-31            1.7   2.58      1.7 1.56  61

# Step 7: Subset to Show Only 2012 and 2013 Data
AMZN.RSI2012 <- subset(AMZN.RSI[, ncol(AMZN.RSI)],
                       index(AMZN.RSI) >= "2012-01-01")
AMZN.RSI2012[c(1:3, nrow(AMZN.RSI2012)), ]
##            RSI
## 2012-01-03  43
## 2012-01-04  41
## 2012-01-05  41
## 2013-12-31  61

# Step 8: Plot the RSI
# buy signal if the RSI rises from below the oversold line (at 30)
# sell signal if the RsI falls from above the overbought line (at 70)
# Why?
# See the rationale in Step 6. 
# Simply put, 30 and 70 represent turning points.

title1 <- "Amazon - Relative Strength Index"
title2 <- "January 2012 - December 2013"
plot(x = index(AMZN.RSI2012),
     y = AMZN.RSI2012$RSI,
     xlab = "Date",
     ylab = "14-Day Moving Average)",
     ylim = c(0, 100),
     type = "l",
     main = paste(title1, "\n", title2))
abline(h = c(30, 70), lty = 2)