2 min read

Stock Market Data Fetcher

This utility fetches stock market data using the yfinance library, which offers a reliable way to download historical market data from Yahoo Finance. It can retrieve current prices, historical data for analysis, and company information.

Modules Used:

  • yfinance: To fetch financial data from Yahoo Finance.
  • pandas: To handle and display the data in a tabular format.
  • argparse: To handle command-line arguments.

Installation

pip install yfinance pandas

The Code

Save this as stock_fetcher.py.

import yfinance as yf
import argparse
import sys

def get_stock_data(ticker_symbol, period="1mo", info=False):
    print(f"Fetching data for: {ticker_symbol.upper()}...")

    try:
        # Create Ticker object
        ticker = yf.Ticker(ticker_symbol)

        # 1. Get Basic Info
        if info:
            print("\n--- Company Info ---")
            # info is a dictionary with many keys
            i = ticker.info
            print(f"Name: {i.get('longName', 'N/A')}")
            print(f"Sector: {i.get('sector', 'N/A')}")
            print(f"Current Price: {i.get('currentPrice', 'N/A')}")
            print(f"Market Cap: {i.get('marketCap', 'N/A')}")
            print(f"Summary: {i.get('longBusinessSummary', 'N/A')[:200]}...")

        # 2. Get Historical Data
        # valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
        history = ticker.history(period=period)

        if history.empty:
            print("No historical data found.")
            return

        print(f"\n--- Historical Data ({period}) ---")
        # Reset index to make Date a column for printing
        print(history<a href='/%27Open%27%2C%20%27High%27%2C%20%27Low%27%2C%20%27Close%27%2C%20%27Volume%27'>'Open', 'High', 'Low', 'Close', 'Volume'</a>.tail())

        # Optional: Save to CSV
        # history.to_csv(f"{ticker_symbol}_{period}.csv")
        # print(f"\nSaved to {ticker_symbol}_{period}.csv")

    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Stock Market Data Fetcher")
    parser.add_argument("ticker", help="Stock Ticker Symbol (e.g., AAPL, MSFT)")
    parser.add_argument("-p", "--period", default="1mo", 
                        choices=['1d','5d','1mo','3mo','6mo','1y','2y','5y','10y','ytd','max'],
                        help="Data period to download (default: 1mo)")
    parser.add_argument("--info", action="store_true", help="Show company information")

    args = parser.parse_args()

    get_stock_data(args.ticker, args.period, args.info)

Usage

# Get last month of data for Apple
python stock_fetcher.py AAPL

# Get company info and 1 year of history for Microsoft
python stock_fetcher.py MSFT --period 1y --info

programming/python/python