In this Apply it to your data assignment, I applied lessons from Chapters 1–3 of R for Data Science to financial market data. I decided to select three securities: Apple (AAPL), Microsoft (MSFT), and the S&P 500 ETF (SPY). These represent two major tech firms and a broad market benchmark.The goal is to compare stock prices, returns, and volatility using visualization and data transformation.
# Install if missing:
# install.packages(c("tidyquant","dplyr","ggplot2","rmarkdown","knitr"))
library(tidyquant)
library(dplyr)
library(ggplot2)
tickers <- c("AAPL", "MSFT", "SPY")
stock_data <- tq_get(tickers,
from = "2024-01-01",
to = Sys.Date(),
get = "stock.prices")
head(stock_data)
## # A tibble: 6 × 8
## symbol date open high low close volume adjusted
## <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 AAPL 2024-01-02 187. 188. 184. 186. 82488700 184.
## 2 AAPL 2024-01-03 184. 186. 183. 184. 58414500 183.
## 3 AAPL 2024-01-04 182. 183. 181. 182. 71983600 180.
## 4 AAPL 2024-01-05 182. 183. 180. 181. 62379700 180.
## 5 AAPL 2024-01-08 182. 186. 182. 186. 59144500 184.
## 6 AAPL 2024-01-09 184. 185. 183. 185. 42841800 184.
returns <- stock_data %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
col_rename = "monthly_returns")
head(returns)
## # A tibble: 6 × 3
## # Groups: symbol [1]
## symbol date monthly_returns
## <chr> <date> <dbl>
## 1 AAPL 2024-01-31 -0.00668
## 2 AAPL 2024-02-29 -0.0185
## 3 AAPL 2024-03-28 -0.0513
## 4 AAPL 2024-04-30 -0.00671
## 5 AAPL 2024-05-31 0.130
## 6 AAPL 2024-06-28 0.0956
summary_stats <- returns %>%
group_by(symbol) %>%
summarize(mean_return = mean(monthly_returns, na.rm = TRUE),
sd_return = sd(monthly_returns, na.rm = TRUE))
summary_stats
## # A tibble: 3 × 3
## symbol mean_return sd_return
## <chr> <dbl> <dbl>
## 1 AAPL 0.0131 0.0578
## 2 MSFT 0.0166 0.0623
## 3 SPY 0.0167 0.0323
ggplot(stock_data, aes(x = date, y = adjusted, color = symbol)) +
geom_line(size = 1) +
labs(title = "Stock Prices (AAPL, MSFT, SPY)",
x = "Date", y = "Adjusted Closing Price",
color = "Symbol") +
theme_minimal()
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
ggplot(returns, aes(x = date, y = monthly_returns, fill = symbol)) +
geom_col(position = "dodge") +
labs(title = "Monthly Returns by Stock",
x = "Date", y = "Return",
fill = "Symbol") +
theme_minimal()
From this analysis, I took that AAPL and MSFT had higher monthly returns but also had a greater volatility compared to SPY. The ETF SPY offered more stable performance with lower fluctuations I noticed.This demonstrates the trade-off between risk and return which means individual growth stocks may provide higher gains but with higher uncertainty, while diversified funds provide more steady results.
tidyquant
package.This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
summary(cars)
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
You can also embed plots, for example:
Note that the echo = FALSE
parameter was added to the
code chunk to prevent printing of the R code that generated the
plot.