Stock Price Checker: Real-Time Stock Prices in Python
Stock Price Checker: Build a program that fetches and displays real-time stock prices.
Input values:
 1. Ticker symbol of the stock (e.g., AAPL, GOOGL, MSFT).
Output value:
- Real-time stock price of the given ticker symbol.
- Additional information (optional):
- Stock price change (amount and percentage) from the previous close.
- Market capitalization.
- Volume of shares traded.
Examples:
Example 1:
- Input:
- Ticker symbol: "AAPL"
- Output:
- Current price: $145.67
- Price change: +$1.23 (+0.85%)
- Market cap: $2.45T
- Volume: 76.89M
Example 2:
- Input:
- Ticker symbol: "GOOGL"
- Output:
- Current price: $2734.56
- Price change: -$15.78 (-0.57%)
- Market cap: $1.82T
- Volume: 1.23M
Solution 1: Using yfinance for Stock Price Checker
Download market data from Yahoo! Finance's API
Installation
pip install yfinance
This solution uses the yfinance library to fetch real-time stock data, including current stock price, price change, market capitalization, and volume.
Code:
# Importing necessary libraries
import yfinance as yf
# Solution 1: Fetch stock data using yfinance
def get_stock_data(ticker_symbol):
    # Download stock data for the given ticker symbol
    stock = yf.Ticker(ticker_symbol)
    # Get today's stock data
    stock_info = stock.history(period="1d")
    if len(stock_info) > 0:
        # Get current price
        current_price = stock_info['Close'].iloc[0]  # Get the first row
        # Check if there is a previous close available
        prev_close = stock.info.get('previousClose', current_price)  # Use previous close if available
        # Calculate price change and percentage change
        price_change = current_price - prev_close
        percentage_change = (price_change / prev_close) * 100 if prev_close != 0 else 0
        # Get market cap and volume
        market_cap = stock.info.get('marketCap', 'N/A')  # Handle cases where market cap may not be available
        volume = stock_info['Volume'].iloc[0]
        # Display stock information
        print(f"Current price: ${current_price:.2f}")
        print(f"Price change: ${price_change:.2f} ({percentage_change:.2f}%)")
        if market_cap != 'N/A':
            print(f"Market cap: ${market_cap/1e12:.2f}T")
        else:
            print("Market cap: N/A")
        print(f"Volume: {volume/1e6:.2f}M")
    else:
        print("No data available for this ticker.")
# Example usage:
ticker = input("Enter the stock ticker symbol (e.g., AAPL, GOOGL): ")
get_stock_data(ticker)
Output:
Enter the stock ticker symbol (e.g., AAPL, GOOGL): AAPL Current price: $235.86 Price change: $-0.62 (-0.26%) Market cap: $3.59T Volume: 34.96M
Enter the stock ticker symbol (e.g., AAPL, GOOGL): GOOGL Current price: $165.14 Price change: $1.07 (0.65%) Market cap: $2.04T Volume: 16.16M
Enter the stock ticker symbol (e.g., AAPL, GOOGL): NVDA Current price: $143.59 Price change: $-0.12 (-0.08%) Market cap: $3.52T Volume: 223.04M
Explanation:
- Import Libraries:
- The yfinance library is imported to fetch stock data from Yahoo Finance.
- Function Definition:
- The function get_stock_data(ticker_symbol) is defined to take a stock ticker symbol (e.g., AAPL, GOOGL) as input.
- Download Stock Data:
- stock = yf.Ticker(ticker_symbol) initializes the stock object for the given ticker symbol.
- stock_info = stock.history(period="1d") fetches the stock's historical data for the last day.
- Check for Data:
- The function checks if there is any data available using if len(stock_info) > 0:. If there is no data, it prints a message saying "No data available for this ticker."
- Fetch Current Price:
- current_price = stock_info['Close'].iloc[0] gets the closing price for the stock from today's data.
- Fetch Previous Close:
- prev_close = stock.info.get('previousClose', current_price) retrieves the previous close price. If it's unavailable, the function uses the current price as a fallback.
- Calculate Price Change and Percentage Change:
- price_change = current_price - prev_close calculates the difference between the current price and previous close.
- percentage_change = (price_change / prev_close) * 100 calculates the percentage change from the previous close. If prev_close is zero, the percentage is set to zero.
- Fetch Market Cap and Volume:
- market_cap = stock.info.get('marketCap', 'N/A') retrieves the market capitalization. If it's unavailable, it returns 'N/A'.
- volume = stock_info['Volume'].iloc[0] fetches today's trading volume.
- Display Stock Information:
- The function prints the current price, price change (both in dollars and percentage), market capitalization (in trillions, if available), and trading volume (in millions).
- Input and Function Call:
- The user is prompted to input a stock ticker symbol with ticker = input("Enter the stock ticker symbol (e.g., AAPL, GOOGL): ").
- The function get_stock_data(ticker) is called with the user’s input to display the stock information.
Solution 2: Using requests and Alpha Vantage API
This solution uses the requests library to fetch stock data from Alpha Vantage API, which provides real-time stock prices and additional financial information.
Code:
 # Import necessary libraries
import requests
# Solution 2: Fetch stock data using Alpha Vantage API
def get_stock_data_alpha_vantage(ticker_symbol, api_key):
    # API URL to get stock data
    url = f"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={ticker_symbol}&interval=1min&apikey={api_key}"
    
    # Fetch stock data from Alpha Vantage
    response = requests.get(url)
    data = response.json()
    
    # Extract stock information
    time_series = data["Time Series (1min)"]
    latest_time = list(time_series.keys())[0]
    latest_data = time_series[latest_time]
    current_price = float(latest_data["4. close"])
    
    # Additional info (previous close and volume)
    previous_close = float(latest_data["1. open"])
    price_change = current_price - previous_close
    percentage_change = (price_change / previous_close) * 100
    volume = int(latest_data["5. volume"])
    
    # Display stock information
    print(f"Current price: ${current_price:.2f}")
    print(f"Price change: ${price_change:.2f} ({percentage_change:.2f}%)")
    print(f"Volume: {volume:,}")
    
# Example usage:
ticker = input("Enter the stock ticker symbol (e.g., AAPL, GOOGL): ")
api_key = "your_alpha_vantage_api_key"
get_stock_data_alpha_vantage(ticker, api_key)
Output:
Enter the stock ticker symbol (e.g., AAPL, GOOGL): MSFT Current price: $426.80 Price change: $0.00 (0.00%) Volume: 539
Enter the stock ticker symbol (e.g., AAPL, GOOGL): TSLA Current price: $217.49 Price change: $-0.01 (-0.00%) Volume: 3,181
Explanation:
- Uses the requests library to fetch stock data from Alpha Vantage.
- This requires an API key.
- Extracts the latest stock price, price change, percentage change, and volume from the API response.
Go to:
