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.

How to Find the Worst-Performing Stocks in Your Portfolio Using Python

Day 72 of 100 Days Coding Challenge: Python

Yesterday, I was busy shining the spotlight on my star performers—the stocks that strutted across the stage as Broadway leads. Today, it was time to peek behind the curtain and see who was tripping over their own shoelaces. Enter: the “Worst-Performing Stock Tracker” function.

The logic is the same as yesterday’s “Best Performer” feature, but instead of crowning heroes, this one identifies the stragglers. Why bother? Because good portfolio management isn’t just about celebrating your winners—it’s also about recognizing when something is quietly dragging you down. I use it as a reminder to rebalance, pairing losses with gains. Thanks to yesterday’s groundwork, adding this feature felt like running downhill instead of uphill.

Today’s Motivation / Challenge

This project matters because no portfolio is a utopia of green arrows. Every investor has that one stock sitting in the corner sulking, ruining the vibe. By building a tool that identifies these underperformers, you can make better decisions: cut your losses, reallocate funds, or at least brace yourself with an extra cup of coffee before checking your account.

Purpose of the Code (Object)

The code checks your portfolio over the past X days (7, 14, or 30) and identifies the worst performer. It then neatly lists the bottom 10, so you can see at a glance which ones are dragging your imaginary—or real—portfolio down. Think of it as a “naughty list” for your investments.

AI Prompt

Add a function to show Worst Performer (last X days). Identify the stock dragging your (imaginary) portfolio down and display the bottom 10 over 7, 14, or 30 days.

Functions & Features

  • Add, remove, and view tracked stocks.
  • Fetch real-time prices.
  • Check best and worst performers over selectable periods.
  • Simulate portfolio performance and rebalance strategies.

Requirements / Setup

  • Python 3.9+

Install dependencies:

pip install yfinance pandas matplotlib

Minimal Code Sample

def worst_performer_last_x_days(symbols, days=7):

    results = []

    for sym in symbols:

        closes = _get_closes_1d(sym, period_days=days+5)

        if closes is None or len(closes) < days + 1:

            continue

        start, end = float(closes.iloc[-(days+1)]), float(closes.iloc[-1])

        pct = (end – start) / start * 100

        results.append({“symbol”: sym, “pct”: pct})

    return sorted(results, key=lambda r: r[“pct”])[:10]  # bottom 10

This function sorts your portfolio by performance and hands you the 10 worst offenders.

Stock Tracker

Notes / Lessons Learned

I made sure the function pulls from the same stocks.json file used by other features, keeping everything consistent. That’s like making sure all your socks match before heading out—details matter.

What surprised me? Debugging an error in my “simulate portfolio value” function. I suspect it’s tied to the line grabbing the first close price, but that’s a mystery for another day. The fun (and slightly maddening) part of coding is how today’s victory sometimes reveals tomorrow’s bug. Keeps life interesting, doesn’t it?

Optional Ideas for Expansion

  • Add a “Worst Sector” view to see which industry is letting you down the most.
  • Build a feature that pairs losers with winners for auto-rebalancing.
  • Compare your bottom 10 to the S&P 500 and see if misery loves company.

Build a Portfolio Performance Checker in Python

Day 71 of 100 Days Coding Challenge: Python

Today, I added a feature to crown the “best performer” from my portfolio. Think of it as a mini award ceremony where only stocks are invited and there’s no acceptance speech—just numbers. The function itself is simple: it checks which stocks in my holdings have gained the most over the last 7, 14, or 30 days. I don’t need this every day; daily stock swings are more like background noise than useful insight. In fact, when I first started, I used to check every single day—bad idea. The constant up-and-down did nothing but feed my anxiety. Now, I prefer to take a step back and do a weekly review, usually on weekends. That’s when I reflect, think strategically, and make any adjustments.

I’m more of a mid-term investor, not a hyperactive day trader, so this tool fits right into my rhythm. It’s like glancing at the scoreboard after a few innings rather than obsessing over every pitch.

Today’s Motivation / Challenge


The challenge was to build a function that helps me zoom out. Beginners (my past self included) often get caught up in every twitch of the market. But sometimes, what you need is a bird’s-eye view: Which of my stocks has been pulling its weight lately? This function answers that without the clutter of daily drama.

Purpose of the Code (Object)


This code identifies which stock in your portfolio had the biggest gain over a chosen period—7, 14, or 30 days. It’s essentially a quick performance check-up for your holdings, designed to keep you focused on trends rather than noise.

