When the Stock Rings, I’ll Answer

Day 65 of the 100 Days Coding Challenge: Python

Today’s project was all about giving my stock tracker a voice—or at least the Python equivalent of tapping me on the shoulder. I added a suite of functions to build a simple price alert system. Now, I can set an alert for any stock symbol, pick a target price (whether I expect it to go soaring or take a nosedive), and check those alerts whenever I feel like it. The alerts live in alerts.json, which means they survive beyond the current run of the program, unlike my patience for earnings season.

Given the market’s recent mood swings—some days it’s caffeine-powered optimism, other days it’s “time to move into a cabin in the woods”—this feature feels like a smart way to keep tabs on a few key stocks. I also tossed in the ability to list all active alerts and remove them once they’re no longer relevant.

I’m not a day trader, so I won’t be glued to this alert system like it’s the final episode of a drama series. But I’m already thinking about how this little foundation could be built into something bigger—perhaps even a full-blown, automated “call me when it matters” system.

Today’s Motivation / Challenge

Sometimes you don’t want to watch the market all day—you just want it to tap you politely when something interesting happens. This project scratches that itch. It’s like hiring a butler who only bothers you when your investments hit the numbers you care about.

Purpose of the Code (Object)

The code lets you set stock price alerts for any symbol, save them, and check them against live prices. You can remove old alerts, list current ones, and trust they’ll be there the next time you run the program. It’s a neat way to track specific opportunities without manually refreshing a stock chart every five minutes.

AI Prompt

Please add a Price Alert system. Let the user set a target price and alert if the current price crosses it. The system needs the following functions: set a price alert, check price alerts now, list alerts, and remove an alert.

Functions & Features

  • Set a Price Alert – Choose a stock, pick a price, and decide if you want to be notified when it rises above or falls below that level.
  • Check Alerts – Compare live prices against saved alerts.
  • List Alerts – See what you’re tracking at a glance.
  • Remove Alerts – Delete alerts you no longer need.

Requirements / Setup

pip install yfinance

Python 3.8+ recommended.

Minimal Code Sample

def check_price_alerts():

    alerts = load_alerts()

    for alert in alerts:

        price = get_price(alert[“symbol”])

        if (alert[“type”] == “above” and price > alert[“target”]) or \

           (alert[“type”] == “below” and price < alert[“target”]):

            print(f”ALERT: {alert[‘symbol’]} hit {price:.2f}”)

Checks each saved alert and prints a message if the condition is met.

Stock Tracker

Notes / Lessons Learned

Yes, I was a bit tired today, so when I created my shiny new alerts.json file, I somehow misspelled it. Naturally, the program refused to recognize it. That was my first mistake. The second? Entering an alert incorrectly—forgetting to choose “above” or “below” before typing in the target price. This left the file corrupted and the program more confused than I was during my first economics class.

The fix was simple but satisfying: I added a load_alerts() function that returns [] if the file is empty and quietly backs up a corrupt JSON before starting fresh. I also made save_alerts() write to a temporary file first, then replace the original in one move. No more half-written files, no more unexpected crashes.

The real lesson? Creating new errors isn’t a bad thing—it’s a great way to see where the cracks are before the whole thing falls apart. It’s a bit like stress-testing your code, except the stress is mostly on you.

Optional Ideas for Expansion

  • Add email or SMS notifications when an alert triggers.
  • Integrate with a dashboard to show alert history.
  • Let alerts expire after a set number of days.

How Not to Miss a Nephrologist Appointment and Routine

Brian’s fitness journal after a brain stroke

Today, I’m doing something slightly less athletic but arguably just as important: planning tomorrow.

I have a nephrologist appointment in the early afternoon, which means tomorrow’s run is officially cancelled. When your kidneys are less than cooperative, you don’t negotiate with specialists—you show up. I see my nephrologist four times a year to make sure my kidneys are still doing their job and haven’t quietly decided to go on strike.

I was supposed to see him in December. That appointment? Completely forgotten.
The lab work, at least, got done—my wife made sure of that—but the results weren’t great. My kidney function had dipped back into Stage 4 territory, which understandably worried her. When numbers go down, her stress level goes up.

Missing that appointment was not something I wanted to repeat.

