[Python] Importing data in Python frol yfinance works except for AJ Close (Adjusted Close)

Discussão em 'Python' iniciado por Stack, Abril 9, 2025.

  1. Stack

    Stack Membro Participativo

    This code works fine if you replace Adj Close with Open or Close. I can't work out why Adj Close, which is what I want, does not work. I run this as a Jupyter Notebook after having installed yfinance. I would really appreciate your suggestions. Here is the code followed by the output.

    # Import necessary libraries
    import yfinance as yf
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    from datetime import datetime, timedelta
    import os

    # Set the style for plots
    plt.style.use('seaborn-v0_8-darkgrid')
    sns.set_palette("viridis")
    plt.rcParams['figure.figsize'] = (12, 8)
    plt.rcParams['font.size'] = 12

    # Define the major stock indices to analyze
    indices = {
    'S&P 500': '^GSPC', # United States
    'Dow Jones': '^DJI', # United States
    'NASDAQ': '^IXIC', # United States
    'FTSE 100': '^FTSE', # United Kingdom
    'DAX': '^GDAXI', # Germany
    'CAC 40': '^FCHI', # France
    'Nikkei 225': '^N225', # Japan
    'ASX 200': '^AXJO', # Australia
    'TSX': '^GSPTSE', # Canada
    'FTSE MIB': 'FTSEMIB.MI' # Italy
    }

    # Define the time period for the data
    end_date = datetime.now()
    start_date = end_date - timedelta(days=365*10) # 10 years of data

    print(f"Collecting weekly returns data from {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}")

    # Function to download data and calculate weekly returns
    def get_weekly_returns(ticker, start_date, end_date):
    try:
    # Download the data
    data = yf.download(ticker, start=start_date, end=end_date, interval='1wk')

    # Calculate weekly returns
    data['Weekly_Return'] = data['Adj Close'].pct_change()

    # Drop NaN values
    data = data.dropna()

    return data['Weekly_Return']
    except Exception as e:
    print(f"Error downloading data for {ticker}: {e}")
    return pd.Series(dtype='float64')

    # Collect weekly returns for all indices
    all_returns = pd.DataFrame()

    for name, ticker in indices.items():
    print(f"Downloading data for {name} ({ticker})...")
    returns = get_weekly_returns(ticker, start_date, end_date)

    if not returns.empty:
    all_returns[name] = returns
    else:
    print(f"No data available for {name}. Skipping.")

    # Save the data to a CSV file
    csv_file = 'weekly_returns_major_indices.csv'
    all_returns.to_csv(csv_file)

    print(f"Data successfully saved to {csv_file}")
    print(f"Total number of weeks: {len(all_returns)}")
    print(f"Indices included: {', '.join(all_returns.columns)}")

    # Display the first few rows of the data
    all_returns.head()


    If you replace data['Adj Close'] with data['Close'] or data['Open'], it all works fine. I see data['Adj Close'] used in plenty of code snippets including here and indices do have an adjusted close, like individual stocks, so I really don't know what's happening.

    yfinance version is 0.2.55. Wayne provided two posts (I searched only using Adjusted Close in full. My mistake. Thank you for your patience.)

    Continue reading...

Compartilhe esta Página