Skip to main content

My Python Program to Monitor Stock Price Momentum and Assign a Relative Strength Score

I have never tried creating a website with Python, but I do appreciate its vast libraries, simplicity, and speed for local programs. I don’t think there’s a simpler programming language for local coding. Today, I decided to share one of the tools in my investing arsenal: my custom Intraday Price Momentum Monitor. The name is quite old, and this latest draft assigns a Relative Strength Variable that I decided to call "momentum."

The program relies on Yahoo Finance for its API and vast resources available to the public—both investors and traders alike. Yahoo Finance is a tremendous resource for coding, information, news, and investing.

This program has become a great resource for me, significantly increasing my success in timing stock entries and exits after being prompted by my spreadsheets, which indicate when a stock has entered one of my target zones (buy or sell). The output provides the latest snapshot—taken every 20 seconds—of the stock price. It calculates the momentum of price movements, then records the intraday high and low. I decided to give the momentum a minimum and maximum score of -10 and 10, respectively, though after using it for several days, I question if that limit is necessary.

I wrote this with the idea of being able to call upon the function in other local Python programs. I am far from a Python professional, and I still question its speed and accuracy for server-side coding or handling MySQL data. Having past experience with PHP, writing Python came surprisingly easy. However, I don’t think Python would integrate easily with HTML to create dynamic websites. If I were creating a dynamic website, I would lean toward PHP over Python. The last version of PHP I learned was PHP 5, and I see that there have been more recent additions to the language. When it comes to writing code for a UI that relies on a web browser, I think PHP would be a lot easier and faster. That being said, for a local tool running on my hard drive, this is an asset I favor and prefer over looking at charts on my broker’s website.

Python Code for Stock Momentum Monitoring

Python Code:

import time
import yfinance as yf
from datetime import datetime, timedelta

def monitor_price():
    while True:
        ticker = input("Enter Ticker or 0 to Exit: ").upper()
        if ticker == "0":
            print("Exiting")
            break
        stock = yf.Ticker(ticker)
        p_price = None  # Previous price snapshot set after beginning
        momentum = 0  # Initialize momentum
        while True: # Create a basic loop
            now = datetime.now()
            market_close_time = datetime.strptime("16:00", "%H:%M").time()
            if now.weekday() >= 5 or not (datetime.strptime("09:30", "%H:%M").time() <= now.time() <= market_close_time):
                print("Market is closed or it's not a weekday. Exiting the Intraday Momentum Monitor.")
                time.sleep(5)
                break
            data = stock.history(period="1d", interval="1m")
            if data.empty:
                print("Failed to retrieve data for the ticker. Retry in 10 seconds.")
                time.sleep(10)
                continue
            day_low = round(float(data['Low'].min()), 2)
            day_high = round(float(data['High'].max()), 2)
            start_time = datetime.now()
            time_limit = timedelta(minutes=180)
            while True: # Basic Snapshot internal loop.
                now = datetime.now()
                if now.time() >= market_close_time:
                    print("Market has closed. Stopping price checks.")
                    break
                if now - start_time > time_limit:
                    print(f"Time limit of 180 minutes reached for monitoring {ticker}.")
                    break
                current_price = round(float(stock.history(period="1m").iloc[-1]['Close']), 2)
                if current_price < day_low:
                    day_low = current_price
                elif current_price > day_high:
                    day_high = current_price
                if p_price is not None:
                    if current_price > p_price:
                        momentum = min(momentum + 1, 10)
                    elif current_price < p_price:
                        momentum = max(momentum - 1, -10)
                print(f"{ticker} {current_price:.2f}  Momentum: {momentum}      Low: {day_low} High: {day_high}")
                p_price = current_price  # Update previous price
                time.sleep(20)
            break

if __name__ == "__main__":
    monitor_price()

Strengths and Weaknesses of This Code

Strengths:

  1. Simple and Effective: The script is straightforward, making it easy to use and modify.

  2. Real-Time Monitoring: It checks stock prices every 20 seconds, allowing for intraday tracking.

  3. Momentum Calculation: Assigns a momentum score to track price trends.

  4. User Input Flexibility: Allows the user to monitor different stocks dynamically.

  5. Market Timing Awareness: Stops execution if the market is closed, preventing unnecessary API calls.

