Back to Recipes

Yahoo Finance Data Downloader

Version 1.0.0

Description

This skill enables the Open Claw bot to download historical stock data from Yahoo Finance. The bot can fetch price data, volume, and other metrics for any stock ticker symbol.

Bot Prompt

"Download the last 6 months of stock data for AAPL from Yahoo Finance and save it as a CSV file"

Required Dependencies

pip install yfinance pandas

The bot should install these packages if not already available

Step-by-Step Instructions

Step 1: Import Required Libraries

import yfinance as yf
import pandas as pd
from datetime import datetime, timedelta

Step 2: Define Parameters

# Extract from user prompt
ticker = "AAPL"  # Stock symbol
period = "6mo"   # Time period (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max)
# OR use specific dates
start_date = "2024-09-01"
end_date = "2025-03-01"

Step 3: Download Data

# Method 1: Using period
data = yf.download(ticker, period=period)

# Method 2: Using specific dates
data = yf.download(ticker, start=start_date, end=end_date)

# For multiple tickers
data = yf.download(["AAPL", "GOOGL", "MSFT"], period="6mo")

Step 4: Save to CSV

# Generate filename
filename = f"{ticker}_data_{datetime.now().strftime('%Y%m%d')}.csv"

# Save to CSV
data.to_csv(filename)

print(f"Data saved to {filename}")
print(f"Downloaded {len(data)} rows of data")

Step 5: Display Summary

# Show basic info
print("\nData Summary:")
print(data.head())
print(f"\nDate range: {data.index[0]} to {data.index[-1]}")
print(f"Columns: {', '.join(data.columns)}")

Complete Example Script

import yfinance as yf
from datetime import datetime

def download_stock_data(ticker, period="6mo", output_file=None):
    """
    Download stock data from Yahoo Finance
    
    Args:
        ticker: Stock symbol (e.g., 'AAPL')
        period: Time period (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max)
        output_file: Optional custom filename
    """
    print(f"Downloading {ticker} data for period: {period}")
    
    # Download data
    data = yf.download(ticker, period=period, progress=False)
    
    if data.empty:
        print(f"Error: No data found for {ticker}")
        return None
    
    # Generate filename if not provided
    if output_file is None:
        output_file = f"{ticker}_data_{datetime.now().strftime('%Y%m%d')}.csv"
    
    # Save to CSV
    data.to_csv(output_file)
    
    print(f"✓ Successfully saved {len(data)} rows to {output_file}")
    print(f"Date range: {data.index[0].strftime('%Y-%m-%d')} to {data.index[-1].strftime('%Y-%m-%d')}")
    print(f"Columns: {', '.join(data.columns)}")
    
    return output_file

# Usage
if __name__ == "__main__":
    download_stock_data("AAPL", period="6mo")

Expected Output

Downloading AAPL data for period: 6mo
✓ Successfully saved 126 rows to AAPL_data_20260301.csv
Date range: 2024-09-01 to 2025-03-01
Columns: Open, High, Low, Close, Adj Close, Volume

Error Handling

  • If ticker symbol is invalid, yfinance returns empty DataFrame - check with data.empty
  • Network errors: Wrap in try-except block and retry with exponential backoff
  • Rate limiting: Yahoo Finance may throttle requests - add delays between multiple downloads
  • Missing data: Some tickers may have gaps - handle with data.fillna() or data.dropna()

Additional Examples

Download Multiple Stocks

tickers = ["AAPL", "GOOGL", "MSFT", "TSLA"]
for ticker in tickers:
    download_stock_data(ticker, period="1y")

Download with Specific Dates

data = yf.download("AAPL", start="2024-01-01", end="2024-12-31")
data.to_csv("AAPL_2024.csv")