Business Analytics Mini-bootcamp - Summer 2025 (day 2) - Stock Market Data Analysis using quantmod and R

Author

Ryan Whiteford, taught by Zhenning ‘Jimmy’ Xu, Ph.D.

Introduction

This Quarto notebook explores stock market data using R packages like quantmod, PerformanceAnalytics, and tidyverse. We analyze and visualize data for multiple tickers including QQQ, TSLA, LMT, and LMT.

Context: Tools like quantmod are widely used in algorithmic trading platforms and fintech firms. For example:

  • Lemon Markets, a European brokerage API platform, uses similar R-based or Python-based workflows to empower retail and institutional clients.
  • QuantInsti, a leading training provider in algorithmic trading, uses packages like quantmod and PerformanceAnalytics in strategy design, backtesting, and risk analysis.

Load Stock Data

LMT <- getSymbols("LMT", src = "yahoo", from = "2020-01-01", to = "2025-06-01", auto.assign = FALSE)

Reflection Question:

What are some advantages of using programmatic data collection (via getSymbols) over manually downloading CSV files from Yahoo Finance?

Answer

Using programmatic data collection is quicker than manually downloading CSV files; additionally, it allows for you to get the data of multiple stocks at once and will always provide you the most up-to-date stock information as long as the correct dates are typed.

View Sample Data

head(LMT)
           LMT.Open LMT.High LMT.Low LMT.Close LMT.Volume LMT.Adjusted
2020-01-02   392.86   399.37  390.95    399.37    1258400     344.4601
2020-01-03   404.02   417.17  403.00    413.74    2990100     356.8542
2020-01-06   417.99   417.99  407.69    413.11    2477800     356.3108
2020-01-07   411.25   416.12  408.29    414.50    1059900     357.5099
2020-01-08   417.06   418.18  409.72    411.03    1708100     354.5169
2020-01-09   410.49   416.00  410.00    414.93    1064300     357.8806
barChart(LMT, name = "LMT Volume Bar Chart")

chartSeries(LMT, type = "bar", theme = chartTheme("white"))

chartSeries(LMT, type = "line", theme = chartTheme("white"))

chartSeries(LMT, type = "candlesticks", theme = chartTheme("white"))

Reflection Question:

Explore each chart type. How do line, bar, and candlestick charts differ in the kind of information they emphasize?

Answer

The different charts highlight different data. Bar charts show the distinguish between gains and losses on the price of the stock as well as the volatility of the volume being traded, line charts only emphasize the the price of the stock, and candlestick just provides a quick snapshot of how the stock is doing without emphasizing anything.

Daily and Yearly Returns

plot(dailyReturn(LMT), main = "LMT Daily Returns")

plot(yearlyReturn(LMT), main = "LMT Yearly Returns")

Discussion Idea:

QuantInsti trains traders to analyze returns across multiple timeframes. Why might a yearly return plot give a different impression than a daily return plot?

Answer

Long-run return plots - yearly, five-years - provide additional context for how the stock is doing. A day or week return plot may show that the company is doing extremely well when in reality the stock has been performing poorly in the long run. Long-run return plots can also highlight positive and negative events that occured within the company, I.E. a bad CEO being fired may result in an increase in stock price, while a scandal may result in a decrease.

write.table(LMT, file = "LMT_stock.csv", row.names = FALSE, col.names = TRUE, sep = ",")

Convert to Data Frame and Visualize

LMT_df <- data.frame(LMT)
LMT_df$time <- index(LMT)

head(LMT_df)
           LMT.Open LMT.High LMT.Low LMT.Close LMT.Volume LMT.Adjusted
2020-01-02   392.86   399.37  390.95    399.37    1258400     344.4601
2020-01-03   404.02   417.17  403.00    413.74    2990100     356.8542
2020-01-06   417.99   417.99  407.69    413.11    2477800     356.3108
2020-01-07   411.25   416.12  408.29    414.50    1059900     357.5099
2020-01-08   417.06   418.18  409.72    411.03    1708100     354.5169
2020-01-09   410.49   416.00  410.00    414.93    1064300     357.8806
                 time
2020-01-02 2020-01-02
2020-01-03 2020-01-03
2020-01-06 2020-01-06
2020-01-07 2020-01-07
2020-01-08 2020-01-08
2020-01-09 2020-01-09
## Do you still remember the ggplot functions we used yesterday?
ggplot(LMT_df, aes(x = time, y = LMT.Adjusted)) +
  geom_point() +
  labs(title = "LMT Adjusted Closing Price",
       x = "Date", y = "Adjusted Price")

Critical Thinking:

Why might financial analysts prefer adjusted closing prices over raw closing prices when visualizing or modeling stock performance?

Answer

Financial analysts perfer adjusted closing prices because they more accurately reflect the financial position of the company - adjusted closing prices take into account dividends paid or stock splits.

Technical Indicators: Bollinger Bands

What Are Bollinger Bands?

Bollinger Bands are a technical analysis tool used to measure a stock’s price volatility and identify potential buying or selling opportunities.

They consist of three lines:

Middle Band: This is usually a simple moving average (SMA) — often a 20-day average.

Upper Band: This is the middle band plus 2 standard deviations.

Lower Band: This is the middle band minus 2 standard deviations.

These bands move with the stock price and expand or contract based on how volatile the stock is.

🧠 Why Use Bollinger Bands? They help answer questions like:

Is the stock price relatively high or low compared to recent history?

Is the stock entering a period of increased volatility?

📌 How to Read Bollinger Bands When the price touches or moves above the upper band: → The stock might be overbought (price could be too high). → Some traders see this as a sell signal.

When the price touches or falls below the lower band: → The stock might be oversold (price could be too low). → This could be a buy signal.

LMT <- getSymbols("LMT", src = "yahoo", auto.assign = FALSE)

chartSeries(LMT, subset = 'last 3 months', theme = chartTheme("white"))

addBBands(n = 20, sd = 2, maType = "SMA", draw = "bands", on = -1)

Reflection:

Bollinger Bands are popular in technical analysis. What kind of market behavior do the upper and lower bands signal? How might a quant fund use this indicator?

What is one key insight or skill you learned today? Briefly explain it in your own words.

Answer

One skill I learned is how to early create my own stock analysis graphs only using a few lines of code.

What is one concept or tool from today’s session that you would like to apply in the future? Describe how you might use it.

Answer

A concept I was unaware of before this session was the concept of adjusted closing price. I was unaware that there was a difference between raw and adjusted, and now knowing the difference can help me better understand how to read stocks.

References

quantmod website: https://www.quantmod.com/

10 great R packages for stock market data:https://dev.to/lemon-markets/10-great-r-packages-for-stock-market-data-1ocp

QuantInsti: Guide to quantmod: https://blog.quantinsti.com/a-guide-on-r-quantmod-package-how-to-get-started/

chartSeries documentation: https://www.rdocumentation.org/packages/quantmod/versions/0.4.27/topics/chartSeries

Shorting strategy in R: https://blog.quantinsti.com/shorting-high-algo-trading-strategy-r/