R
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Data Structures
-
Section 4: Data Manipulation
-
Section 5: Visualization and Statistics
-
Section 6: Advanced R
-
Section 7: Practical Projects
-
Section 8: Interview Practice
-
Section 9: More Practice Exercises
-
Section 10: Shiny Apps in Depth
-
Section 11: More Data Wrangling
-
Section 12: Tidyverse Deep Dive
-
Section 13: Statistical Modeling Deep Dive
-
Section 14: Machine Learning in R
-
Section 15: R Visualization Deep Dive
-
Section 16: R Package Development Deep Dive
-
Section 17: R for Reproducible Research
-
Section 18: R and Databases
-
Section 19: R Performance Optimization
-
Section 20: Bioinformatics and Specialized R
-
Section 21: More Shiny Practice
-
Section 22: More Practice Exercises
-
Section 23: R Data Structures Deep Dive
-
Section 24: More Interview and Review
-
Section 25: R for Business Analytics
-
Section 26: R Text Mining and NLP
-
Section 27: R Spatial Data Analysis
-
Section 28: R Deep Learning
-
Section 29: Advanced Statistical Techniques
-
Section 30: R Object Systems Deep Dive
-
Section 31: R Environments and Metaprogramming
-
Section 32: R for Finance
-
Section 33: R for Clinical and Health Data
-
Section 34: More Shiny Advanced Practice
-
Section 35: R Data Cleaning Deep Dive
-
Section 36: R Reporting Automation
-
Section 37: More Practical Projects Round 2
-
Section 38: R Ecosystem and Career
-
Section 39: More Visualization Practice
-
Section 40: R for Experimentation
-
Section 41: R for Genomics and Bioinformatics Deep Dive
-
Section 42: R for Marketing Analytics
-
Section 43: R Data Import/Export Deep Dive
-
Section 44: R String Processing Deep Dive
-
Section 45: R for Actuarial and Insurance Analytics
-
Section 46: R Testing and Quality Assurance Deep Dive
-
Section 47: R Version Control and Collaboration
-
Section 48: R Advanced Functional Programming
-
Section 49: R for Supply Chain and Operations
-
Section 50: More Practice Exercises Round 3
-
Section 51: R Dashboards and BI Integration
-
Section 52: R Data Governance and Ethics
-
Section 53: More Modeling Practice
-
Section 54: R Final Capstone Projects
-
Section 55: R for Sports Analytics
-
Section 56: More Interview Practice Round 2
-
Section 57: R Networking and APIs
-
Section 58: R for Environmental Science
-
Section 59: R Notebook and Documentation Practices
-
Section 60: More Data Wrangling Mastery
-
Section 61: R for A/B Testing at Scale
-
Section 62: R Package Ecosystem Deep Dive
148: Building a Financial Portfolio Tracker
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
tidyquantpackage, 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_typeto 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_valueentries). - Use
group_by(asset_type)andsummarise()to calculate the total value held in Stocks versus the total value held in ETFs.
There are no comments for now.