pyfolio-reloaded

repository·main·Indexed 20 days ago

https://github.com/stefan-jansen/pyfolio-reloaded

A Python library for the performance and risk analysis of financial portfolios. It provides comprehensive 'tear sheets' containing metrics and time-series plots, and is specifically designed to work with the Zipline backtesting engine. Key features include performance attribution, round trip analysis, sector-based PnL reporting, and liquidity analysis such as estimating days to liquidate positions and applying quadratic slippage penalties.

Tokens
16.2K
Snippets
87
Records
99
Agent score
67%

What's inside pyfolio-reloaded

  1. Analyze trading strategies using tear sheets

    main

    The core functionality of pyfolio is the generation of "tear sheets". A tear sheet is a comprehensive report that combines individual plots and summary statistics to provide a view of a trading algorithm's performance.

    Key components of a tear sheet include:

    • Performance Metrics: Displays performance and risk metrics separately for backtest and out-of-sample periods.
    • Performance Plots: Visualizes how various risk and return metrics behave over time.

    pyfolio is designed to work well with the Zipline backtesting library.

  2. Use benchmarks for comparative analysis

    main

    In versions 0.9.0 and later, pyfolio is completely independent of benchmarks. This allows for the analysis of international equities and alternative data sets without requiring a U.S. market benchmark like SPY.

    • If a benchmark is passed to the analysis functions, all benchmark-related analyses will be performed.
    • If no benchmark is passed, benchmark-related analyses will simply be skipped.
  3. Install pyfolio-reloaded for development

    main

    To contribute to or develop pyfolio-reloaded, it is recommended to use a virtual environment.

    1. Create a virtual environment (e.g., using virtualenvwrapper):
    mkvirtualenv pyfolio
    1. Clone the repository.
    2. Install the package in editable mode with all dependencies:
    python -m pip install .[all]
    mkvirtualenv pyfolio
    python -m pip install .[all]
  4. Run pyfolio examples in Jupyter Notebook

    main

    The best way to explore pyfolio is by running the provided examples in a Jupyter notebook.

    1. Start a Jupyter notebook server:
    jupyter notebook
    1. From the notebook interface, navigate to the pyfolio/examples directory.
    2. Open an example notebook and execute cells using Shift+Enter.
  5. Generate sector allocation and PnL plots using sector mappings

    main

    To include sector-based analysis in your performance reports, you must provide a dictionary (or dict-like structure) where the keys are asset symbols and the values are their corresponding sectors.

    Providing these mappings allows pyfolio to:

    1. Generate sector allocation plots within the positions tearsheet.
    2. Generate PnL by sector within the round trips tearsheet.

    You can pass this dictionary to create_position_tear_sheet or to the high-level create_full_tearsheet function using the sector_mappings keyword argument.

    # Define your mapping: {symbol: sector}
    sect_map = {
        'COST': 'Consumer Goods',
        'INTC': 'Technology',
        'CERN': 'Healthcare',
        'GPS': 'Technology',
        'MMM': 'Construction',
        'DELL': 'Technology',
        'AMD': 'Technology'
    }
    
    # Use in position tear sheet
    pf.create_position_tear_sheet(returns, positions, sector_mappings=sect_map)
    
    # Use in round trip tear sheet
    pf.create_round_trip_tear_sheet(returns, positions, transactions, sector_mappings=sect_map)
    
    # Use in full tear sheet
    pf.create_full_tearsheet(returns, positions, sector_mappings=sect_map)
  6. Prepare time-series data for pyfolio

    main

    Pyfolio requires input data to be timezone-aware and set to the UTC timezone. When using yfinance to fetch stock history, you must explicitly localize the index to UTC to avoid errors during analysis.

    To prepare returns:

    1. Download history using yf.Ticker.history().
    2. Localize the index using .tz_localize('utc').
    3. Calculate percentage changes on the price column (e.g., Close) to create a returns series.
    import yfinance as yf
    import pyfolio as pf
    
    # Download data
    fb = yf.Ticker('FB')
    history = fb.history('max')
    
    # CRITICAL: Pyfolio expects tz-aware input set to UTC timezone
    history.index = history.index.tz_localize('utc')
    
    # Calculate returns
    returns = history.Close.pct_change()