Skip to Content
Course content

148: Building a Financial Portfolio Tracker

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of building a portfolio tracker like managing a physical collection of vintage comic books. You have a ledger where you've noted which issues you own and what you paid for them back in the day. But that ledger is static; it doesn't tell you what those comics are worth today. To find the current value, you have to check a price guide or an auction site for every single book, multiply that current price by the number of copies you own, and then compare that to your original cost to see if you've actually made money.

In R, we're doing the exact same thing, just faster. Your ledger is a data frame, the "price guide" is a financial API, and the calculations are handled by vectorization. Here is how those pieces map together:

  • The Ledger: A data frame containing your symbols, shares held, and average cost basis.
  • The Price Guide: The tidyquant package, which lets us pull live market data from Yahoo Finance.
  • The Appraisal: Joining the live price to your ledger and calculating the current market value.

Setting Up Your Holdings

I always recommend starting with a clean, tidy data frame for your assets. I've seen a lot of developers try to use nested lists for this, but that's a mistake in R. Stick to a tibble. It makes the subsequent joins much cleaner.

library(tidyquant)
library(dplyr)

# This is our "ledger"
my_portfolio <- tibble(
  symbol = c("AAPL", "MSFT", "GOOGL", "TSLA"),
  shares = c(10, 5, 2, 15),
  cost_basis = c(145.20, 280.10, 110.00, 190.50)
)

Fetching Real-Time Market Data

Now we need the current price. Instead of manually typing in numbers—which is a recipe for disaster the moment the market opens—we'll use tq_get. I prefer this over quantmod for trackers because it returns a tidy tibble by default.

# We only need the most recent price, so we'll grab the last day of data
current_prices <- tq_get(my_portfolio$symbol, get = "stock.prices") %>%
  group_by(symbol) %>%
  slice_tail(n = 1) %>%
  select(symbol, adjusted = adjusted)

Crunching the Returns

This is where the magic happens. We join the current prices back to our ledger. Once they are in the same row, we can perform vectorized arithmetic. I like to calculate both the absolute gain and the percentage return, because a $100 gain on a $1,000 investment is very different from a $100 gain on a $10,000 investment.

portfolio_performance <- my_portfolio %>%
  left_join(current_prices, by = "symbol") %>%
  mutate(
    current_value = shares * adjusted,
    total_cost = shares * cost_basis,
    gain_loss = current_value - total_cost,
    return_pct = (gain_loss / total_cost) * 100
  )

print(portfolio_performance)

One thing to keep in mind: tq_get pulls "adjusted" prices, which account for dividends and stock splits. If you're building a professional-grade tool, you'll want to be very intentional about whether you're using the raw closing price or the adjusted one. For a general tracker, adjusted is almost always the way to go.




📋 Practical Task

Developing a Diversified Asset Valuation Tool

You've mastered the basics of tracking stocks, but a real portfolio often includes different asset classes. Your task is to expand the tracker to handle a mix of stocks and ETFs.

Create a script that does the following:

  • Define a portfolio tibble containing at least 3 stocks (e.g., "NVDA", "AMZN") and 2 ETFs (e.g., "VOO", "QQQ").
  • Add a column called asset_type to your tibble to distinguish between 'Stock' and 'ETF'.
  • Fetch the current adjusted prices for all 5 symbols using tq_get.
  • Calculate the total portfolio value (the sum of all current_value entries).
  • Use group_by(asset_type) and summarise() to calculate the total value held in Stocks versus the total value held in ETFs.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.