AI Prompt


Use the file uploaded, and add the function to see Best Performer (last X days): Identify the top gainer over the last 7, 14, or 30 days.

Functions & Features

  • Add and remove stock symbols from your portfolio
  • Track daily changes and simulate allocations
  • Plot historical charts and moving averages
  • Check diversification and sector exposure
  • New: Spot the best performer over 7, 14, or 30 days

 You’ll need Python 3 and a few common libraries:

pip install yfinance pandas matplotlib

Minimal Code Sample

winner, results = best_performer_last_x_days(symbols, days=7)

print(f”Best performer (7 days): {winner[‘symbol’]} {winner[‘pct’]:.2f}%”)

This snippet finds the top gainer in your current portfolio over the past 7 days.

Stock Tracker

Notes / Lessons Learned


Today, I learned how a tiny inconsistency can wreak havoc. My script is now over 1,300 lines, and I initially got nothing but “no results” because the function was pulling symbols from the wrong place. I mistakenly used get_symbols() from portfolio.json, while the rest of the app stores tickers in stocks.json through load_stocks(). Naturally, the poor function came up empty. The quick fix was to swap in load_stocks(). It reminded me of those group projects where one person keeps using a different spreadsheet version—chaos ensues. Moral of the story: keep your files consistent, keep your sanity intact.

Optional Ideas for Expansion

  • Add a “Worst Performer” twin function, so you know which stock deserves detention.
  • Compare your portfolio’s best performer against the S&P 500 for context.
  • Create a simple chart that ranks the top 5 movers for a more visual snapshot.

Build a Portfolio Sector Weight Analyzer in Python

Day 70 of 100 Days Coding Challenge: Python

Yesterday’s mission was neat labels; today’s mission is guardrails. After building a sector classifier, I wired up a real diversification warning that uses my actual holdings. Diversification isn’t a hedge against everything, but it’s a reliable seatbelt against unsystematic risk—the “one company or one industry sneezes, and my portfolio catches a cold” problem. During COVID, anyone parked entirely in hospitality learned this the hard way.

This little alarm is more than a nag; it’s a planning tool. You can use it for sector rotation, thematic tilts, or just sanity checks alongside momentum and RSI. I also like it for quick overlap checks: if a few ETFs secretly pile into the same sector, this makes the crowding visible. Honestly, the feature pays off all the tiny utilities I’ve been adding—now they sing together instead of humming alone.

Today’s Motivation / Challenge

I wanted a single, honest number that says, “Are you concentrated or not?” The challenge: turn tickers into sectors, sectors into dollars, and dollars into weights—without burying the user in math or menus.

Purpose of the Code (Object)

The program reads your tracked tickers and your share counts, fetches current prices, and calculates market value per holding. It then groups by sector (treating multi-sector and bond ETFs as their own diversified buckets) and shows each sector’s weight. If any one slice is larger than your chosen threshold, you get a clear warning.

AI Prompt

“Refactor the diversification function to be small, readable, and robust. Keep inputs flexible, handle ETFs cleanly, and print a concise sector weight table followed by any threshold warnings.”

Functions & Features

  • Record or update shares for each tracked symbol.
  • Classify holdings by sector, with special handling for multi-sector and bond ETFs.
  • Compute sector weights using Market Value = Shares × Price.
  • Trigger a diversification warning if any sector exceeds a threshold (e.g., 35%).

Requirements / Setup

  • Python 3.10+

Install:

pip install yfinance pandas matplotlib

Minimal Code Sample

def sector_weights(rows, threshold=0.35):

    # rows: list of {symbol, sector, shares, price}

    df = pd.DataFrame(rows)

    df[“market_value”] = df[“shares”] * df[“price”]

    total = df[“market_value”].sum()

    if total <= 0:

        return {}, []

    weights = (df.groupby(“sector”)[“market_value”].sum() / total).sort_values(ascending=False)

    offenders = [(s, w) for s, w in weights.items() if w >= threshold]

    return dict(weights), offenders

Compute sector weights from actual dollars; return all weights plus any over the threshold.

Stock Tracker

Notes / Lessons Learned

I initially forgot to store share counts. Which meant every stock was treated like I owned exactly one share—cute for demos, terrible for truth. I was sure I’d written a “set shares” function before; apparently Past Me left Future Me a polite illusion. Once I added a quick way to save shares in stocks.json, the numbers snapped into place.

The joy here is leverage: Python fetches prices, lines up sectors, and crunches totals in seconds. What used to be a spreadsheet slog is now a button press. Also, beware ETF overlap—their tickers look diverse, but their guts sometimes aren’t.

