Pairs Trading API Reference¶
financelib.quant.pairs.cointegration_test(series_a: pd.Series, series_b: pd.Series) -> Dict[str, float]
¶
Test for cointegration between two price series using Engle-Granger method.
Regresses series_a on series_b and tests residuals for stationarity using the ADF test approximation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
series_a
|
Series
|
First price series. |
required |
series_b
|
Series
|
Second price series. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, float]
|
Dictionary with 'beta' (hedge ratio), 'adf_statistic', |
Dict[str, float]
|
'is_cointegrated' (True if ADF < -2.86 at 5% level). |
Source code in financelib/quant/pairs.py
financelib.quant.pairs.find_cointegrated_pairs(prices: pd.DataFrame, significance: float = -2.86) -> List[Dict[str, any]]
¶
Scan a universe of assets to find cointegrated pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prices
|
DataFrame
|
DataFrame of price series (columns = assets). |
required |
significance
|
float
|
ADF critical value threshold. |
-2.86
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, any]]
|
List of dicts with 'pair', 'adf_statistic', 'beta' for |
List[Dict[str, any]]
|
cointegrated pairs, sorted by ADF statistic. |
Source code in financelib/quant/pairs.py
financelib.quant.pairs.spread_z_score(series_a: pd.Series, series_b: pd.Series, hedge_ratio: float, window: int = 20) -> pd.Series
¶
Calculate the z-score of the spread between two cointegrated series.
spread = series_a - hedge_ratio * series_b z = (spread - mean(spread)) / std(spread)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
series_a
|
Series
|
First price series. |
required |
series_b
|
Series
|
Second price series. |
required |
hedge_ratio
|
float
|
Hedge ratio (beta from cointegration test). |
required |
window
|
int
|
Rolling window for mean and std. |
20
|
Returns:
| Type | Description |
|---|---|
Series
|
Z-score series of the spread. |
Source code in financelib/quant/pairs.py
financelib.quant.pairs.pairs_backtest(series_a: pd.Series, series_b: pd.Series, hedge_ratio: float, entry_z: float = 2.0, exit_z: float = 0.5, window: int = 20, initial_capital: float = 100000) -> Dict[str, any]
¶
Backtest a pairs trading strategy.
Enter long spread when z < -entry_z, short when z > entry_z. Exit when |z| < exit_z.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
series_a
|
Series
|
First price series. |
required |
series_b
|
Series
|
Second price series. |
required |
hedge_ratio
|
float
|
Hedge ratio. |
required |
entry_z
|
float
|
Z-score threshold for entry. |
2.0
|
exit_z
|
float
|
Z-score threshold for exit. |
0.5
|
window
|
int
|
Rolling window for z-score. |
20
|
initial_capital
|
float
|
Starting capital. |
100000
|
Returns:
| Type | Description |
|---|---|
Dict[str, any]
|
Dictionary with backtest results. |