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.