Build a Portfolio ‘What-If’ Simulator in Python

Day 73 of 100 Days Coding Challenge: Python

Today, I added a simulator that answers the age-old investor’s question: “What if I had bought back then?” This little time machine lets me track the profit and loss if I invested on a specific date. Now, I’m not the kind of person who enjoys crying over missed opportunities (I don’t keep a framed photo of Bitcoin circa 2012 on my wall), but this tool is less about regret and more about feedback.

It’s a way to run “what-if” experiments—like the financial version of those alternate timeline episodes in sci-fi shows. Did my stock beat the Nasdaq? Was it just riding the wave of its sector, or did it genuinely outperform? Did this one brilliant pick offset that other… not-so-brilliant one?

Of course, the analysis could get fancier if I tossed in transaction fees, taxes, dividends, and maybe even margin interest. But for now? I’m thrilled that my simulator is alive, kicking, and handing me numbers without judgment.

Today’s Motivation / Challenge

Everyone has had that “If only I had invested sooner…” thought. This project turns that into something useful rather than depressing. It’s like a personal coach reminding you: “Hey, hindsight is free—use it to plan your next move.”

Purpose of the Code (Object)

This function calculates how much money your investment would be worth today if you had dropped a certain amount into your chosen stocks on a specific past date. It doesn’t predict the future; it simply tells you how different entry points would have played out.

AI Prompt

Make it cleaner.
Please add the following function to the script:
Profit and loss if you invested on a chosen day.

Functions & Features

  • Add and remove stock symbols
  • Fetch and display real-time prices
  • Run simulations: X days ago or from a specific date
  • Calculate portfolio profit and loss over time
  • Rank best and worst performers

Requirements / Setup

  • Python 3.10+

Libraries:

pip install yfinance pandas matplotlib

Minimal Code Sample

closes = pd.to_numeric(closes, errors=”coerce”).dropna()

if isinstance(closes, pd.DataFrame):

    closes = closes.squeeze()  # flatten edge case

first_close = closes.iloc[idx:idx+1].to_numpy().item()

last_close  = closes.iloc[-1:].to_numpy().item()

This ensures you get true Python floats, not pandas Series objects that trigger warnings.

Stock Tracker

Notes / Lessons Learned

Remember the pandas deprecation I grumbled about yesterday? Well, it came back for an encore. Turns out float(closes.iloc[idx]) works fine—until pandas decides it doesn’t. My fix was to extract scalars with .to_numpy().item(). It’s one of those small but mighty changes that make the difference between smooth sailing and cryptic warnings.

To be honest, I wouldn’t have solved this one on my own without some outside nudges. But now both simulators (menu 10 and the shiny new “from date” feature) run clean. The app feels less like a prototype and more like a portfolio time machine.

Optional Ideas for Expansion

  • Add a benchmark comparison (e.g., against the S&P 500).
  • Layer in dividends and transaction costs for realism.
  • Simulate dollar-cost averaging for the cautious investor.

Leave a Reply

Your email address will not be published. Required fields are marked *