Optional Ideas for Expansion

  • Add “max sector cap” rules per account and print suggested trades to rebalance.
  • Show a tiny trendline of each sector’s weight over time (store daily snapshots).
  • Include an “overlap matrix” for ETFs using their published holdings, if available.

Know Thy Sector Before Thy Portfolio Falls Apart

Day 69 of 100 Days Coding Challenge: Python

Today’s stop on the Stock Tracker Express was “Sector Classification,” and I decided to pull into that station before the Diversification Warning stop. Why? Because you can’t warn about lopsided allocations until you know where your money is hiding. Sector classification is like labeling your pantry—if you find 14 jars of peanut butter and no pasta, you might reconsider your meal plan.

In investing, this helps spot “unsystematic risk,” which is just the fancy way of saying, “If one company or industry tanks, you don’t want your whole portfolio going down with it.” Sometimes, yes, you might choose to overload in one sector—maybe tech is hot or utilities are shining—but the point is to know when you’re doing it. With the sector view in place, you can pair it with performance metrics, macroeconomic signals, or just your gut to make better decisions. My roadmap had diversification before classification, but order matters—this way, we start with a map before we set up roadblocks.

Today’s Motivation / Challenge

If you’ve ever played a board game without reading the rules first, you’ll understand why knowing your sector exposure before diversifying is important. Classification turns a pile of tickers into an organized story, letting you see not just what you own, but where it lives.

Purpose of the Code (Object)


This function takes your tracked tickers, peeks under the hood, and tells you what sector and industry they belong to. For ETFs and funds, it makes an educated guess—flagging them as multi-sector or fixed income when appropriate. The idea is to give you a quick visual of portfolio balance before you go hunting for weak spots.

AI Prompt

Creates the following functions: Fetch sector and industry, identify ETFs and label them as multi-sector or fixed income, and finally print a tidy classification table and sector summary.

Functions & Features

  • Fetch sector and industry data for each tracked stock.
  • Identify ETFs and label them as multi-sector or fixed income.
  • Print a tidy classification table and sector summary.
  • Optionally export results to CSV.

Requirements / Setup

  • Python 3.10+

Install dependencies:

pip install yfinance pandas matplotlib

Minimal Code Sample

import yfinance as yf

def get_sector(symbol):

    info = yf.Ticker(symbol).info

    return info.get(“sector”), info.get(“industry”)

print(get_sector(“MSFT”))  # (‘Technology’, ‘Software—Infrastructure’)

Pulls sector and industry info for a ticker.

Stock Tracker

Notes / Lessons Learned

ETFs can be divas—some announce their sector proudly, others just say “multi-sector” or “bond fund” and walk away. Fixed income ETFs (bond funds) make perfect hedges for my tech-heavy holdings, so I labeled those separately. This classification step also reminded me how ambiguous data can be; without it, I might’ve assumed my ETFs were more focused—or more diversified—than they really are.

Optional Ideas for Expansion

  • Show top three sector weights for ETFs when available.
  • Include historical sector rotation charts.
  • Add filters to display only certain sectors.

Stock Momentum Indicator Made Simple: Compute Trend Direction with Python

Day 68 of 100 Days Coding Challenge: Python

Yesterday’s three-hour duel with RSI left me a little cross-eyed, so I returned today with a reset brain and a mission: add a Stock Momentum Indicator. I’m not a chart whisperer, but this little gauge helps me decide which stocks deserve a spot on the keep list and which ones can politely see themselves out. Of course, no single indicator is a magic “buy/sell” button—RSI and moving averages still earn their keep, and a quick skim of headlines never hurts. If a name like TSLA suddenly lurches up or down, momentum usually lights up first, and that’s my cue to check the news and sanity-check my long-term plan. I’m investing for the marathon, not the sprint; momentum just helps me keep my shoelaces tied.

Today’s Motivation / Challenge

Prices wiggle. Trends matter. The challenge is turning those squiggles into a simple “up, down, or meh” signal you can read in one glance—something practical enough to use with your existing RSI/MA checks without turning your brain into soup.

Purpose of the Code (Object)

The Momentum Score looks at recent closing prices, fits a straight line through them, and tells you if the general direction is up, down, or flat. It also weighs how “clean” the trend is so wobbly lines don’t shout as loudly as steady climbs. You get a single number plus a label that’s easy to act on.

AI Prompt