So this time, I’ve deployed redundancy like a NASA launch:
  • Phone alarm 
  • Calendar reminder 
  • Morning check-in alert 
  • Uber is scheduled in advance 

If I miss this appointment, it won’t be due to a lack of safeguards. If this system works, it may become the standard operating procedure for all future medical visits.

I don’t want to miss these appointments for three reasons:

  1. I need to understand what’s happening with my kidneys.
  2. I’ve accumulated a respectable list of questions.
  3. Uncertainty scares my wife far more than bad news with context.

On the positive side, my other biometrics look solid. My weight is stable. Blood pressure has been well-behaved. Heart rate is calm and cooperative. So while the kidneys demand attention, the rest of the system seems content.

Yes, I’m a little annoyed about skipping my run—but these appointments are rare enough that missing one workout won’t derail anything. And, conveniently, tomorrow’s forecast is rainy, which takes some of the sting out of it.

Sometimes progress isn’t about doing more—it’s about showing up where it matters most, even if that means trading running shoes for a waiting room chair.

I Made A Visualizing Stock Volatility Tool in Python

Day 64 of 100 Days Coding Challenge: Python

For the last few days, I’ve been steadily upgrading my stock tracker with little nuggets of market intelligence—kind of like giving a hamster a GPS and a Fitbit. Today’s upgrade: a Volatility Checker, which ranks your stocks by how wildly they’ve been swinging around lately.

One detail worth noting is the setting auto_adjust=False. Normally, when you download stock prices, finance APIs like to quietly “fix” the numbers for dividends and stock splits. Nice in theory, but I wanted raw, unpolished numbers—like getting your coffee without sugar or cream—so that my results match every other function in my program and avoid those overly polite warning messages.

I also baked in the formula: annualized volatility = daily_std * sqrt(252). Here, daily_std is the standard deviation of daily returns—basically, how jittery a stock has been day-to-day. Multiplying by the square root of 252 assumes there are about 252 trading days in a year. It’s like saying, “If this stock keeps bouncing around at the same pace all year, here’s how dramatic it will look.”

But, markets don’t always stick to 252 trading days. So I went a step further—adding a flag that lets the program annualize based on the actual number of trading days in my dataset. It’s like tailoring a suit instead of buying it off the rack—more accurate and much better fitting.

Today’s Motivation / Challenge

Some investors watch price charts like hawks. Others, like me, enjoy knowing which stocks are acting like calm lakes and which ones are more like caffeinated squirrels. By ranking volatility, you can spot potential opportunities—or avoid heartburn—before making your next move.

Purpose of the Code (Object)

This function checks recent price swings for your tracked stocks, calculates how volatile they’ve been, and ranks them from wildest to tamest. It works for short windows like 10 days or longer periods like 90, depending on how much market drama you want to see. The output includes both daily volatility and an annualized version.

AI Prompt

Please add the following function to the script. “Volatility Checker: Calculate and rank stocks by recent price volatility.”

Functions & Features

  • Tracks and ranks stocks by recent volatility
  • Calculates both daily and annualized volatility
  • Works with a user-selected date range
  • Optionally annualizes based on actual trading days in your dataset

Requirements / Setup

pip install yfinance

pip install matplotlib

pip install pandas

Python 3.9+ recommended.

Minimal Code Sample

returns = closes.pct_change().dropna()

daily_vol = returns.std()

annual_vol = daily_vol * math.sqrt(len(closes))  # based on actual days

Calculates daily volatility, then annualizes it based on your dataset length.

Stock Tracker

Notes / Lessons Learned

Finance isn’t new to me—I’ve studied it and used it in real life—but coding it is a different story. You can know the theory (like “252 trading days in a year”) without realizing the programming implications until you see the raw code. AI acts like the friend who not only reminds you of the theory but also shows you how to plug it into your function, keeping you from stepping into common traps.

By now—day 64—I’m convinced that AI’s real power isn’t just spitting out answers; it’s stitching together knowledge from different worlds and handing you a well-fitted solution. Still, the joy comes from building something from scratch. With AI as your co-pilot, you’re suddenly flying first class.

Optional Ideas for Expansion

  • Allow filtering for “Top 5 most volatile stocks” only
  • Save volatility rankings to a CSV for record-keeping
  • Add color-coded output for quick scanning (green for calm, red for wild)

