Indira Fouch
2022-12-09
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6 ✔ purrr 0.3.4
## ✔ tibble 3.1.8 ✔ dplyr 1.0.10
## ✔ tidyr 1.2.1 ✔ stringr 1.4.1
## ✔ readr 2.1.2 ✔ forcats 0.5.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## Linking to GEOS 3.9.1, GDAL 3.4.3, PROJ 7.2.1; sf_use_s2() is TRUE
##
## Attaching package: 'scales'
##
## The following object is masked from 'package:purrr':
##
## discard
##
## The following object is masked from 'package:readr':
##
## col_factor
## Warning: package 'tidytuesdayR' was built under R version 4.2.2
## Warning: package 'gganimate' was built under R version 4.2.2
## Warning: package 'gifski' was built under R version 4.2.2
## Warning: package 'av' was built under R version 4.2.2
## Warning: package 'plotly' was built under R version 4.2.2
##
## Attaching package: 'plotly'
##
## The following object is masked from 'package:ggplot2':
##
## last_plot
##
## The following object is masked from 'package:stats':
##
## filter
##
## The following object is masked from 'package:graphics':
##
## layout
## Date Open High Low
## Length:44 Min. :361.8 Min. :365.9 Min. :357.0
## Class :character 1st Qu.:389.4 1st Qu.:392.9 1st Qu.:386.9
## Mode :character Median :403.3 Median :406.7 Median :401.8
## Mean :401.0 Mean :403.8 Mean :397.6
## 3rd Qu.:415.2 3rd Qu.:417.3 3rd Qu.:412.0
## Max. :427.7 Max. :431.7 Max. :426.9
## Close Adj.Close Volume
## Min. :357.2 Min. :357.2 Min. : 44931800
## 1st Qu.:389.7 1st Qu.:388.5 1st Qu.: 61143300
## Median :404.0 Median :402.3 Median : 74654100
## Mean :400.4 Mean :399.1 Mean : 78214218
## 3rd Qu.:413.8 3rd Qu.:412.1 3rd Qu.: 90249750
## Max. :429.7 Max. :427.9 Max. :153396100
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
final1 <- test %>%
ggplot(aes(x = Close, y = Date)) +
geom_col(position = "dodge2") +
labs(x = "Close",y = "Date") +
theme(legend.position = "top")
final1
getSymbols() creates an object called SPY, class xts allows storing time
series data or time based indexing, allowing multiple time series, often
related, getting same time index to be stored in the same object.
Yahoo! Finance provides six indicators for each stock. Open is the price of the stock at the beginning of the trading day (can be different than closing price of previous trading day), high is the highest price of the stock had that opne mrket day, low, and close the price of the stock at closing time. Volume indicates how many stocks were traded.
A linechart is fine, but there are at least four variables involved for each date (open, high, low, and close), so having a visual way to see all that does not require plotting four separate lines is what we often see used on popular trading platforms. Patterns detected can change trading decisions, depending on the shape, color, and position of the candles. I will not cover such strategies today.
With a candlestick chart, a green 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. Candlestick charts are popular in finance and some strategies in technical analysis use them to make
## Warning: package 'quantmod' was built under R version 4.2.2
## Loading required package: xts
## Warning: package 'xts' was built under R version 4.2.2
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
##
## Attaching package: 'xts'
## The following objects are masked from 'package:dplyr':
##
## first, last
## Loading required package: TTR
## Warning: package 'TTR' was built under R version 4.2.2
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
## Skipping install of 'quantstrat' from a github remote, the SHA1 (c3e729b1) has not changed since last install.
## Use `force = TRUE` to force installation
## Loading required package: blotter
## Loading required package: FinancialInstrument
## Warning: package 'FinancialInstrument' was built under R version 4.2.2
##
## Attaching package: 'FinancialInstrument'
## The following object is masked from 'package:tidyr':
##
## spread
## Loading required package: PerformanceAnalytics
## Warning: package 'PerformanceAnalytics' was built under R version 4.2.2
##
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
##
## legend
## Loading required package: foreach
## Warning: package 'foreach' was built under R version 4.2.2
##
## Attaching package: 'foreach'
## The following objects are masked from 'package:purrr':
##
## accumulate, when
# Dates
start <- "2022-01-01"
end <- "2022-12-01"
getSymbols("SPY",from = start, to = end,src='yahoo')## [1] "SPY"
## [1] "xts" "zoo"
## SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
## 2022-01-03 476.30 477.85 473.85 477.71 72668200 472.2423
## 2022-01-04 479.22 479.98 475.58 477.55 71178700 472.0841
## 2022-01-05 477.16 477.98 468.28 468.38 104538900 463.0191
## 2022-01-06 467.89 470.82 465.43 467.94 86858900 462.5841
## 2022-01-07 467.95 469.20 464.65 466.09 85111600 460.7553
## 2022-01-10 462.70 465.74 456.60 465.51 119362000 460.1819
chartSeries(SPY,
theme = chartTheme("black"),
name = "SPY",
TA = list("addBBands(n = 10)",
"addVo()",
"addEMA(20)",
"addEMA(10, col = 2)"))# Custom theme
myTheme <- chart_theme()
myTheme$col$dn.col <- "pink"
myTheme$col$dn.border <- "pink"
myTheme$col$up.col <- "green"
myTheme$col$up.border <- "green"
myTheme$rylab <- TRUE
myTheme$lylab <- FALSE
# Plot the data
chart_Series(SPY, theme = myTheme)#Stock Candlesticks
final3 <- test %>% plot_ly(x = ~Date, type="candlestick",
open = ~Open, close = ~Close,
high = ~High, low = ~Low)
final3 <- final3 %>% layout(title = "Candlestick Chart with slider")
final3##Candlestick without slider
final2 <- test %>% plot_ly(x = ~Date, type="candlestick",
open = ~Open, close = ~Close,
high = ~High, low = ~Low)
final2 <- final2 %>% layout(title = "Candlestick without slider",
xaxis = list(rangeslider = list(visible = F)))
final2##Custom figure,shapes and annotations
a <- list(text = "Stock Split",
x = '2014-06-06',
y = 1.02,
xref = 'x',
yref = 'paper',
xanchor = 'left',
showarrow = FALSE
)
# use shapes to create a line
l <- list(type = line,
x0 = '2022-10-01',
x1 = '2022-10-01',
y0 = 0,
y1 = 1,
xref = 'x',
yref = 'paper',
line = list(color = 'black',
width = 0.5)
)
fig <- final4 <- test %>% plot_ly(x = ~Date, type="candlestick",
open = ~Open, close = ~Close,
high = ~High, low = ~Low)
fig <- fig %>% layout(title = "SPY Stock",
annotations = a,
shapes = l)
fig## Add a Trace to Candlestick Chart
df <- data.frame(Date=index(SPY),coredata(SPY))
df <- tail(df, 365)
fig1 <- df %>% plot_ly(x = ~Date, type="candlestick",
open = ~SPY.Open, close = ~SPY.Close,
high = ~SPY.High, low = ~SPY.Low)
fig1 <- fig1 %>% add_lines(x = ~Date, y = ~SPY.Open, line = list(color = 'black', width = 0.75), inherit = F)
fig1 <- fig1 %>% layout(showlegend = FALSE)
fig1## [1] "AAPL"
df <- data.frame(Date=index(AAPL),coredata(AAPL))
# create Bollinger Bands
bbands <- BBands(AAPL[,c("AAPL.High","AAPL.Low","AAPL.Close")])
# join and subset data
df <- subset(cbind(df, data.frame(bbands[,1:3])), Date >= "2015-02-14")
# colors column for increasing and decreasing
for (i in 1:length(df[,1])) {
if (df$AAPL.Close[i] >= df$AAPL.Open[i]) {
df$direction[i] = 'Increasing'
} else {
df$direction[i] = 'Decreasing'
}
}
i <- list(line = list(color = '#17BECF'))
d <- list(line = list(color = '#7F7F7F'))
# plot candlestick chart
fig <- df %>% plot_ly(x = ~Date, type="candlestick",
open = ~AAPL.Open, close = ~AAPL.Close,
high = ~AAPL.High, low = ~AAPL.Low, name = "AAPL",
increasing = i, decreasing = d)
fig <- fig %>% add_lines(x = ~Date, y = ~up , name = "B Bands",
line = list(color = '#ccc', width = 0.5),
legendgroup = "Bollinger Bands",
hoverinfo = "none", inherit = F)
fig <- fig %>% add_lines(x = ~Date, y = ~dn, name = "B Bands",
line = list(color = '#ccc', width = 0.5),
legendgroup = "Bollinger Bands", inherit = F,
showlegend = FALSE, hoverinfo = "none")
fig <- fig %>% add_lines(x = ~Date, y = ~mavg, name = "Mv Avg",
line = list(color = '#E377C2', width = 0.5),
hoverinfo = "none", inherit = F)
fig <- fig %>% layout(yaxis = list(title = "Price"))
# plot volume bar chart
fig2 <- df
fig2 <- fig2 %>% plot_ly(x=~Date, y=~AAPL.Volume, type='bar', name = "AAPL Volume",
color = ~direction, colors = c('#17BECF','#7F7F7F'))
fig2 <- fig2 %>% layout(yaxis = list(title = "Volume"))
# create rangeselector buttons
rs <- list(visible = TRUE, x = 0.5, y = -0.055,
xanchor = 'center', yref = 'paper',
font = list(size = 9),
buttons = list(
list(count=1,
label='RESET',
step='all'),
list(count=1,
label='1 YR',
step='year',
stepmode='backward'),
list(count=3,
label='3 MO',
step='month',
stepmode='backward'),
list(count=1,
label='1 MO',
step='month',
stepmode='backward')
))
# subplot with shared x axis
fig <- subplot(fig, fig2, heights = c(0.7,0.2), nrows=2,
shareX = TRUE, titleY = TRUE)
fig <- fig %>% layout(title = paste("Apple: 2015-02-14 -",Sys.Date()),
xaxis = list(rangeselector = rs),
legend = list(orientation = 'h', x = 0.5, y = 1,
xanchor = 'center', yref = 'paper',
font = list(size = 10),
bgcolor = 'transparent'))
fig