Using pyfolio for Portfolio Risk Analytics and Tear Sheets: A Complete Guide

pyfolio is a Python library that transforms raw backtest returns into professional tear sheets visualizing cumulative performance, drawdown periods, risk-adjusted metrics, and factor exposures.

The paperswithbacktest/awesome-systematic-trading repository recognizes pyfolio as an essential tool for systematic strategy evaluation, listing it in the curated resources table of README.md. While the repository does not maintain its own fork of the library, it provides numerous static strategy scripts in static/strategies/ that generate the exact pandas data structures pyfolio requires for risk analysis.

What is pyfolio?

pyfolio is an open-source Python library designed for portfolio performance and risk analytics. It consumes time-series data—specifically returns as a pandas.Series and optional positions as a pandas.DataFrame—to compute a comprehensive set of financial metrics. The library automatically generates a tear sheet, a single-page HTML or PDF report containing interactive visualizations of cumulative returns, drawdown analysis, rolling Sharpe ratios, and sector exposures.

Architecture and Workflow

pyfolio operates as the analytics layer in a three-stage pipeline. According to the repository structure in paperswithbacktest/awesome-systematic-trading, you can feed outputs from any backtest engine directly into pyfolio without data transformation.

Data Ingestion

Your backtest engine—whether custom code or third-party libraries—must produce a daily or weekly time-series of portfolio returns. The static/strategies/ folder contains example scripts that output precisely this format, typically as CSV files with date-indexed return columns.

Risk Analytics Engine

pyfolio computes statistics such as maximum drawdown, volatility, beta, and alpha. These calculations happen internally when you invoke the tear sheet creation functions.

Tear Sheet Generation

The final stage renders multiple matplotlib visualizations into a cohesive report. The entry point pyfolio.create_returns_tear_sheet orchestrates this process, accepting your returns series and optional benchmark data.

Implementing pyfolio with Strategy Backtests

To integrate pyfolio with strategies from the repository, load your backtest results and pass them to the tear sheet generator. The following example assumes you have executed a strategy from static/strategies/ and saved the returns to CSV.

import pandas as pd
import pyfolio as pf
import matplotlib.pyplot as plt

# Load daily returns from a backtested strategy

returns = pd.read_csv('data/strategy_returns.csv',
                      parse_dates=['date'],
                      index_col='date')['return']

# Optional: Load position data for exposure analysis

# positions = pd.read_csv('data/positions.csv', 

#                        parse_dates=['date'], 

#                        index_col='date')

# Generate the full tear sheet

pf.create_returns_tear_sheet(
    returns,
    benchmark_rets=None,   # Add benchmark series here for comparison

    live_start_date=None,  # Date when strategy went live (for out-of-sample analysis)

    # pos=positions        # Uncomment if providing position data

)
plt.show()

This workflow applies to any strategy notebook in static/strategies/ that outputs a time-indexed return series.

Understanding Tear Sheet Components

The tear sheet produced by pyfolio.create_returns_tear_sheet contains several analytical sections:

  • Cumulative Returns: Tracks portfolio growth over time versus a benchmark.
  • Drawdown Analysis: Identifies peak-to-trough declines and recovery periods, critical for setting stop-loss levels.
  • Rolling Sharpe Ratio: Displays risk-adjusted returns over a moving window to detect regime changes.
  • Monthly Returns Heatmap: Reveals seasonal patterns and calendar effects in strategy performance.
  • Factor Exposure: When position data is provided via the pos parameter, shows concentration risks across sectors or asset classes.

Integration with the Awesome Systematic Trading Repository

The paperswithbacktest/awesome-systematic-trading repository references pyfolio in specific locations:

  • README.md (line 197): Lists pyfolio as a recommended resource for portfolio risk analytics.
  • README_zh.md (line 187): Contains the Chinese translation of the same resource entry.
  • static/strategies/: Directory containing strategy implementations that generate compatible return series.
  • opencode.json: Repository metadata file supporting the project's tooling infrastructure.

To use pyfolio with this repository, select any strategy from static/strategies/, capture its return output, and process it through the tear sheet function demonstrated above.

Summary

  • pyfolio generates institutional-grade risk reports from simple pandas Series objects.
  • The create_returns_tear_sheet function requires only a returns time-series, with optional benchmark and position data.
  • The paperswithbacktest/awesome-systematic-trading repository catalogs pyfolio as a core analytics tool and provides strategy templates in static/strategies/ that feed directly into it.
  • Tear sheets visualize cumulative returns, drawdowns, rolling Sharpe ratios, and factor exposures in a single comprehensive view.

Frequently Asked Questions

What data format does pyfolio require for analysis?

pyfolio requires a pandas.Series of percentage returns indexed by datetime. The series should contain daily or weekly portfolio returns, not cumulative values. If you want exposure analysis, you must also provide a pandas.DataFrame of positions indexed by date with ticker weights or dollar amounts.

Can I use pyfolio without providing position data?

Yes. The pos parameter in create_returns_tear_sheet is optional. Without position data, pyfolio will generate all performance and risk metrics except for factor exposure and sector concentration plots. The core functionality—returns analysis, drawdown calculation, and Sharpe ratio computation—requires only the returns series.

How do I integrate pyfolio with existing backtests in the repository?

Execute any script in static/strategies/ to generate a CSV of daily returns, then load that file into a pandas Series. Pass this series to pyfolio.create_returns_tear_sheet. Because pyfolio operates independently of the backtest engine, no modifications to the original strategy code are necessary—only standardization of the output format to a datetime-indexed return series.

What is the difference between a tear sheet and a standard backtest report?

A tear sheet is a condensed, single-page visualization designed for rapid risk assessment, whereas standard backtest reports often contain tabular trade logs and granular statistics. pyfolio tear sheets focus on visual analytics—drawdown charts, rolling metrics, and heatmaps—making them ideal for presentations and high-level strategy comparison, while traditional reports prioritize transactional detail.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →