In this exercise you will learn to plot data using the ggplot2 package. To answer the questions below, use Chapter 4.3 Categorical vs. Quantitative Data Visualization with R.
# Load packages
library(tidyquant)
library(tidyverse)
# Import stock prices
stock_prices <- tq_get(c("AAPL", "MSFT"), get = "stock.prices", from = "2020-01-01")
# Calculate daily returns
stock_returns <-
stock_prices %>%
group_by(symbol) %>%
tq_mutate(select = adjusted, mutate_fun = periodReturn, period = "daily")
stock_returns
Hint: See the code in 4.3.2 Grouped kernel density plots.
ggplot(stock_returns,
aes(x = daily.returns,
fill = symbol)) +
geom_density(alpha = 0.4) +
labs(title = "Daily return distribution by stock")
Hint: See the code in 4.3.3 Box plots. Use the same title as in the density plot.
ggplot(stock_returns,
aes(x = symbol,
y = daily.returns)) +
geom_boxplot() +
labs(title = "Daily return distribution by stock")
Hint: Discuss your answer based on median, the middle 50%, roughly 99% of the data, and outliers.
I believe that it would be smart to invest in Microsoft over Apple based off of this box plot. It appears that the median for Microsoft on daily returns is slighty higher than that of Apple. Apple also has two outliers that lie very low on the plot meaning that it is more likely to get a negative outcome with Apple.
Hint: See the code in 4.3.1 Bar chart (on summary statistics).
library(dplyr)
plotdata <- stock_returns %>%
group_by(symbol) %>%
summarize(mean_return = mean(daily.returns))
plotdata
Hint: See the code in 4.3.1 Bar chart (on summary statistics).
ggplot(plotdata,
aes(x = symbol,
y = mean_return)) +
geom_bar(stat = "identity")
Hint: See the code in 4.3.1 Bar chart (on summary statistics).
ggplot(plotdata,
aes(x = symbol,
y = mean_return)) +
geom_bar(stat = "identity",
fill = "cornflowerblue")
Hint: See the code in 4.3.1 Bar chart (on summary statistics).
library(scales)
ggplot(plotdata,
aes(x = symbol,
y = mean_return)) +
geom_bar(stat = "identity",
fill = "cornflowerblue") +
geom_text(aes(label = percent(mean_return)),
vjust = -0.25)
Hint: Use message, echo and results in the chunk options. Refer to the RMarkdown Reference Guide.