# Stock Pair Cointegration Analyzer (`autoworks-jp/stock-pair-cointegration-analyzer`) Actor

Test stock/ETF pairs for cointegration: hedge ratio, half-life, spread z-score and a walk-forward check. Statistical data only, not investment advice.

- **URL**: https://apify.com/autoworks-jp/stock-pair-cointegration-analyzer.md
- **Developed by:** [AutoWorks JP](https://apify.com/autoworks-jp) (community)
- **Categories:** Business, Developer tools, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 pair analyzeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Stock Pair Cointegration Analyzer

Test whether pairs of stocks or ETFs move together in a statistically stable way (cointegration), and see how far their spread is from its usual level today. Built for quants, pair-trading researchers and students who want clean statistics without writing their own pipeline.

**This Actor provides statistical data only. It is not investment advice and does not recommend buying or selling any security.**

### What you get for each pair

| Field | Meaning |
|---|---|
| `cointegrationPValue` | Engle-Granger test p-value on log prices over the formation window |
| `qValueBH` | p-value adjusted for testing many pairs at once (Benjamini-Hochberg) |
| `cointegrated` | `true` if q < significance, hedge ratio > 0 and half-life is 2-30 days |
| `hedgeRatio` | OLS beta of log(A) on log(B) |
| `halfLifeDays` | Mean-reversion half-life of the spread (Ornstein-Uhlenbeck fit) |
| `spreadZScore` | Today's spread vs. the previous `zWindow` days (today excluded, no look-ahead) |
| `spreadState` | `above mean` / `below mean` / `within band` |
| `returnCorrelation` | Correlation of daily log returns |
| `walkForward` | Out-of-sample style historical check: parameters re-estimated monthly using past data only, trades simulated with costs, results split into first/second half |

### Why the walk-forward check matters

Many pairs look cointegrated in hindsight. In our own 10-year test on 221 same-sector US large-cap pairs, pairs chosen on the first half of the data showed strong results in that half but were not statistically significant in the second half. Use `walkForward.secondHalf` and its `tStat` to judge whether a relationship has held up, not the first-half numbers.

### Input

- `tickers`: 2-40 symbols; every combination is analyzed (max 300 pairs per run)
- `pairs`: specific pairs such as `XOM/CVX`
- `dataSource`: `yahoo` or `csvUrl` (your own adjusted-close CSV: first column date, other columns tickers)
- `years`, `formationDays`, `zWindow`, `significance`, `zThreshold`, `includeBacktest`, `costBps`

### Pricing

Pay per event: you are charged once per analyzed pair (`pair-result`). A summary is stored in the key-value store as `SUMMARY`.

### Notes

- Yahoo Finance data is retrieved via the open-source `yfinance` library and is subject to Yahoo's terms. For commercial use, supply your own licensed data via `csvUrl`.
- Results depend on the window chosen and on survivorship of the tickers you pick.

# Actor input Schema

## `tickers` (type: `array`):

2-40 symbols. Every combination is analyzed (max 300 pairs).

## `pairs` (type: `array`):

Optional, e.g. 'XOM/CVX'.

## `dataSource` (type: `string`):

Where daily adjusted close prices come from.

## `csvUrl` (type: `string`):

First column = date, other columns = adjusted close per ticker.

## `years` (type: `integer`):

How many years of daily history to load.

## `formationDays` (type: `integer`):

Trading days used to estimate hedge ratio and run the cointegration test.

## `zWindow` (type: `integer`):

Rolling window for the spread z-score.

## `significance` (type: `string`):

False discovery rate for Benjamini-Hochberg adjusted Engle-Granger p-values.

## `zThreshold` (type: `integer`):

Absolute z-score used to label the spread state and for the walk-forward check.

## `includeBacktest` (type: `boolean`):

Run a simple out-of-sample walk-forward check of the spread rule (statistics only).

## `costBps` (type: `integer`):

Transaction cost per leg in basis points applied in the walk-forward check.

## Actor input object example

```json
{
  "tickers": [
    "KO",
    "PEP",
    "PG",
    "CL"
  ],
  "dataSource": "yahoo",
  "years": 5,
  "formationDays": 252,
  "zWindow": 60,
  "significance": "0.05",
  "zThreshold": 2,
  "includeBacktest": true,
  "costBps": 10
}
```

# Actor output Schema

## `results` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "tickers": [
        "KO",
        "PEP",
        "PG",
        "CL"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("autoworks-jp/stock-pair-cointegration-analyzer").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "tickers": [
        "KO",
        "PEP",
        "PG",
        "CL",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("autoworks-jp/stock-pair-cointegration-analyzer").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "tickers": [
    "KO",
    "PEP",
    "PG",
    "CL"
  ]
}' |
apify call autoworks-jp/stock-pair-cointegration-analyzer --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,autoworks-jp/stock-pair-cointegration-analyzer"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/CB045I1i3Q7Mdhrr6/builds/wJvpTGxy8UwaseRg4/openapi.json
