Skip to content

Instantly share code, notes, and snippets.

@oNddleo
Last active March 10, 2025 09:44
Show Gist options
  • Save oNddleo/6b8d1e56f0166352f9ce2d9970b7a2c5 to your computer and use it in GitHub Desktop.
Save oNddleo/6b8d1e56f0166352f9ce2d9970b7a2c5 to your computer and use it in GitHub Desktop.
SpdjIndex

I'll provide you with an example of using the sane_finances library to export S&P Dow Jones Indices (SPDJI) data in Python.

from decimal import Decimal
from datetime import date, datetime
import pandas as pd
from sane_finances.sources.spdji.v2021.exporters import SpdjIndicesExporter
from sane_finances.sources.spdji.v2021.parsers import SpdjIndicesParser

def export_spdji_index(index_code, start_date, end_date, output_file=None):
    """
    Export S&P Dow Jones Index data using sane_finances library.
    
    Parameters:
    -----------
    index_code : str
        The code of the index to export (e.g., 'SP500')
    start_date : date
        The start date for data retrieval
    end_date : date
        The end date for data retrieval
    output_file : str, optional
        If provided, save data to this file (CSV format)
    
    Returns:
    --------
    pandas.DataFrame
        DataFrame containing the exported index data
    """
    # Initialize the exporter and parser
    exporter = SpdjIndicesExporter()
    parser = SpdjIndicesParser()
    
    # Get the data
    raw_data = exporter.export_daily_values(
        index_code=index_code,
        moment_from=start_date,
        moment_to=end_date
    )
    
    # Parse the data
    parsed_values = parser.parse(raw_data)
    
    # Convert to pandas DataFrame for easier manipulation
    data = []
    for value in parsed_values:
        data.append({
            'date': value.moment,
            'value': float(value.value),
            'index_code': index_code
        })
    
    df = pd.DataFrame(data)
    
    # Sort by date
    df = df.sort_values('date')
    
    # Save to file if requested
    if output_file:
        df.to_csv(output_file, index=False)
        print(f"Data saved to {output_file}")
    
    return df

# Example usage
if __name__ == "__main__":
    # Export S&P 500 data for the last year
    today = date.today()
    one_year_ago = date(today.year - 1, today.month, today.day)
    
    # Export data
    sp500_data = export_spdji_index(
        index_code="SP500",
        start_date=one_year_ago,
        end_date=today,
        output_file="sp500_data.csv"
    )
    
    # Display first few rows
    print(sp500_data.head())
    
    # Simple visualization
    try:
        import matplotlib.pyplot as plt
        
        plt.figure(figsize=(12, 6))
        plt.plot(sp500_data['date'], sp500_data['value'])
        plt.title('S&P 500 Index')
        plt.xlabel('Date')
        plt.ylabel('Index Value')
        plt.grid(True)
        plt.tight_layout()
        plt.savefig('sp500_chart.png')
        plt.show()
    except ImportError:
        print("Matplotlib not available for visualization")

This example demonstrates how to:

  1. Set up the SPDJI exporter and parser from the sane_finances library
  2. Export daily values for a specific index (SP500 in this case)
  3. Parse the data and convert it to a pandas DataFrame
  4. Save the data to a CSV file
  5. Create a simple visualization of the data

To use different indices, you would change the index_code parameter. Common S&P Dow Jones indices include:

  • "SP500" (S&P 500)
  • "DJIA" (Dow Jones Industrial Average)
  • "SPX" (S&P 500)
  • "NDX" (Nasdaq-100)

Would you like me to provide more details about any specific part of this example?​​​​​​​​​​​​​​​​

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment