Skip to content
TheChatArchiveThe Chat Archive
DeepSeekdeepseek-v3-0324· DeepSeekHugging Face LMArena Human Preference 140K

into the csv files are actually tickers. get the list and show me the stock values for…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514’s answer.
  1. User

    into the csv files are actually tickers. get the list and show me the stock values for the tickers.

  2. DeepSeek 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:

    1. CSV Parsing:

      • Reads semicolon-delimited, quoted CSV files
      • Handles tickers spread across multiple columns
      • Removes duplicate tickers while preserving order
    2. Stock Data Fetching:

      • Uses Yahoo Finance's API through the yfinance library
      • Gets the most recent available price (last close price)
      • Handles both single and multiple ticker cases
      • Gracefully handles invalid tickers
    3. 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
    4. Error Handling:

      • Handles file not found errors
      • Manages API request failures
      • Identifies invalid tickers

    Example Usage:

    1. First, create a CSV file named tickers.csv with content like:

      "AAPL";"MSFT";"GOOGL"
      "TSLA";"AMZN"
      "INVALIDTICKER"
      
    2. Run the script:

      python stock_prices.py --csv_filename tickers.csv
      
    3. 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
    • yfinance library (will be automatically installed if missing)
    • pandas (dependency of yfinance, will be installed automatically)

    The script will automatically install yfinance if it's not already available in your Python environment.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.