Personal Quantitative Analysis Journal

Can R Fix My IRA Account? — Day 2

My chronological journey to getting R to invest in the market for me: Plotting using ggplot (line) and plotly (candlestick)

Cindy S. Cheung
6 min readJul 8, 2019

NOTE: This is for absolute beginners.

Photo by Chris Li on Unsplash

Ok, so I don’t know what happened, but when I opened my R script today, it stopped working. Overnight!

Argh!

It mentioned that Rtools was missing. It didn’t say that yesterday!

I restarted RStudio, and it worked again?!

Fine.

Alright, now that I extracted RACE, the Ferrari stock data, I could finally take a look at it. Let’s start off where I ended on Day 1…

Exploratory Data Analysis of RACE

Describe the structure

> str(RACE)
An ‘xts’ object on 2015–10–21/2019–06–11 containing:
Data: num [1:915, 1:6] 60 57.1 57.8 57 54.8 …
— attr(*, “dimnames”)=List of 2
..$ : NULL
..$ : chr [1:6] “RACE.Open” “RACE.High” “RACE.Low” “RACE.Close” …
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 2
$ src : chr “yahoo”
$ updated: POSIXct[1:1], format: “2019–06–12 16:36:47”
> head(RACE)
RACE.Open RACE.High RACE.Low RACE.Close RACE.Volume RACE.Adjusted
2015–10–21 60.00 60.97 55.000 55.00 22425300 53.13913
2015–10–22 57.07 58.20 55.700 56.75 4545100 54.82992
2015–10–23 57.77 58.00 56.270 56.38 1967600 54.47243
2015–10–26 57.00 57.00 54.535 55.02 1466200 53.15845
2015–10–27 54.80 54.99 49.360 53.85 5949200 52.02803
2015–10–28 54.02 54.16 50.100 51.87 2411300 50.11503

So it’s a xts object. It included 915 rows and 6 columns. From what I can tell, that meant the data showed 915 days of stock prices and 6 stock variables: opening price, high price, low price, closing price, volume, and adjusted closing price.

It also indicated that the time zone is UTC, coordinated universal time. So the time stamp in the data is either seven hours ahead during daylight savings or eight hours ahead during non-daylight savings from where I live…?

Let’s see if I could plot one of the more important price points, the closing prices.

Plot the Closing Price with ggplot

I didn’t want to simply use R’s base plot command, so I installed ggplot2.

install.packages(‘ggplot2’)

Since I only wanted the closing price, I went ahead and subset that column, which produced another xts object indexed by date. To make it things cleaner for later calculations, I separated the date index to a date variable and the closing price to a price list.

close <- Cl(RACE)
Date <- index(close)
Price <- coredata(close)
> str(close)
An ‘xts’ object on 2015–10–21/2019–06–27 containing:
Data: num [1:927, 1] 55 56.8 56.4 55 53.8 …
— attr(*, “dimnames”)=List of 2
..$ : NULL
..$ : chr “RACE.Close”
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 2
$ src : chr “yahoo”
$ updated: POSIXct[1:1], format: “2019–06–28 18:53:39”
> str(Date)
Date[1:927], format: "2015-10-21" "2015-10-22" "2015-10-23" "2015-10-26" "2015-10-27" "2015-10-28" "2015-10-29" "2015-10-30" ...
> str(Price)
num [1:927, 1] 55 56.8 56.4 55 53.8 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr "RACE.Close"

Now I was ready to plot the closing price of RACE.

ggplot(close, aes(x = Date, y = Price)) + 
geom_line() +
labs(title = “Closing Price of RACE”, x = “Date”, y = “Price”)

The resulting plot looked like this.

First thing I noticed, I missed the boat on this one. Second, based on initial technical stock chart analysis, there were some obvious resistance and support levels at $40, $50, $100, $120, and $140.

I could work with this, but I really wanted something I was more used to: a candlestick chart.

Plot RACE in a Candlestick Chart

I googled for how to do a candlestick chart, and was told to use the plotly package. So I installed it.

install.packages(‘plotly’)

This was when trouble came knocking.

Several websites state that I needed to do the following for a candlestick chart:

data.frame(date = index(RACE), coredata(RACE)) %>%
plot_ly(x = ~Date, type = “candlestick”,
open = ~RACE.Open, close = ~RACE.Close,
high = ~RACE.High, low = ~RACE.Low) %>%
layout(title = “Candlestick Chart of RACE”)

But an error abruptly stopped me on my tracks.

Error: Trace type must be one of the following:
‘scatter’, ‘bar’, ‘box’, ‘heatmap’, ‘histogram’, ‘histogram2d’, ‘histogram2dcontour’, ‘pie’, ‘contour’, ‘scatter3d’, ‘surface’, ‘mesh3d’, ‘scattergeo’, ‘choropleth’, ‘scattergl’, ‘scatterternary’, ‘scattermapbox’, ‘area’

What?! But the internet said to use plotly!

I scoured the internet again and found out the newest version of plotly was 4.9.0, but I had 4.5.2. That explained it.

So I tried to install the newest development version as instructed:

devtools::install_github(“ropensci/plotly”)

However, when I did that, a new error popped up:

