Create a line chart with both the daily and 7-day moving average for the close price for Apple stock. You can download a CSV with the current prices from Yahoo APPL.
library(tidyverse) # for data wrangling
library(zoo) # for using the rollmean function
library(lubridate) # for dates
library(plotly) # for making interactive charts
# This was fetched from Yahoo
# Get the data from the link: https://finance.yahoo.com/quote/AAPL/history/?guccounter=1
aapl <- read_csv("AAPL.csv")
glimpse(aapl) #looking at the structure of the data
## Observations: 1,259
## Variables: 7
## $ Date <chr> "2/24/2014", "2/25/2014", "2/26/2014", "2/27/2014"...
## $ Open <dbl> 74.73572, 75.62572, 74.80143, 73.87714, 75.58285, ...
## $ High <dbl> 75.70286, 75.65286, 75.00000, 75.54000, 76.10714, ...
## $ Low <dbl> 74.63143, 74.42857, 73.65714, 73.72143, 74.58857, ...
## $ Close <dbl> 75.36429, 74.58000, 73.90714, 75.38143, 75.17714, ...
## $ `Adj Close` <dbl> 66.64329, 65.94975, 65.35475, 66.65845, 66.47778, ...
## $ Volume <int> 72227400, 57988000, 69054300, 75470500, 92992200, ...
aapl <- aapl %>%
mutate(Date = mdy(Date)) #using the mdy from lubridate
glimpse(aapl)
## Observations: 1,259
## Variables: 7
## $ Date <date> 2014-02-24, 2014-02-25, 2014-02-26, 2014-02-27, 2...
## $ Open <dbl> 74.73572, 75.62572, 74.80143, 73.87714, 75.58285, ...
## $ High <dbl> 75.70286, 75.65286, 75.00000, 75.54000, 76.10714, ...
## $ Low <dbl> 74.63143, 74.42857, 73.65714, 73.72143, 74.58857, ...
## $ Close <dbl> 75.36429, 74.58000, 73.90714, 75.38143, 75.17714, ...
## $ `Adj Close` <dbl> 66.64329, 65.94975, 65.35475, 66.65845, 66.47778, ...
## $ Volume <int> 72227400, 57988000, 69054300, 75470500, 92992200, ...
ggplot(aapl, aes(x = Date, y = Close))+
geom_line(color = "red")+
theme_classic()+
labs(x = "Date", y = "Close Price($)" , title = "Apple Stock Price")+
theme(plot.title = element_text(hjust = 0.5))#move title to centre
aapl <- aapl %>%
mutate(close_5 = rollmean(x = Close, # column to take
k = 5, # rolling time period
align = "right", #leave values above the top
fill = NA),
close_30 = rollmean(x = Close,
k = 30,
align = "right",
fill = NA)) # fill the missing with NA))
ggplotly(ggplot(aapl, aes(x = Date))+
geom_line(aes(y = Close), color = "blue")+
geom_line(aes(y = close_5), color = "brown")+
geom_line(aes(y = close_30), color = "darkgreen")+
theme_classic()+
labs(x = "Date", y = "Price($)" , title = "Apple Stock Price (Close and Moving Average)")+
theme(plot.title = element_text(hjust = 0.5)))#move title to centre %>%