Day 63 of 100 Days Coding Challenge: Python
On a quiet Saturday morning, armed with coffee and optimism, I dove into today’s coding task: building a function that calculates what my portfolio would be worth today if I had invested a certain amount X days ago. In my Excel days, I used to do this sort of thing manually—lots of formulas, lots of scrolling, and the occasional formatting meltdown. But coding it? That felt far more satisfying, like turning a laborious chore into a sleek push-button tool.
In the real investing world, this is a performance measurement exercise: “How much did this lump sum grow or shrink over that period?” It’s also a sobering way to check whether your portfolio is keeping pace with the S&P 500 or whatever benchmark you care about. One moment you’re patting yourself on the back, the next you’re wondering if you should have just bought an index fund and taken the afternoon off.
It’s also fantastic for “what if” scenarios: missed opportunities, potential sector shifts, or just feeding your curiosity. “If I’d put $10,000 into Tesla six months ago, it’d be worth $14,000 today—a 40% gain. How does that compare to the Nasdaq?” You can test those ideas instantly. Today’s code felt like a solid investment itself—an investment in my ability to measure investments.
Today’s Motivation / Challenge
Being able to quickly test “what if” scenarios helps me make more informed choices. Whether it’s checking how a holding performed, comparing it to a benchmark, or seeing how badly I missed the boat on a hot stock, this feature brings insight without the spreadsheet headaches.
Purpose of the Code (Object)
The function takes a starting investment amount and a time frame, then calculates how much that investment—split equally among all tracked stocks—would be worth today. It uses historical price data to find the purchase price and today’s value, so you can see gains, losses, and percentage changes without doing the math yourself.
AI Prompt:
Create a Python function that simulates the value of an equal-weighted investment across multiple stocks from X days ago to today, using yfinance historical data.
Functions & Features
- Calculate equal-weight portfolio growth over a set number of days
- Show per-stock performance in dollars and percentage terms
- Handle missing or invalid price data gracefully
- Display total portfolio gain/loss and percentage change
Requirements / Setup
pip install yfinance pandas matplotlib
Python 3.8+ recommended.
Minimal Code Sample
idx = closes.index.searchsorted(pd.Timestamp(target_date))
first_close = closes.iloc[idx]
last_close = closes.iloc[-1]
Selects the first available close on/after the target date and the last available close—no ambiguous Series logic.
Notes / Lessons Learned
When I first ran the code, it hit me with two issues. The first was a friendly FutureWarning:
FutureWarning: YF.download() has changed argument auto_adjust default to True
This is Python’s polite way of saying, “Hey, our defaults changed. You might want to set auto_adjust yourself so you know what you’re getting.” Easy fix: add auto_adjust=False (or True if you prefer adjusted prices) to every yf.download(…) call.
The second was less polite:
The truth value of a Series is ambiguous.
I had code like:
if hist[‘Close’][hist.index >= target_date]:
That hist[‘Close’][…] returns a Pandas Series—a list of prices. Python doesn’t know whether I mean “Is this empty?” or “Are all of these True?” or “Is at least one True?” So it refuses to guess. The fix was to pick a single value with .iloc[0] or check .empty.
My final mistake? Forgetting to restart my Python session after fixing the code. I kept seeing the same error because Python was still running the old function from memory. Lesson learned: restart your environment after major changes, or you’ll be debugging ghosts.
Honestly, I’m glad I chased this bug down—it’s one of those errors I won’t forget, and it’s a reminder that both my code and my process are worth investing in.
Optional Ideas for Expansion
- Add weighted allocation for “X days ago” simulations
- Compare portfolio performance to a benchmark like the S&P 500
- Save simulation results to a CSV for record-keeping
