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.

Leave a Reply

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