Track Portfolio Growth Simulation with Python and yfinance

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.

Stock Tracker

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

A Rainy Morning Run and a Strong Finish Elsewhere

Brian’s fitness journal after a brain stroke

Despite the heavy rain early this morning, my wife still went out for her morning exercise—and got thoroughly soaked. She owns a proper running jacket designed for rain and snow, a relic from her years in Canada. Unless there’s ice on the road, the weather is more of a suggestion than a deterrent for her.

I, on the other hand, was mildly concerned about becoming a soggy runner.

By the time I headed out, the rain had cleared completely—and somehow it was warm enough for shorts. A rare weather plot twist. Unfortunately, this unexpected kindness from the sky did not translate into a target-paced run.

Running pace is a fragile thing. Sleep quality, body condition, temperature, humidity—almost anything can tip it off balance. If I don’t sleep well, my pace suffers. If the weather shifts suddenly, my pace notices. So I try not to get too discouraged when a run doesn’t go exactly as planned.

Today was one of those days.

Still, the workout wasn’t a loss. Pull-ups were on the schedule, and those went well. I completed all 21, finishing the first 10 without dropping off the bar—a small but satisfying benchmark. Planking and stretching followed, both completed without complaint from my body.

While the run didn’t cooperate, the rest of the system performed.

I’ll have one more chance this week to hit my target pace. Tomorrow’s weekly 10K will be the real test. If I can’t hit my goal across the full distance, I’m hoping to at least lock it in for one strong half.Not every run is fast.
Not every workout shines.
But consistency still counts—and today, that box is firmly checked.

The Stock Market Mood Ring

Day 62 of 100 Days Coding Challenge: Python

Yesterday, I taught my script how to look into the past—specifically, the last 30 days of each tracked stock’s closing prices. Today, we’re talking emotions—well, stock emotions. I added a function in Python to show each stock’s daily percentage change, color-coded like a moody person: green when it’s up, red when it’s down, and default when it’s flat.

Now, to be clear, I’m not a day trader glued to five monitors with live tickers whizzing by. I have a full-time job, thank you very much, and no one’s got time for that kind of circus. I check in weekly, adjust when needed, and focus on consistency over drama. Still, this function gives me a quick visual snapshot of how things are moving—and more importantly, how they might move. It’s like giving your portfolio a morning coffee and asking, “How are we feeling today?”

Patterns are the name of the game. If I can start spotting them, maybe one day I’ll teach this program to make some educated guesses—and eventually, add a bit of risk management to keep me from playing financial roulette. The next few days are all about adding the kind of analytical firepower that helps with smarter decisions down the road. And honestly? I’m kind of pumped.

Today’s Motivation / Challenge

You know that moment when you look at your bank account and squint, wondering, “What happened yesterday?” That’s what this feature is for. It’s like a digital mood chart for your stocks—without the therapy bills. Adding daily change percentages, especially in color, helps me scan for drama or calm in seconds. It’s a tiny step toward building a truly useful tool for hands-off investors like me, who want the intel without the stress.

Purpose of the Code (Object)

This code adds a quick visual check-in for each stock in my portfolio. It tells me whether a stock’s price went up or down today—and by how much—without needing a spreadsheet or third-party app. It’s lightweight, readable, and tailored to my investment rhythm.

AI Prompt (used to create today’s function):

“Please add the following function to the script.
Daily Change (%): Show today’s % change for each stock with green/red highlight.

Functions & Features

  • Calculates daily percent change for each stock.
  • Highlights gains in green and losses in red.
  • Leaves unchanged stocks in default color.
  • Makes my console look like it actually cares.

Requirements / Setup

pip install yfinance

Minimal Code Sample