> devtools::install_github(“ropensci/plotly”)
Downloading GitHub repo ropensci/plotly@master
from URL https://api.github.com/repos/ropensci/plotly/zipball/master
Installing plotly
“C:/PROGRA~1/MICROS~3/RCLIEN~1/R_SERVER/bin/x64/R” — no-site-file — no-environ — no-save — no-restore — quiet CMD \
INSTALL “C:/Users/cinji/AppData/Local/Temp/RtmpMNgiEt/devtools27f029a57c1a/ropensci-plotly-2cc296d” \
— library=”C:/Users/cinji/OneDrive/Documents/R/win-library/3.3" — install-tests
ERROR: dependencies ‘rlang’, ‘crosstalk’, ‘promises’ are not available for package ‘plotly’
* removing ‘C:/Users/cinji/OneDrive/Documents/R/win-library/3.3/plotly’
Error: Command failed (1)

Several more painstaking minutes landed me on Stack Overflow, the online forum for developers. I had the account years ago, but I abandoned it for — let’s just say — unhelpful negative comments. Sadly, I did not have a chose at this point, so I posted the question.

One person suggested I do:

install.packages(c('rlang', 'crosstalk', 'promises'))

Which got me this error:

> install.packages(c('rlang', 'crosstalk', 'promises'))
WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:

https://cran.rstudio.com/bin/windows/Rtools/
Installing packages into ‘C:/Users/cinji/OneDrive/Documents/R/win-library/3.3’
(as ‘lib’ is unspecified)
Warning in install.packages :
packages ‘rlang’, ‘crosstalk’, ‘promises’ are not available (for R version 3.3.2)

Huh? Did this mean I had a really old version of R? This didn’t make sense to me because I had just installed the updated version a couple weeks earlier.

I checked the About window in RStudio, and I did, in fact, had the latest version 1.2.1335. Yet, the Stack Overflow person said there was a 3.6.0 release. Huh?

After much confusion, I figured out that he meant the underlying R software, not RStudio. I had always thought they had the same version numbering. I guess I was wrong.

I downloaded the latest version of R, which was 3.6.0 from CRAN, and tried everything again.

devtools::install_github(“ropensci/plotly”)

It worked.

I checked the version:

> packageVersion(‘plotly’)
[1] ‘4.9.0’

Now, I re-executed the plot:

data.frame(date = index(RACE), coredata(RACE)) %>%
plot_ly(x = ~Date, type = “candlestick”,
open = ~RACE.Open, close = ~RACE.Close,
high = ~RACE.High, low = ~RACE.Low) %>%
layout(title = “Candlestick Chart of RACE”)

It compiled!

Finally, after much pain, it produced this graph:

Sigh.

On to the next thing.

Takeaway Lesson

Always check if I have the latest version of both RStudio AND R.

Entire Script So Far

I finally got my scripts uploaded into GitHub.

####################################################################
# Creator: Cindy S Cheung
# Script Name: RQuantAnalytics
# Purpose: This is the first R script in learning how to use R to
# evaluate stock investment. This is the core script at its
# first stages, so there are no functions yet.
# Version: 1.0
####################################################################
####################################################################
# Install packages needed to be used in script
####################################################################
# For data manipulaton in data frame objects
install.packages(‘dplyr’)
# Make package development easier — needed this to update quantmod
# to work with the current Yahoo server. Otherwise, quantmod cannot
# download data from Yahoo. Also needed this to update plotly to
# plot candlestick charts.
install.packages(‘devtools’)
# Quantitative Financial Modeling Framework Package includes most
# trading functions and strategies
# Update quandmod to the development version created by J. Ulrich
devtools::install_github(“joshuaulrich/quantmod”)
# For data visualization
install.packages(‘ggplot2’)
# For plotting candlesticks
# Update plotly to the development version created by rOpenSci
devtools::install_github(“ropensci/plotly”)
####################################################################
# Load package libraries
####################################################################
library(dplyr)
library(devtools)
library(quantmod)
library(ggplot2)
library(plotly)
####################################################################
# Set directory
####################################################################
work_dir <- “C:/Users/cinji/OneDrive/Quantitative Analytics”
setwd(work_dir)
####################################################################
# Extract stock price data of Ferrari from Yahoo
####################################################################
getSymbols(“RACE”, src = “yahoo”, auto.assign = TRUE)
####################################################################
# Exploratory Data Analysis
####################################################################
# Examine structure of the stock
str(RACE)
# Show the first 5 rows of the data
head(RACE)
# Extract closing price of the stock
close <- Cl(RACE)
Date <- index(close)
Price <- coredata(close)
# Plot the closing price of the stock
ggplot(close, aes(x = Date, y = Price)) +
geom_line() +
labs(title = “Closing Price of RACE”,
x = “Date”,
y = “Price”)
# Plot candlestick chart for RACE
data.frame(date = index(RACE), coredata(RACE)) %>%
plot_ly(x = ~Date, type = “candlestick”,
open = ~RACE.Open, close = ~RACE.Close,
high = ~RACE.High, low = ~RACE.Low) %>%
layout(title = “Candlestick Chart of RACE”)

To be continued…

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Cindy S. Cheung
Cindy S. Cheung

Written by Cindy S. Cheung

Data Analyst. Screenwriter. Project Manager. Now, Resume Coach. A student of life and West Coast Swing. A promoter of self from within. www.sunbreakresumes.com

No responses yet

Write a response