Weaknesses:

  1. Rate Limits and API Calls: Since it fetches data every 20 seconds, it may hit Yahoo Finance’s rate limits, especially when monitoring multiple stocks (more than one PS window).

  2. Error Handling: If the API fails momentarily, the script does not efficiently retry fetching data.

  3. Hardcoded Time Limits: The script stops monitoring after 180 minutes, which may not be ideal for all traders. However, a decision is eventually made to either buy or sell, and I simply close the window after that occurs. Keep in mind that I am first prompted by a spreadsheet when a stock enters my set target. I also use alerts from my broker’s website.

  4. Inefficient Nested Loops: The structure of loops could be optimized to avoid redundant checks.

  5. Ticker History Fetching: Calls stock.history(period="1m") inside a loop, which may be unnecessary and cause performance issues.

This tool has proven invaluable in my trading strategy, helping me refine entry and exit points. While it’s not perfect, I continue to tweak it as I gain more insights from market behavior. Let me know what you think, and feel free to suggest improvements!

Disclaimer:
This is not Investing Advice and this program is not guaranteed to improve timing trades in the Stock Market. The Stock Market is very difficult to predict and/or anticipate.

Popular posts from this blog

How to Add Beneficiaries on E*TRADE Without Losing Your Mind

“Because your money should go where you want it, not where the probate court thinks it should, I am sharing this information.” Ah, E*TRADE. The place where your money grows, your trades execute (sometimes), and your hopes for financial freedom flutter like a candlestick chart on a volatile Thursday. But what happens if you kick the bucket before you get that Tesla stock to moon? Simple: you assign a beneficiary. Unfortunately, E*TRADE doesn’t make this as intuitive as you might think. This isn’t a “click here and boom, you’re immortal” situation. But fear not, fellow capitalist. I’ve braved the pixelated jungle so you don’t have to. 🛠️ Step-by-Step: Setting a Beneficiary for Your E*TRADE Brokerage Account (aka “How to ensure your money doesn’t end up in your ex’s lap or your neighbor's GoFundMe”) Log in at etrade.com . (Obvious, yes. But worth saying—this isn’t Webkinz, you need the real site.) At the top, click “Accounts” and select your Brokerage Account . (The on...

NJ's Middle-Class Squeeze: Too Much for Help, Not Enough for Comfort

This is a long post — longer than what I usually write — because what I’m talking about here isn’t a small annoyance or a passing frustration. It’s something that has been building for years, and I’m finally putting it all into words. I’m upset, I’m exhausted, and I’m passionate about what follows, because it affects every working person in this state who’s trying to stay afloat. There’s a growing group in New Jersey — people who work full‑time, sometimes more than one job, who earn too much to qualify for assistance but not enough to absorb the constant increases in living costs. These are the people tightening their budgets, lowering their thermostats, cutting back wherever they can, and still watching their bills rise for reasons that have nothing to do with their own usage or behavior. If you’re part of that group, or you know someone who is, then what follows will probably resonate with you. And if you’re not, then I hope this gives you a clearer picture of what the middle class i...

Understanding Treasury Bond Auctions: The Difference Between High Yield and Interest Rate

Treasury bonds are a popular choice for investors looking for a reliable source of income backed by the U.S. government. However, understanding how these bonds are priced at auction can be confusing, especially when comparing the High Yield and the Interest Rate (Coupon Rate) columns. In this post, I'll break it down using a real-world example.  A Look at a Recent Treasury Bond Auction Here’s an example of a 20-year Treasury bond that was recently auctioned: Security Term CUSIP Reopening Issue Date Maturity Date High Yield Interest Rate 20-Year 912810UF3 Yes 01/31/2025 11/15/2044 4.900% 4.625% What Do These Numbers Mean? CUSIP : This is a unique identifier for the bond. Reopening : Since it says "Yes," this means the bond was originally issued earlier and is now being reoffered. Issue Date : January 31, 2025—this is when the bond will be offi...