ArbitrageLab Documentation

repository·master·Indexed 20 days ago

https://github.com/hudson-and-thames/arbitragelab

An open-source Python library (v1.0.0) providing end-to-end strategies and tools for mean-reverting and pairs trading based on academic research. It includes specialized modules for statistical arbitrage, codependence, cointegration, copulas, distance metrics, and machine learning. Key features include implementations of Spearman's rho, GPR and GNPR distances, mutual information, variation of information, and various angular distance metrics for portfolio construction.

Tokens
77.8K
Snippets
147
Records
310
Agent score
71%

What's inside ArbitrageLab

  1. Overview of Optimal Mean-Reverting Strategies

    master

    The optimal_mean_reversion module provides solutions for the optimal stopping problem applied to assets or portfolios with mean-reverting dynamics. It addresses the timing of trades: specifically, when to enter a market position and when to liquidate a position to maximize returns.

    The module focuses on portfolios constructed by holding $\alpha$ shares of a risky asset $S^{(1)}$ and shorting $\beta$ shares of another risky asset $S^{(2)}$, resulting in a portfolio value $X_t^{\alpha,\beta} = \alpha S^{(1)} - \beta S^{(2)}$.

    Strategies are implemented based on three mathematical mean-reverting models:

  2. Overview of ArbitrageLab

    master

    ArbitrageLab is a Python library designed for statistical arbitrage, specifically focusing on pairs trading strategies. It provides both end-to-end trading strategies and a suite of tools for strategy creation, covering the full range of strategies defined by Krauss' taxonomy for pairs trading.

    The library is built upon implementations from peer-reviewed quantitative finance journals, including publications from The Journal of Portfolio Management, The Journal of Financial Data Science, and Cambridge University Press.

  3. Construct sparse mean-reverting portfolios

    master

    The arbitragelab module provides tools to construct sparse mean-reverting portfolios, which aim to trade as few assets as possible ($k \ll n$) to mitigate transaction costs and improve P&L interpretability.

    Available construction methods include:

    • Covariance selection and penalized regression: To narrow down the investing universe.
    • Greedy search: To construct sparse portfolios.
    • Semidefinite programming (SDP): To construct sparse portfolios above a specific volatility threshold.

    Additionally, the module supports:

    • Box-Tiao canonical decomposition: For constructing dense mean-reverting portfolios.
    • Ornstein-Uhlenbeck (OU) model fitting: To directly compare the mean-reversion strength of different portfolios.
  4. What is the Copula approach in ArbitrageLab?

    master

    The Copula approach is an advanced analysis tool for pairs trading that provides a more nuanced understanding of traded pairs compared to traditional distance or cointegration methods.

    Unlike Euclidean distance or cointegration approaches which focus on price gaps or long-run means, the Copula model incorporates the marginal distributions of the time series. This allows for capturing complex dependency structures, such as tail dependency, which is critical for identifying rare or extreme market swings.

    By modeling how two random variables are correlated through their distributions, the Copula approach aims to create more realistic and robust trading strategies.

  5. What is the Distance Approach for pairs trading?

    master

    The Distance Approach is a pairs trading strategy based on the work of Gatev et al. (2006). It identifies pairs of assets by calculating the Euclidean squared distance (SSD) between their normalized price time series.

    Key Characteristics:

    • No Cointegration Tests: Unlike mean-reversion approaches, it relies purely on distance metrics.
    • Normalization: Prices are normalized using the formula: $P_{normalized} = \frac{P - min(P)}{max(P) - min(P)}$.
    • Signal Generation: A trade is triggered when the difference between the normalized prices of a pair diverges by more than 2 standard deviations (calculated during the training period).
    • Position Management:
      • Long/Short: If the portfolio value (difference in normalized prices) exceeds +2 standard deviations, a sell signal is generated (short the first element, long the second). If it falls below -2 standard deviations, a buy signal is generated (long the first element, short the second).
      • Exit: Positions are closed when the portfolio value crosses zero (the normalized prices cross) or when the trading period ends.
  6. Overview of Spread Modeling approaches

    master

    The Spread Modeling module implements research by Dr. Christian Dunis and colleagues focused on modeling and forecasting commodity spreads (e.g., Crack Spread, Soy Crush Spread, Corn Crush Spread).

    Core Concepts

    • Spread Trading: Trading the difference between two correlated assets. This approach aims to reduce exposure to information shocks and speculative bubbles, as movements in the two legs often offset each other.
    • Modeling Goal: The module provides tools to model the spread accurately and, more importantly, to discriminate between large and small moves to optimize transaction costs.

    Available Model Types

    • Neural Networks: MLP (Multi-Layer Perceptron), RNN (Recurrent Neural Networks), and HONN (Higher Order Neural Networks).
    • Benchmark Models: Fair Value Non-Linear Cointegration Models, ARMA, and MACD.
    • Filters: Used to minimize transaction costs by selecting trades based on volatility or correlation. Includes Threshold Filters, Asymmetric Threshold Filters, Correlation Filters, and Time-Varying RiskMetrics volatility models.
  7. Overview of the C-vine Copula Strategy

    master

    The C-vine Copula strategy is a statistical arbitrage approach used to model multivariate dependencies among a cohort of stocks. It decomposes joint probability density into bivariate copula densities and marginal densities using a tree structure.

    Key Concepts

    • C-vine vs. R-vine: While R-vines are the most generic structure, they are computationally expensive and prone to overfitting. C-vines (Canonical vines) have a star-like structure that is more interpretable and efficient for modeling dependencies where one specific random variable (the target stock) is central to the group.
    • Trading Logic: The strategy uses a "1-vs-the-rest" framework. It calculates conditional (cumulative) probabilities to determine if a target stock is underpriced or overpriced relative to the rest of the cohort, generating trading signals based on a mean-reversion bet.

    Typical Workflow

    1. Get data: Collect historical price/return data for the stock cohort.
    2. Figure out the C-vine structure: Determine the tree structure for the dependencies.
    3. Calculate probability density: Compute the joint density using the copula model.
    4. Calculate the conditional probability: Derive the conditional probability to gauge mispricing.
    5. Generate signals and trade: Execute trades based on the calculated mispricing signals.
  8. What is a Vine Copula and how does it work?

    master

    A Copula is a statistical tool used to study the relationship among multiple random variables by focusing on the joint cumulative density of marginal quantiles, bypassing the idiosyncratic features of individual marginal distributions.

    While standard bivariate copulas work well for two dimensions, they become rigid and lose detail in higher dimensions. Vine Copulas solve this by decomposing a high-dimensional probability density function (PDF) into a hierarchy of bivariate copulas and marginal densities.

    The Decomposition Principle

    The core idea is to decompose the joint PDF into conditional probabilities, which are then further decomposed into bivariate copulas. For example, a 3D joint density $f(x_1, x_2, x_3)$ can be decomposed as:

    $f(x_1, x_2, x_3) = f_1(x_1) f_2(x_2) f_3(x_3) \times c_{2,3}(F_2(x_2), F_3(x_3)) c_{1,3}(F_1(x_1), F_3(x_3)) \times c_{1,2|3}(F_{1|3}(x_1 | x_3), F_{2|3}(x_2 | x_3))$

    Visualizing the Structure

    Vine copulas are visualized as tree structures where:

    • Nodes represent either joint densities or marginal densities.
    • Bivariate copulas connect the nodes.
    • Leaves (at the top of the tree) represent the marginal densities of each random variable.
  9. Concept: Multivariate Cointegration Strategy

    master

    The Multivariate Cointegration strategy bets on the mean reversion of a spread formed by $N$ cointegrated assets.

    Core Logic

    1. Identify Cointegration: Use the Johansen test on log-price series to derive a cointegration vector $\mathbf{b}$.
    2. Calculate the Spread: The spread is a linear combination of log-prices: $Y_t = \sum_{i=1}^N b^i \ln{P_t^i}$.
    3. Trading Rule: Trade the assets based on the deviation of the recent sum of log-returns from zero. In practice, a finite lag $P$ is used to approximate the infinite sum of returns: $\sum_{p=1}^P Z_{t-p}$.
    4. Dollar Neutrality: To ensure the portfolio is dollar-neutral, assets are partitioned into two sets based on the sign of their cointegration coefficient $b^i$:
      • Set $L$: Assets where $b^i \geq 0$
      • Set $S$: Assets where $b^i < 0$

    The resulting portfolio maintains $C$ dollars in long positions and $C$ dollars in short positions, where $C$ is a positive scale factor.

  10. Use mixed copulas for flexible dependency modeling

    master

    The copula_approach module provides mixed copula classes to better capture upper and lower tail dependencies than 'pure' Archimedean or elliptical copulas.

    Supported mixed copula classes:

    • CFGMixCop: A Clayton-Frank-Gumbel mix.
    • CTGMixCop: A Clayton-Student-Gumbel mix.

    For a CFG mixed copula, you specify the dependency parameters ($\theta$) for each component and their corresponding weights (which must sum to 1). These weights are interpreted in a Markov sense, describing the probability of an observation originating from a specific component.

  11. Configure investor preferences for the OU Model

    master

    The model supports two primary preference structures for the arbitrageur:

    1. Constant Relative Risk Aversion (CRRA): Used for maximizing the discounted utility of terminal wealth at a finite horizon $T$.

      • Value function: $V_{t}=\sup E_{t}\left[e^{-\beta(T-t)} \frac{W_{T}^{1-\gamma}}{1-\gamma}\right]$
      • Best for modeling proprietary trading desks or managers with a fixed investment horizon.
    2. Epstein-Zin Recursive Utility: Allows the elasticity of intertemporal substitution and the coefficient of relative risk aversion to vary independently.

      • Used to model the role of management fees (intermediate consumption/cash flows).
      • In the special case of unit elasticity of intertemporal substitution ($\psi = 1$), the agent's consumption-to-wealth ratio is constant, effectively modeling a flat management fee collected as a continuous stream.
  12. How the EM fitting algorithm works for mixed copulas

    master

    To avoid the instability and convergence issues of generic maximization optimizers when fitting multiple parameters and weights, arbitragelab uses a two-step Expectation-Maximization (EM) algorithm adapted from [Cai, Wang 2014].

    The Two-Step Process:

    1. E-step: Iteratively calculates updated weights $w_k^{new}$ using the current parameters $\theta$ and weights $w$.
    2. M-step: Uses the updated weights to find new parameters $\theta$ by maximizing the objective function $Q(\boldsymbol{\theta}, \mathbf{w})$ (often using truncated Newton or Newton-Raphson).

    Key Characteristics:

    • Oracle and Sparse: The algorithm has good asymptotic properties and uses a SCAD (smoothly clipped absolute deviation) penalty term to drive insignificant component weights toward zero.
    • Performance Note: The CTGMixCop may take longer to converge due to the computational bottleneck of the Student-t copula component.
    • Limitations: If copula components are very similar (e.g., Gaussian and Frank), the algorithm may struggle to distinguish weights accurately. The SCAD parameters $\gamma$ and $a$ are tuned via cross-validation in the package defaults.