“Make this function cleaner. Keep inputs/outputs simple, follow PEP 8, handle edge cases (short/NaN data), add concise docstrings, and avoid side effects. Return a small dict with last_close, ann_pct, r2, score, and direction. Prefer readable names over cleverness.”

Functions & Features

  • Momentum Score: Up/Down/Flat with a strength-weighted score.
  • RSI status: Quick read on overbought/oversold.
  • Moving Averages: Short vs. long for context.
  • Fetch recent closes: Pulls the last N days for each ticker.

Requirements / Setup

  • Python 3.10+

Install:

pip install yfinance pandas numpy matplotlib

Minimal Code Sample

def momentum_score(closes, lookback=60):

    s = pd.Series(closes).dropna().astype(float).tail(lookback)

    if len(s) < 20:

        return {“direction”: “flat”, “score”: 0.0, “r2”: 0.0, “ann_pct”: 0.0, “last_close”: float(‘nan’)}

    y = s.values

    x = np.arange(len(y), dtype=float)

    slope, intercept = np.polyfit(x, y, 1)

    y_hat = intercept + slope * x

    ss_res = np.sum((y – y_hat) ** 2)

    ss_tot = np.sum((y – y.mean()) ** 2)

    r2 = 0.0 if ss_tot == 0 else max(0.0, 1.0 – ss_res / ss_tot)

    ann_pct = (slope / np.mean(y)) * 252.0 * 100.0

    score = ann_pct * r2

    direction = “up” if score > 1 else “down” if score < -1 else “flat”

    return {“direction”: direction, “score”: score, “r2”: r2, “ann_pct”: ann_pct, “last_close”: float(s.iloc[-1])}

Fits a straight line through recent prices, scales the slope to annualized %, weights by trend quality (R²), and labels the direction.

Stock Tracker

Notes / Lessons Learned

Yesterday taught me a simple truth: sometimes the best fix is a fresh chat and a tidier workspace. I kept stuffing more context into the same thread and the AI started juggling chainsaws. Uploading the project folder and the roadmap calmed everything down—clean inputs, clean outputs, faster help. People get overwhelmed by messy instructions; AI does too (just less visibly).

Under the hood, momentum is pleasantly un-mystical. Grab the last N closes (I like 60), draw a line, scale the slope to an annualized percentage, weight it by how straight that line is, and call it: up, down, or flat. It runs in seconds, which is delightful—just remember fast ≠ infallible. Spiky data, low volume, or surprise news can throw elbows, so pair this with RSI, moving averages, and a quick look at headlines before you make grown-up decisions.

Optional Ideas for Expansion

  • Add a tiny sparkline plot with the regression line for each ticker.
  • Auto-flag “momentum flips” (e.g., score crosses ±1) and show the last few related headlines.
  • Let each symbol have its own lookback window so slow movers and high fliers get fair treatment.

Stock RSI Made Simple: Calculate Overbought & Oversold Conditions in Python

Day 67 of 100 Days Coding Challenge: Python

Today’s experiment was all about giving my stock tracker a sixth sense—adding the Relative Strength Index (RSI), RSI Stock Indicator . Think of RSI as the mood ring of the trading world: if it reads over 70, your stock might be partying too hard and due for a hangover (price pullback). Under 30? That’s the sulking, underappreciated stock that might be ready to rally.

Now, RSI isn’t the crystal ball some traders wish it was, but it’s a handy companion—especially when paired with the moving average I added yesterday. It’s popular for a reason: it’s simple, visual, and just a little bit addictive. The fun part is seeing it tell a different story than the price chart itself, which feels a bit like watching a behind-the-scenes documentary instead of just the movie.

Today’s Motivation / Challenge

I wanted to give my tracker more “personality” by adding an indicator that can hint when prices might reverse. Also, part of me just wanted to prove to myself that I could wrestle with the math, the formatting, and Yahoo Finance’s occasional mood swings—and win.

Purpose of the Code (Object)

This code calculates the RSI for each stock I’m tracking, then tells me whether each one might be overbought, oversold, or just sitting in the middle lane. It takes the raw price data, does a little statistical gymnastics, and spits out a number that’s easy to read, even if you’ve never taken a finance class.

AI Prompt

Add an RSI tracker to my existing Code

Functions & Features

  • Calculate the 14-day RSI for each tracked stock.
  • Flag stocks as overbought (≥70), oversold (≤30), or neutral.
  • Handle messy or missing data without breaking the whole program.

Requirements / Setup

  • Python 3.x
  • pip install yfinance pandas numpy matplotlib

