Here's a Python script that reads ticker symbols from a CSV file and fetches their current stock prices:
#!/usr/bin/env python3
import csv
import argparse
import yfinance as yf
import pandas as pd
from datetime import datetime
def read_tickers_from_csv(csv_filename):
"""Read ticker symbols from a CSV file with semicolon separators and quoted fields."""
tickers = []
try:
with open(csv_filename, 'r', encoding='utf-8') as file:
csv_reader = csv.reader(file, delimiter=';', quotechar='"')
for row in csv_reader:
# Add all non-empty fields from each row as potential tickers
for field in row:
field = field.strip()
if field: # Only add non-empty fields
tickers.append(field.upper()) # Convert to uppercase
except FileNotFoundError:
print(f"Error: File '{csv_filename}' not found.")
return []
except Exception as e:
print(f"Error reading file: {e}")
return []
return tickers
def get_stock_prices(tickers):
"""Fetch current stock prices for a list of ticker symbols."""
if not tickers:
print("No tickers found.")
return
print(f"Fetching stock data for {len(tickers)} tickers...\n")
# Remove duplicates while preserving order
unique_tickers = list(dict.fromkeys(tickers))
results = []
for ticker in unique_tickers:
try:
# Create yfinance Ticker object
stock = yf.Ticker(ticker)
# Get current stock info
info = stock.info
hist = stock.history(period="1d")
if not hist.empty:
current_price = hist['Close'].iloc[-1]
previous_close = info.get('previousClose', current_price)
change = current_price - previous_close
change_percent = (change / previous_close) * 100 if previous_close != 0 else 0
results.append({
'Ticker': ticker,
'Company': info.get('longName', 'N/A'),
'Current Price': f"${current_price:.2f}",
'Previous Close': f"${previous_close:.2f}",
'Change': f"${change:.2f}",
'Change %': f"{change_percent:.2f}%",
'Volume': f"{info.get('volume', 'N/A'):,}" if info.get('volume') else 'N/A'
})
else:
results.append({
'Ticker': ticker,
'Company': 'Data not available',
'Current Price': 'N/A',
'Previous Close': 'N/A',
'Change': 'N/A',
'Change %': 'N/A',
'Volume': 'N/A'
})
except Exception as e:
print(f"Error fetching data for {ticker}: {e}")
results.append({
'Ticker': ticker,
'Company': 'Error fetching data',
'Current Price': 'N/A',
'Previous Close': 'N/A',
'Change': 'N/A',
'Change %': 'N/A',
'Volume': 'N/A'
})
return results
def print_stock_data(results):
"""Print stock data in a formatted table."""
if not results:
return
# Create DataFrame for better formatting
df = pd.DataFrame(results)
print("=" * 120)
print(f"{'STOCK PRICES':^120}")
print(f"{'Updated: ' + datetime.now().strftime('%Y-%m-%d %H:%M:%S'):^120}")
print("=" * 120)
# Print formatted table
print(f"{'Ticker':<10} {'Company':<30} {'Price':<12} {'Prev Close':<12} {'Change':<10} {'Change %':<10} {'Volume':<15}")
print("-" * 120)
for _, row in df.iterrows():
print(f"{row['Ticker']:<10} {row['Company'][:29]:<30} {row['Current Price']:<12} "
f"{row['Previous Close']:<12} {row['Change']:<10} {row['Change %']:<10} {row['Volume']:<15}")
def main():
parser = argparse.ArgumentParser(description='Read ticker symbols from CSV and fetch stock prices')
parser.add_argument('--csv_filename', type=str, required=True,
help='Path to the CSV file containing ticker symbols')
args = parser.parse_args()
print(f"Reading tickers from: {args.csv_filename}")
# Read tickers from CSV
tickers = read_tickers_from_csv(args.csv_filename)
if tickers:
print(f"Found tickers: {', '.join(tickers)}\n")
# Get stock prices
stock_data = get_stock_prices(tickers)
# Print results
print_stock_data(stock_data)
else:
print("No valid tickers found in the CSV file.")
if __name__ == "__main__":
main()
To use this script, you'll need to install the required dependencies:
pip install yfinance pandas
Then run the script:
python stock_ticker_reader.py --csv_filename your_tickers.csv
The script will:
- Read ticker symbols from your CSV file (handling semicolon separators and quoted fields)
- Remove duplicates and convert tickers to uppercase
- Fetch current stock data using the Yahoo Finance API
- Display a formatted table showing:
- Ticker symbol
- Company name
- Current price
- Previous close
- Price change (dollar amount and percentage)
- Trading volume
For example, if your CSV contains:
"AAPL";"GOOGL";"MSFT"
"TSLA";"AMZN"
The script will fetch and display current stock prices for Apple, Google, Microsoft, Tesla, and Amazon.