into the csv files are actually tickers. get the list and show me the stock values for…
- User
into the csv files are actually tickers. get the list and show me the stock values for the tickers.
Assistant
Here's a Python script that reads a CSV file containing stock tickers (semicolon-delimited, quoted fields), fetches their current stock prices using the Yahoo Finance API (
yfinance), and displays the results:import csv import argparse import yfinance as yf from datetime import datetime def parse_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser(description='Fetch stock prices for tickers in a CSV file.') parser.add_argument('--csv_filename', type=str, required=True, help='Path to the CSV file containing tickers.') return parser.parse_args() def read_tickers(filename): """Read tickers from the CSV file.""" tickers = [] try: with open(filename, 'r') as file: csv_reader = csv.reader(file, delimiter=';', quotechar='"') for row in csv_reader: # Flatten the row in case tickers are in multiple columns tickers.extend([ticker.strip() for ticker in row if ticker.strip()]) except FileNotFoundError: print(f"Error: The file '{filename}' was not found.") exit(1) except Exception as e: print(f"An error occurred while reading the CSV: {e}") exit(1) return tickers def fetch_stock_prices(tickers): """Fetch current stock prices for the given tickers.""" if not tickers: print("No tickers found in the CSV file.") return {} # Remove duplicates while preserving order unique_tickers = list(dict.fromkeys(tickers)) try: # Fetch current market data data = yf.download( tickers=unique_tickers, period="1d", interval="1m", group_by='ticker', progress=False ) # Get the last available price (most recent) prices = {} for ticker in unique_tickers: try: if len(unique_tickers) == 1: # Single ticker case has different data structure last_price = data['Close'].iloc[-1] else: last_price = data[ticker]['Close'].iloc[-1] prices[ticker] = round(last_price, 2) except (KeyError, AttributeError): prices[ticker] = "N/A (Invalid ticker or no data)" return prices except Exception as e: print(f"Error fetching stock prices: {e}") return {ticker: "Error fetching data" for ticker in unique_tickers} def display_results(prices): """Display the stock prices in a formatted table.""" if not prices: print("No stock prices to display.") return print("\nCurrent Stock Prices:") print("-" * 40) print(f"{'Ticker':<10}{'Price':>15}") print("-" * 40) for ticker, price in prices.items(): if isinstance(price, (int, float)): print(f"{ticker:<10}${price:>14.2f}") else: print(f"{ticker:<10}{price:>15}") print("-" * 40) print(f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") def main(): args = parse_args() tickers = read_tickers(args.csv_filename) prices = fetch_stock_prices(tickers) display_results(prices) if __name__ == "__main__": # Install yfinance if not already installed try: import yfinance except ImportError: print("Installing yfinance...") import subprocess import sys subprocess.check_call([sys.executable, "-m", "pip", "install", "yfinance"]) main()Key Features:
-
CSV Parsing:
- Reads semicolon-delimited, quoted CSV files
- Handles tickers spread across multiple columns
- Removes duplicate tickers while preserving order
-
Stock Data Fetching:
- Uses Yahoo Finance's API through the
yfinancelibrary - Gets the most recent available price (last close price)
- Handles both single and multiple ticker cases
- Gracefully handles invalid tickers
- Uses Yahoo Finance's API through the
-
Output Formatting:
- Displays results in a clean table format
- Shows prices in USD with proper alignment
- Includes a timestamp of when the data was fetched
-
Error Handling:
- Handles file not found errors
- Manages API request failures
- Identifies invalid tickers
Example Usage:
-
First, create a CSV file named
tickers.csvwith content like:"AAPL";"MSFT";"GOOGL" "TSLA";"AMZN" "INVALIDTICKER" -
Run the script:
python stock_prices.py --csv_filename tickers.csv -
Sample output:
Current Stock Prices: ---------------------------------------- Ticker Price ---------------------------------------- AAPL $189.98 MSFT $420.72 GOOGL $142.56 TSLA $172.63 AMZN $177.23 INVALIDTICKER N/A (Invalid ticker or no data) ---------------------------------------- Last updated: 2023-11-20 14:30:45
Requirements:
- Python 3.x
yfinancelibrary (will be automatically installed if missing)pandas(dependency of yfinance, will be installed automatically)
The script will automatically install
yfinanceif it's not already available in your Python environment.-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.