You are currently viewing

To create a script that searches for stock information using the ‘Ticker’ from Yahoo Finance, we can utilize Python along with the yfinance library. The yfinance library allows us to easily fetch stock data from Yahoo Finance. Below is an outline of how the program will work:

  1. Ask the user for the stock ticker symbol they want to analyze.
  2. Fetch stock data using the yfinance library.
  3. Perform analysis on the fetched data (e.g., historical data, moving averages, etc.)
  4. Display the results.

Steps:

  • Install the necessary libraries (yfinancematplotlib, etc.).
  • Ask the user for input.
  • Fetch and analyze the stock data.
  • Display the analysis results.

Step 1: Install Required Libraries

First, ensure you have the required libraries installed by running:

Bashpip install yfinance matplotlib pandas

Step 2: Python Script

Pythonimport yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt

def get_stock_data(ticker_symbol):
    """
    Fetches stock data for the given ticker symbol.
    """
    try:
        stock = yf.Ticker(ticker_symbol)
        # Get historical market data for the last 30 days
        hist = stock.history(period="30d")
        if hist.empty:
            print(f"No data found for ticker symbol: {ticker_symbol}")
            return None
        return hist
    except Exception as e:
        print(f"Error fetching data for {ticker_symbol}: {e}")
        return None

def analyze_stock(hist):
    """
    Performs basic analysis on the stock data (e.g., Moving Averages).
    """
    if hist is None:
        return
    
    # Calculate Simple Moving Averages (SMA)
    hist['SMA_5'] = hist['Close'].rolling(window=5).mean()
    hist['SMA_10'] = hist['Close'].rolling(window=10).mean()

    # Print some analysis results
    print("\nStock Analysis:")
    print("Latest Close Price:", hist['Close'][-1])
    print("5-Day SMA:", hist['SMA_5'][-1])
    print("10-Day SMA:", hist['SMA_10'][-1])

    return hist

def plot_stock_data(hist):
    """
    Plots the stock's closing price and moving averages.
    """
    if hist is None:
        return
    
    plt.figure(figsize=(12, 6))
    
    # Plot the closing prices
    plt.plot(hist.index, hist['Close'], label='Close Price', color='blue')
    
    # Plot the 5-day SMA
    plt.plot(hist.index, hist['SMA_5'], label='5-Day SMA', color='orange')
    
    # Plot the 10-day SMA
    plt.plot(hist.index, hist['SMA_10'], label='10-Day SMA', color='green')
    
    # Add title and labels
    plt.title('Stock Price and Moving Averages')
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.legend()
    plt.grid(True)
    
    # Show the plot
    plt.show()

def main():
    # Prompt the user for the stock ticker symbol
    ticker_symbol = input("Enter the stock ticker symbol you want to analyze (e.g., AAPL, MSFT): ").strip().upper()
    
    # Fetch stock data
    hist = get_stock_data(ticker_symbol)
    
    # Analyze the stock data
    analyzed_data = analyze_stock(hist)
    
    # Plot the stock data
    if analyzed_data is not None:
        plot_stock_data(analyzed_data)

if __name__ == "__main__":
    main()

Explanation of the Code:

  1. get_stock_data Function:
    • This function takes a stock ticker symbol as input and fetches historical stock data using the yfinance library. It retrieves the last 30 days of data by default.
  2. analyze_stock Function:
    • This function calculates two simple moving averages (SMA) for the stock: 5-day and 10-day SMAs.
    • It also prints out the latest close price and the calculated SMAs.
  3. plot_stock_data Function:
    • This function uses matplotlib to plot the stock’s closing price along with the 5-day and 10-day SMAs.
  4. main Function:
    • The main function prompts the user for the stock ticker symbol, fetches the data, analyzes it, and then plots the results.

Example Usage:

When you run the script, it will prompt you for a stock ticker symbol:

BashEnter the stock ticker symbol you want to analyze (e.g., AAPL, MSFT): AAPL

After entering the ticker symbol (e.g., “AAPL”), the script will:

  1. Fetch the historical data for Apple Inc. (AAPL) over the last 30 days.
  2. Perform basic analysis, including calculating the 5-day and 10-day moving averages.
  3. Plot the stock’s closing price along with the moving averages.

Sample Output:

Enter the stock ticker symbol you want to analyze (e.g., AAPL, MSFT): AAPL

Stock Analysis:
Latest Close Price: 145.89000701904297
5-Day SMA: 146.123454
10-Day SMA: 145.987654

A plot will also appear showing the stock’s closing price and the moving averages.

Notes:

  • You can modify the period in stock.history(period="30d") to fetch more or less historical data.
  • You can add more sophisticated analysis techniques like RSI, MACD, etc., depending on your needs.
  • Ensure that the yfinance library is up-to-date to avoid any issues with fetching data.

Leave a Reply