Minimal Code Sample

def _compute_rsi(series, period=14):

    delta = series.diff()

    gain = delta.clip(lower=0)

    loss = -delta.clip(upper=0)

    avg_gain = gain.ewm(alpha=1/period, adjust=False).mean()

    avg_loss = loss.ewm(alpha=1/period, adjust=False).mean()

    rs = avg_gain / avg_loss

    return 100 – (100 / (1 + rs))  # RSI formula

Calculates the RSI from closing prices using Wilder’s smoothing.

Stock Tracker

Notes / Lessons Learned


If there’s one thing RSI taught me, it’s that the market isn’t the only thing that can get moody—code can too. I ran into a storm of “err arg must be…” errors when pandas didn’t like the format of the data coming from Yahoo Finance. It wasn’t just the low-volume ETFs either; even TSLA decided to throw a tantrum. I tried to fix it, and in the process, managed to break other parts of my program.

After a frustrating 150 minutes of debugging, I threw in the towel and started fresh. One hour later—miracle!—it worked. The fixes? Making value conversions safer, checking Series length before indexing, and printing clear error messages. Then came the “not 1-D” ambush—some tickers return MultiIndex columns, which threw my code into existential crisis. The solution was to always extract a clean 1-D float series before running calculations. Now it runs without cryptic complaints, and I finally feel like I’ve tamed it… for now.

Optional Ideas for Expansion

  • Plot RSI alongside the price chart for a quick visual check.
  • Let the user choose the RSI period length (not just 14 days).
  • Add alerts for when a stock crosses the overbought/oversold thresholds.

The Long and Short of It: Moving Averages for Lazy Traders

Day 66 of 100 Days Coding Challenge: Python

I’ve added a new trick to my stock tracker: the moving average. Think of it as the “Zen master” of stock analysis—calm, collected, and uninterested in daily drama. I set it up so I can see both the short-term (7-day) moving average, which catches the mood swings, and the long-term (30-day) moving average, which reveals the bigger picture. Short-term trends tell you if a stock is suddenly sprinting, while long-term averages show if it’s been strolling uphill—or slowly rolling downhill—over time.

In finance, we do this on all sorts of timelines: monthly, quarterly, yearly. I’m not a day trader, so this isn’t about chasing every market twitch. Instead, this helps me filter out noise and focus on the broader trend—much like ignoring the gossip at the office and paying attention to the quarterly earnings report. In the future, I’d like to use this to spot “support” and “resistance” levels—that is, the invisible floor and ceiling where prices tend to bounce.

Today’s Motivation / Challenge

Daily stock prices are a roller coaster. Fun if you like screaming every 3 seconds, exhausting if you actually want to get somewhere. Moving averages smooth out the ride, letting you see if the track is going up, down, or looping sideways.

Purpose of the Code (Object)

This feature takes the recent stock prices for each symbol, calculates the 7-day and 30-day averages, and compares them to the most recent closing price. The result: a quick glance at short-term momentum versus long-term direction, without getting blinded by daily price noise.

AI Prompt

“Add a function to track the 7-day and 30-day moving averages of listed stocks, comparing each to the last closing price, and display the results clearly.”

Functions & Features

  • Calculates 7-day and 30-day simple moving averages (SMA).
  • Compares latest price to SMA values.
  • Displays trends for quick decision-making.

Requirements / Setup

pip install yfinance pandas

Minimal Code Sample

closes = hist[‘Close’]

last = float(closes.iloc[-1])  # Get most recent closing price

sma7 = closes.rolling(window=7).mean().iloc[-1]

sma30 = closes.rolling(window=30).mean().iloc[-1]

Calculates the last closing price and both moving averages.

Stock Tracker

Notes / Lessons Learned

The first time I ran this, Pandas wagged its finger at me with a “FutureWarning” about float(series). Apparently, in Pandas 2.2+, turning a whole Series into a single float is too vague. Imagine handing a librarian a 300-page book and saying, “Turn this into a number.” Which page, line, or word? Pandas now demands you be explicit:

  • .iloc[0] → picks the first element.
  • .item() → converts it directly to a Python number.

Once I cleaned up the code and restarted, it ran like a charm. And honestly, seeing my own program spit out these averages feels much better than refreshing some finance site.

Optional Ideas for Expansion

  • Add a chart to visualize SMA crossovers.
  • Let the user set custom time windows for moving averages.
  • Include alerts when the short-term average crosses the long-term average.

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.

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)