Live Stock Price Tracker Python Script

This Python script fetches live stock prices for a specified ticker using the yfinance library and logs the data with a timestamp into a CSV file for further analysis. It provides an easy way to monitor and record real-time market price movements.

If you haven’t installed yfinance yet, you can easily add it by running the following command in your terminal:

pip install yfinance
Click to view script…
#!/usr/bin/env python3
import yfinance as yf
import csv
import os
from datetime import datetime

def fetch_stock_price(ticker_symbol):
    """
    Fetches the current stock price for the given ticker symbol using yfinance.
    It first tries to get the 'regularMarketPrice' from the ticker info.
    If that fails, it falls back to using the latest close price from recent historical data.
    """
    ticker = yf.Ticker(ticker_symbol)
    try:
        # Attempt to get the live price from the info dictionary
        info = ticker.info
        price = info.get("regularMarketPrice", None)
        if price is None:
            # Fallback: get the most recent closing price from historical data
            data = ticker.history(period="1d", interval="1m")
            price = data["Close"].iloc[-1]
    except Exception as e:
        print(f"Error fetching data for {ticker_symbol}: {e}")
        return None
    return price

def store_stock_price(ticker_symbol, price, filename="stock_prices.csv"):
    """
    Stores the fetched stock price along with a timestamp and the ticker symbol into a CSV file.
    If the file does not exist, it creates one with appropriate headers.
    """
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    header = ["timestamp", "ticker", "price"]
    file_exists = os.path.isfile(filename)
    
    with open(filename, mode="a", newline="") as file:
        writer = csv.writer(file)
        if not file_exists:
            writer.writerow(header)
        writer.writerow([now, ticker_symbol, price])
    
    print(f"Stored price for {ticker_symbol} at {now} in {filename}.")

def main():
    print("Stock Price Tracker")
    print("-------------------")
    print("Fetches live stock prices and stores them for analysis.\n")
    
    ticker_symbol = input("Enter the stock ticker (e.g., AAPL): ").strip().upper()
    if not ticker_symbol:
        print("No ticker entered. Exiting.")
        return
    
    price = fetch_stock_price(ticker_symbol)
    if price is not None:
        print(f"Current price of {ticker_symbol}: ${price:.2f}")
        store_stock_price(ticker_symbol, price)
    else:
        print("Failed to fetch stock price.")

if __name__ == "__main__":
    main()