Analytics Vidhya
Published in

Analytics Vidhya

Plot Stock Prices with R

http://www.financialtipsor.com/
  • Prepare the envionment
  • Get the data
  • Plot
  1. Prepare the envionment
install.packages("quantmod")
install.packages("broom"))
library(quantmod)
library(ggplot2)
library(magrittr)
library(broom)
start = as.Date("2020-01-01") 
end = as.Date("2021-01-22")
getSymbols(c("AAPL", "GOOGL", "MSFT","^GSPC"), src = "yahoo", from = start, to = end)
stocks = as.xts(data.frame(A = AAPL[, "AAPL.Adjusted"], 
B = GOOGL[, "GOOGL.Adjusted"], C = MSFT[, "MSFT.Adjusted"],
E = GSPC[,"GSPC.Adjusted"]))
names(stocks) = c("Apple", "Google", "Microsoft","S&P 500")
index(stocks) = as.Date(index(stocks))
stocks_series = tidy(stocks) %>% 

ggplot(aes(x=index,y=value, color=series)) +
labs(title = "Top Three US Tech Comany and S&P 500: Daily Stock Prices January 2020 - January 2021 (1)",

subtitle = "End of Day Adjusted Prices",
caption = " Source: Yahoo Finance") +

xlab("Date") + ylab("Price") +
scale_color_manual(values = c("Red", "Black", "DarkBlue","Orange"))+
geom_line()
stocks_series
stocks_series2 = tidy(stocks) %>% 

ggplot(aes(x=index,y=value, color=series)) +
geom_line() +
facet_grid(series~.,scales = "free") +
labs(title = "Top Three US Tech Comany and S&P 500: Daily Stock Prices January 2020 - January 2021 (2)",

subtitle = "End of Day Adjusted Prices",
caption = " Source: Yahoo Finance") +

xlab("Date") + ylab("Price") +
scale_color_manual(values = c("Red", "Black", "DarkBlue","Orange"))
stocks_series2

--

--

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store