if change_percent > 0:

    color = “\033[92m”  # Green

elif change_percent < 0:

    color = “\033[91m”  # Red

else:

    color = “\033[0m”   # Reset

This assigns a text color based on the day’s percent change in stock price.

Stock Tracker

Notes / Lessons Learned


I’m starting to feel like a feature-adding machine—well-oiled, slightly caffeinated, and surprisingly organized. Thanks to the roadmap I drafted early on, it’s easier to stack new functions like LEGO bricks (minus the foot pain).

Today, I learned how to add color using ANSI escape codes. Think of them as secret signals you whisper to your terminal to make it look fancier. So now, green means the stock had a good day, red means it might need a hug, and the reset command keeps the rest of the terminal from turning into Christmas.

What I love about this feature? It’s subtle but powerful. Visual clarity goes a long way when you don’t have time to deep dive. And hey—who knew the terminal had a flair for drama?

Optional Ideas for Expansion

  • Add arrows (↑/↓) next to the percent for more flair.
  • Let users set custom alert colors (purple for panic? Why not).
  • Create a summary line showing how many stocks gained vs. lost today.

Watching Your Stocks Like a Hawk (But With a Graph)

Day 61 of 100 Days Coding Challenge: Python

The last five days were all about laying the foundation—think of it as assembling IKEA furniture, but with Python and fewer Allen wrenches. I got the stock tracker’s bones in place, installing essentials like the yfinance library. Now, it’s time to dress it up and make it do something more alive—like track real stock movement over time.

I’m finally stepping into the exciting part: creating a portfolio visualization that doesn’t require squinting at 14 browser tabs.

We’re starting simple. One historical price chart per stock. No more, no less. Why? Because trying to cram five charts into one screen is like watching five soap operas at once—dramatic, confusing, and probably bad for your blood pressure.

Back in university, my finance professors swore by stock observation like it was a sacred rite. Watch the markets, they said. Understand the impact of events—unemployment numbers, interest rate announcements, or when Jerome Powell so much as blinks. These things shake the market, and now, thanks to a bit of Python magic, I can watch those ripples without hopping from one website to another.

Today’s Motivation / Challenge

Have you ever tried checking your stocks manually, one by one? It’s like chasing toddlers in different directions. Today’s goal: automate that madness. With a single function, I want to see the historical price trends of each stock in my portfolio—visually. Because numbers are fine, but a chart? A chart speaks volumes.

Purpose of the Code (Object)

This little script fetches and plots the past 30 days of closing prices for each stock in your portfolio. It doesn’t try to impress anyone with fancy calculations. It just shows you what your stock has been up to, in a nice, simple line graph—so you can stop opening 27 browser tabs.

AI Prompt

Add the function to plot past 30-day price history for a single stock

Functions & Features

  • Plots past 30-day price history for a single stock
  • Automatically fetches historical data from Yahoo Finance.
  • Easy to reuse for each stock in your portfolio

Requirements / Setup

pip install yfinance matplotlib

Minimal Code Sample

import yfinance as yf

import matplotlib.pyplot as plt

def plot_stock_history(ticker):

    stock = yf.Ticker(ticker)

    hist = stock.history(period=”30d”)

    hist[‘Close’].plot(title=f”{ticker} – Last 30 Days”)

    plt.xlabel(“Date”)

    plt.ylabel(“Price ($)”)

    plt.grid(True)

    plt.show()

→ Fetches and plots 30-day closing price for a given stock symbol.

Stock Tracker

Notes / Lessons Learned

To get this feature working, I first installed yfinance and matplotlib. Easy enough—until I noticed the pip version nagging me to update (again). I was on 25.1.1, and suddenly it wants 25.2. It’s like that one friend who insists on “just one more update” before going out.

This is the reality of programming: libraries get updated more often than your favorite streaming shows, and if you’re not careful, your working code might just throw a tantrum the next day. I used to roll my eyes when game servers went down for “maintenance.” Now I know—those devs were heroes.

Also, pro tip: stock movements don’t just come from earnings reports. Tariff announcements? Those hit hard. I saw a few of my stocks tumble right after one went into effect. Should’ve bought the dip… but hey, now I can at least see it happening, in style.

Optional Ideas for Expansion

  • Add a dropdown menu or an input box to select stock instead of typing it
  • Color-code gains vs losses on the chart
  • Combine charts into one interactive dashboard (when you’re feeling brave)

Pull-Ups, Greed, and the Fine Art of Pushing Just Enough

Brian’s fitness journal after a brain stroke

I woke up a few minutes early this morning, which already put me in a suspiciously good mood. Mondays usually require negotiation. Today did not. Today was pull-up day.

That meant I had a decision to make.

I’d originally set my goal at 20 pull-ups—a nice, round, respectable number. I hit that last week. So the question was simple:
Do I maintain… or do I get greedy?

Before my brain stroke, I used to follow a program called P90X. I had one of those doorway pull-up bars—the kind that makes you question both engineering and your doorframe. A year before my stroke, my wife upgraded me to a proper exercise bar. Then the stroke happened. The bar sat unused. Later, it was dismantled when we moved to Nashville.

For a long time, upper-body strength wasn’t even on the agenda.

First came walking—with a walker.
Then walking with my wife’s support.
Then a stick.
Then jogging.
And now… 10K runs.

A few years ago, I pulled the equipment back out and reassembled it. At first, pull-ups were brutal. Awkward. Humbling. But slowly—quietly—they came back.

Here’s the strange part:
I can now do more pull-ups than I could before my stroke.

That still surprises me.

So this morning, being appropriately greedy, I went for 21.

I completed the first 10 without dropping from the bar and immediately felt victorious enough to justify the decision. When you push just beyond what you think you can handle—not recklessly, but deliberately—your body often agrees to the negotiation.

The remaining 11 came in two bursts:
6 pull-ups, a few seconds of existential bargaining, then 5 more.

Done.

I’m still careful. I have to be. My kidneys mean I can’t overwork muscle tissue or recover like a typical athlete. Cardio and resistance training are good for me—but excess is not. Everything lives in the margins of balance.

Still, this kind of pushing works for me.

For now, I think I’ll keep increasing the count each week—at least until I can comfortably complete two clean sets of 10 with only a short break between them.

After that?
We’ll renegotiate again.

That’s how progress works—not in straight lines, but in small, stubborn decisions made on ordinary Monday mornings.

How to Simulate Weighted Stock Investments in Python

Day 60 of 100 Days Coding Challenge: Python

When it comes to investing, I tend to lean toward the systematic approach. I like a plan. Not a “buy high, panic low” kind of plan, but a “how can I make $100 go as far as possible without needing a spreadsheet and a prayer” plan. Many stocks—especially ETFs—allow fractional share purchases, which is a blessing for anyone whose investing budget is less Wall Street and more wallet lint. That’s the beauty of modern investing: even if you don’t have a mountain of capital, you can still climb the hill.

So today I asked myself, what if my program could simulate that for me? What if I could say, “Here’s my $100,” and the program could allocate it automatically? Then I thought: what if I want to invest 25% in TSLA and only 5% in that random biotech company I’m not sure I trust? That’s where the idea of weighted allocation came in. A little money invested consistently can become something big over time—and the code now knows how to treat your dollars like they matter. Because they do.

Today’s Motivation / Challenge

You’ve probably heard some version of the advice “invest consistently, even with small amounts.” But how do you split that $100 in a smart, intentional way? Today’s challenge was about helping the program act like a friendly robo-advisor. Instead of dividing your money equally, it now lets you decide how much each stock gets. More TSLA, less risk. Or more risk, less cash. Either way, it’s your call—and the math is on your side.

Purpose of the Code (Object)

This new feature lets you simulate how much stock you could buy with a specific amount of money based on custom weight percentages. You choose the amount to invest, set the allocation weights for each stock, and the script calculates how many shares you could get, what it would cost, and how much remains. It’s budgeting, but for your imaginary portfolio.

AI Prompt: 

Create a Python function that takes a total investment amount and a custom percentage for each stock, then calculates how many shares can be purchased and the cost per stock using yfinance.

Functions & Features

  • Add or remove stock symbols from your portfolio
  • View real-time prices of all tracked stocks
  • Simulate investment allocation based on equal weights
  • Simulate investment allocation based on custom weight percentages
  • Check the price of a specific stock
  • Exit the program (option 99)

Requirements / Setup

pip install yfinance

Works with Python 3.8+. Use a virtual environment for clean setup.

Minimal Code Sample

def simulate_weighted_allocation():

    total = float(input(“How much to invest? $”))

    for symbol in stocks:

        weight = float(input(f”{symbol} weight (%): “))

        allocated = (weight / 100) * total

        shares = allocated / get_price(symbol)

        print(f”{symbol}: {shares:.4f} shares for ${allocated:.2f}”)

Takes your total investment and simulates purchasing based on custom weights.

Stock Tracker App

Notes / Lessons Learned

Initially, my simulation just split the money evenly—simple and safe. With 13 stocks in my portfolio, that reminded me of those index funds that allocate 1% to everything, like some kind of financial democracy. And while that’s a solid strategy (Vanguard would approve), I wanted control. I wanted to give TSLA a bigger slice of my $100 pie. So I added a custom weight input. Now the script lets me play mini portfolio manager.

One catch: if your percentages don’t add up to exactly 100, the program will throw a gentle tantrum. So you do have to plan ahead and know what you’re allocating. Otherwise, it’s like hosting a potluck and forgetting who brings dessert—awkward and disappointing. Still, once it worked, I thought: This is cool. It’s like mock investing with real math—and zero risk.

Optional Ideas for Expansion

  • Save your weight presets for recurring investment styles
  • Add error handling to automatically rebalance weights to 100%
  • Display a pie chart of your allocation with matplotlib

This marks the point where the stock tracker grows from a utility to a personal investing playground. And we’re only 60 days in.

The Price is Modular: Breaking Up is Clean to Do

Day 59 of 100 Days Coding Challenge: Python

Yesterday, I caught myself on the edge of a rookie mistake: copying the same chunk of “fetch price” code into every place that needed it. It was like déjà vu with worse indentation. So I took a breath, cleaned it up, and extracted that logic into a shiny, single-purpose function: get_price(). Now, anytime I need the current price of a stock, I just call one clean little line. And if I ever want to swap out Yahoo Finance for Alpha Vantage—or carrier pigeons, who knows—I only have to update it in one place.

Unlike my previous project (the slightly chaotic book tracker that looked like it was written in a storm), this time I’ve actually thought about structure. I outlined a rough roadmap and started slicing features into small, logical pieces. Turns out, coding for your future self is a real kindness. It’s already making the script easier to manage, and I haven’t even spilled coffee on it yet.

I also added an extra feature that turned out to be more useful than expected: the ability to check the current price of a single stock on demand. It’s perfect for those moments when I randomly wonder, “How’s TSLA doing today?” or “Is MSFT still climbing?” Now I don’t have to scroll through my entire portfolio—I just type, fetch, and boom. Market curiosity satisfied.

Today’s Motivation / Challenge

 This project is starting to feel like a real tool, not just a list of stock symbols collecting digital dust. But with functionality growing, it was time to tidy up the code before it turned into a spaghetti bowl. By modularizing the price-fetching logic, I gave myself room to grow—because adding new features is so much easier when your code isn’t held together with duct tape and denial.

Purpose of the Code (Object)
 

The script now includes a reusable function, get_price(), that handles all price-fetching tasks. It simplifies the process of displaying current prices and opens the door to adding new features without clutter. I also added a quick price-check tool for any stock—not just ones in your portfolio.

AI Prompt: 

Refactor price-fetching logic into a reusable Python function using yfinance. Add an option to check the real-time price of any single stock.

Functions & Features

  • Add or remove stock symbols
  • View your portfolio with current prices
  • Fetch real-time price for any single stock
  • Show stock symbol list
  • Exit the program (option 99, always last)

Requirements / Setup

pip install yfinance

Python 3.8+ recommended. Use a virtual environment if possible for clean installs.

Minimal Code Sample

python

CopyEdit

def get_price(symbol):

    ticker = yf.Ticker(symbol)

    return ticker.info.get(“regularMarketPrice”)

A reusable function to get the latest market price for a stock symbol.

Stock Tracker

Notes / Lessons Learned
 

The key to keeping a growing script from turning into chaos? Organization. Even with AI in your corner, you still need to think ahead. During my book tracker project, I just tacked on features as they came to mind—resulting in a menu that looked like a word jumble and an exit function mysteriously wedged in the middle of everything.

This time, it’s different. Each function has a purpose, and I’m building with intention. Adding the “check a specific stock” feature was fast and satisfying. I tested it with TSLA and MSFT—worked like a charm. It’s amazing what a little structure (and a lot less clutter) can do.

Optional Ideas for Expansion

  • Add error handling for invalid or misspelled stock symbols
  • Include the timestamp of last price update
  • Build a search history so you can revisit recently checked stocks

This project is starting to feel less like a toy and more like a tool. Clean code, clear menus, and real data—what’s not to love?