Risk Management and Portfolio Analytics with pyfolio: A Complete Guide for Systematic Trading

The awesome-systematic-trading repository recommends pyfolio for portfolio-level risk analysis, enabling analysts to transform strategy return series from static/strategies/ into comprehensive tear sheets and risk metrics.

The awesome-systematic-trading repository is a curated collection of factor-based and rule-based trading strategies implemented in Python. While the repo does not embed pyfolio directly within its source code, it explicitly lists the library in README.md and README_zh.md as the recommended tool for risk management and portfolio analytics with pyfolio, bridging the gap between raw strategy outputs and institutional-grade risk reporting.

Repository Architecture and Data Flow

The repository organizes its strategy implementations under static/strategies/, where each Python script generates a time series of daily returns. The recommended workflow follows a linear pipeline: individual strategy scripts produce return vectors, users consolidate these into a pandas.DataFrame, and pyfolio consumes this data to compute turnover, drawdowns, Sharpe ratios, and full tear sheets.

According to the repository structure, the modular design allows arbitrary combination of strategies, enabling comparative risk dashboards across dozens of academic-style factors.

Installation and Setup

Before integrating with the repository's outputs, install pyfolio via pip:

pip install pyfolio

Loading Strategy Returns from awesome-systematic-trading

Each strategy file in static/strategies/ typically exports results to CSV. Collect these into a consolidated DataFrame where each column represents a distinct strategy:

import pandas as pd
import glob
import os

# Locate all CSV files generated by the strategy scripts

csv_files = glob.glob(os.path.join("outputs", "*.csv"))

# Build a DataFrame where each column is a strategy's returns

returns_df = pd.DataFrame()
for file in csv_files:
    name = os.path.splitext(os.path.basename(file))[0]   # e.g., "momentum_factor_effect_in_stocks"

    returns = pd.read_csv(file, parse_dates=["date"], index_col="date")["return"]
    returns_df[name] = returns

Generating pyfolio Tear Sheets

Single Strategy Analysis

To evaluate one specific strategy from the repository, use create_simple_tear_sheet():

import pyfolio as pf

# Pick one strategy to illustrate

strategy = returns_df["momentum_factor_effect_in_stocks"]

# Generate the classic performance tear-sheet

pf.create_simple_tear_sheet(strategy)

Comparative Portfolio Analytics

For side-by-side comparison of multiple strategies from static/strategies/, align dates and generate a comparative report:


# Combine several strategies into a single DataFrame (already done above)

# Optionally drop NaNs to align dates

aligned_returns = returns_df.dropna(how="any")

# Create a comparative tear-sheet

pf.create_returns_tear_sheet(aligned_returns, benchmark_rets=None)

Extracting Risk Metrics Programmatically

Beyond visual reports, extract specific quantitative measures using pyfolio.timeseries functions:

from pyfolio import timeseries

# Example: annualized Sharpe ratio for each strategy

sharpe = {}
for col in aligned_returns:
    sharpe[col] = timeseries.sharpe_ratio(aligned_returns[col])

print("Annualized Sharpe ratios:")
for strat, val in sharpe.items():
    print(f"{strat}: {val:.2f}")

This approach leverages the modular architecture of awesome-systematic-trading, allowing you to programmatically compare risk-adjusted returns across the entire strategy library.

Summary

  • The awesome-systematic-trading repository lists pyfolio in README.md and README_zh.md as the recommended tool for portfolio analytics.
  • Strategy scripts in static/strategies/*.py generate daily return series that serve as input data.
  • The workflow follows: strategy scripts → daily returns → pandas.DataFrame → pyfolio analysis.
  • Use pf.create_simple_tear_sheet() for single strategy reports and pf.create_returns_tear_sheet() for comparisons.
  • Extract specific metrics like Sharpe ratios via timeseries.sharpe_ratio() for quantitative strategy ranking.

Frequently Asked Questions

How does pyfolio integrate with the awesome-systematic-trading repository?

The repository does not embed pyfolio internally, but explicitly recommends it in the main README.md for portfolio-level risk analysis. Users run strategy scripts from static/strategies/ to generate return CSVs, then load these into pyfolio to create tear sheets and risk metrics.

Can I analyze multiple strategies simultaneously in one report?

Yes. Consolidate return series from multiple strategy files into a single pandas.DataFrame with aligned dates, then call pf.create_returns_tear_sheet(aligned_returns). This generates comparative visualizations showing relative drawdowns, volatility, and return profiles across the strategy library.

What specific risk metrics can I extract programmatically from pyfolio?

The pyfolio.timeseries module provides functions like sharpe_ratio(), max_drawdown(), and annual_return() that accept a pd.Series of returns. These allow programmatic extraction of key risk indicators for automated strategy screening and ranking.

Where should I store strategy returns before pyfolio analysis?

The repository suggests exporting daily returns from each strategy script to an outputs/ directory as CSV files. Use glob to pattern-match these files into a consolidated DataFrame, ensuring each strategy name becomes a column header for clear identification in pyfolio reports.

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 →