# Regime Analytics for your research workflow

Status: customer API/MCP pilot. Availability depends on the deployed version and your account grant. A published specification is not proof of activated access or client certification; see the [compatibility matrix](#compatibility-matrix) for what has actually been tested.

Bring a shortlist, a book of weights or your own written rules from your research process and review them against Regime Analytics' latest observations. Responses connect security trend stance with market, sector and industry trends plus market Exposure and Mood, each with its own date. Use that context to investigate which candidates fit your strategy, which need more evidence and which deserve a later review.

The selected public market sample remains at https://regimeanalytics.com/market-pulse.html. Full terminal datasets require a verified account session plus current Research membership or explicitly approved developer/beta access. Signup alone grants neither full data nor API access, and a paid Research membership does not automatically grant the customer API.

The customer API provides decision context rather than a general market-data feed. It does not export the universe, historical datasets, model coefficients, constituent panels or proprietary recipes. It does not choose portfolio weights, size positions or execute trades. Any strategy needs its own explicit sizing and eligibility rules before an allocation workflow can apply them faithfully.

Companion references: [field guide and error catalog](https://terminal.regimeanalytics.com/developer-field-guide.md), [changelog and deprecation policy](https://terminal.regimeanalytics.com/developer-changelog.md), [OpenAPI 3.1](https://terminal.regimeanalytics.com/api/v2/openapi.json).

## 1. Get a customer key

Sign in at https://terminal.regimeanalytics.com/account and open **API & MCP**. An invited account shows its grant, usage and key controls. Choose a descriptive key name, create the key and copy it into a password manager or secret environment while it is visible.

The complimentary pilot costs $0 per month and has no checkout step. It includes five active keys, 300 authenticated HTTP requests and 500 symbol reviews per account per UTC day, with up to 25 symbols per request. These are provisional product-usage allowances, not trading or investment restrictions. **All keys and MCP connections on an account share one bucket**, so a notebook, an AI client and a polling job draw from the same daily total.

Store the key as `REGIME_ANALYSIS_API_KEY` in your local secret environment. Send it only in the `Authorization` header to `https://terminal.regimeanalytics.com`. Do not put a key in URLs, shared prompts, source code, receipts or screenshots; key-list responses contain only prefixes, and the server stores a one-way digest.

### Customer keys and other credentials

| Credential | Purpose | Used by the Python client |
| --- | --- | --- |
| Customer analysis key (`REGIME_ANALYSIS_API_KEY`) | The workflows in this guide, over REST and MCP | Yes |
| Owner full-read key | Separately approved owner access to existing terminal datasets | No |
| Operator `/api/v1` key (`REGIME_API_KEY`) | Separate operator API with its own authority | No |

Owner full read requires human approval of the account and an explicit per-key selection in **API & MCP → Key access**. Every key defaults to **Watchlist analysis**, including keys created on an owner-approved account. An owner full-read key can read existing RA publications such as `/api/grid` (including `?date=YYYY-MM-DD`), `/api/meta` and the other terminal datasets documented in `docs/contracts/terminal-openapi.json`, with their existing date, provenance and query rules. Account administration, billing, credentials, writes and trade execution are excluded, owner dataset requests share the same daily request allowance, and future endpoints acquire no automatic owner-key access. The Python client never reads `REGIME_API_KEY` or an owner key, even when one is set.

## 2. Install the Python client

The client is in this repository at `sdk/python`. It uses only the Python standard library (3.9+) and is not published to a package index.

```sh
python -m pip install ./sdk/python
export REGIME_ANALYSIS_API_KEY=...   # from your secret store
python sdk/python/examples/01_watchlist_receipt.py receipts/watchlist.json AAPL MSFT SPY
```

The client sends requests only to the canonical origin, refuses redirects, caps responses at 1 MiB and uses a 30-second socket timeout and response-body deadline by default. DNS and slowly delivered HTTP headers are not covered by a hard wall-clock deadline. It never retries automatically, because every attempt consumes allowance. Every method returns an `ApiResult` that reads like a dict and also carries `.raw` (exact response bytes), `.request_id` and `.captured_at`; failures raise `ApiError` with `status`, `code`, `message`, `request_id` and `retry_after`.

## 3. Workflows

### Review a watchlist, with optional evidence

```python
from regime_analytics import Client
review = Client().review_watchlist(["AAPL", "MSFT", "SPY"], evidence=True)
```

```sh
curl --fail-with-body https://terminal.regimeanalytics.com/api/v2/watchlist-review \
  -H "Authorization: Bearer $REGIME_ANALYSIS_API_KEY" \
  -H 'Content-Type: application/json' \
  --data '{"symbols":["AAPL","MSFT","SPY"],"evidence":true}'
```

The response (`ra.watchlist-review.v1`) has `publication`, `freshness`, `market`, `results`, `guidance` and `request_id`. Each symbol keeps its own observation date, and missing coverage stays explicit. The order of unique input symbols is preserved, lowercase symbols are normalized and duplicates are counted once. Omitting `evidence` (or sending `false`) returns the original shape unchanged. With `evidence: true` an additive `evidence` block lists compact reason codes per symbol with the source of each fact and its date, plus the publication's recorded times; see the field guide for every code.

### Summarize a signed-weight portfolio

```python
from regime_analytics import Client, Position
book = Client().review_portfolio([Position("AAPL", 0.35), Position("XLE", 0.15), Position("TSLA", -0.20)])
```

Send 1–25 unique symbols with signed fractions of your book: `1.0` is 100%, `-0.2` is a 20% short. Shorts, leverage and partial books are accepted as supplied, and duplicate symbols are rejected rather than merged. The `ra.portfolio-review.v1` response returns each position's context plus long, short, net and gross sums by coverage, asset type, security trend, sector, sector trend, industry and industry trend. Weights are never renormalized, sized or risk-modelled, and positions without a classification are reported as a separate `unknown` bucket, which is not neutral. For books larger than 25 symbols, keep disjoint partial batches on the original whole-book NAV denominator. Combine only matching publication IDs and source cursors, adding corresponding signed bucket totals and unknown contributions; see the [partial-book example](https://terminal.regimeanalytics.com/developer-field-guide.md#books-larger-than-25-symbols).

### Evaluate your own rules

```python
from regime_analytics import Client, Rule
rules = [Rule("trend_buy", "security.trend_stance", "eq", "Buy"),
         Rule("sector_not_down", "sector.stance", "in", ["up", "neutral"]),
         Rule("fresh", "freshness.sessions_behind", "lte", 1)]
result = Client().evaluate_rules(["AAPL", "XLE"], rules)
```

Send 1–10 rules `{id, field, operator, value}` for 1–25 symbols. Fields are limited to an allowlist of existing context fields (listed in the field guide and `regime_analytics.RULE_FIELDS`), and only the rules you send are applied. Each symbol and rule gets `pass`, `fail` or `unknown` with the observed value and its date. A missing observation is `unknown`, never a match or a failure. A pass is a research-rule match, not eligibility, a weight or an order.

### Review changes since a saved response

```python
from regime_analytics import Client, load_receipt
saved = load_receipt("receipts/watchlist.json")
diff = Client().review_changes(saved.response, saved.captured_at)
```

Send a complete earlier `ra.watchlist-review.v1` response and when you received it (`previous_received_at`, ISO 8601 with an offset). The server reviews the same symbols again and returns only changed explicit fields with previous and current values, their dates and both publication ids. The baseline is labelled `source: client_supplied` and `verified: false`: Regime Analytics does not save the supplied baseline as account research and does not certify what was known at the earlier time. Changes are observations, not trading actions.

### Publication status and usage

`client.publication(after="<earlier cursor>")` (`GET /api/v2/publication?after=...`) returns the current core publication id, data date, freshness, `status` (`published`, `transition` or `unavailable`) and an opaque `cursor` (see section 5). With `after`, `changed` says whether the cursor differs; without it, `changed` is null. `client.usage()` (`GET /api/v2/usage`) returns the account's UTC-day allowance, consumption, remaining totals and reset time, and already counts itself. Each call consumes one request.

## 4. Local receipts

```python
from regime_analytics import save_receipt, load_receipt
path = save_receipt(review, "receipts/2026-10-30-watchlist.json")
receipt = load_receipt(path)
```

A receipt stores the requested workflow (method, path and request body), the local capture time, the response schema, publication and freshness, and the complete qualified response. Its SHA-256 covers the exact response bytes (`response_body_utf8_bytes`); receipts of locally generated JSON such as poll events instead hash `json_sorted_keys_compact_utf8` (sorted keys, compact separators, UTF-8, which is not RFC 8785). Receipt permissions are exercised on macOS using Unix file modes; Windows receipt permissions are not verified. Files are created exclusively with mode 0600, missing parent directories are created 0700, and existing files and any path whose supplied components include a symlink are refused for both writing and reading. On macOS `/tmp` and `/var` are symlinks, so keep receipts under a real directory such as one in your home folder. Keys are never written. If writing or flushing fails, the client raises `ReceiptError` and leaves the attempted file for inspection; it does not delete or overwrite that path. Use a new filename after resolving the disk error.

`load_receipt` recomputes the digest over the stored response and checks the schema, publication and freshness summary against that response. That detects edits to the stored response and its summary only: the workflow, `captured_at` and `request_id` fields are not hashed and remain unverified local metadata. It is not a signature, it is not issued or certified by the server, and it does not prove what was published or when, since anyone can recompute a hash. Saving or loading a receipt makes no network call. The offline notebook `sdk/python/examples/saved_receipts.ipynb` tabulates saved receipts.

## 5. Polling notifications

Notifications are **bounded client-side polling**, not push and not webhooks. Nothing runs in the background, nothing is installed or scheduled, and no message is sent anywhere.

```sh
python -m regime_analytics poll --after <cursor from the last stopped event> \
  --symbols AAPL MSFT SPY --max-polls 1 --receipt-dir receipts
```

Change detection uses the opaque `cursor`, not the core `publication.id`. The cursor covers the exact source content being served (equity grid, ETFs, composites and publication metadata, but not freshness clocks), so it also moves for an ETF-only update or a correction published under the same id. Cursors are compared for equality only and carry no order or date. The cursor contract is deployed as of October 31, 2026; against an older server without it, the poller stops with `cursor_unsupported` instead of silently doing nothing.

Each poll checks publication status once. When the status is `published` and its cursor differs from `--after`, the supplied watchlist is reviewed once, always with `evidence: true`. A `transition`, `unavailable` or null-cursor status triggers no review. The poller then acknowledges only the cursor the review itself returned in `evidence.source.cursor`, never the status cursor. If the two differ, a `publication_changed_during_review` event reports both cursors and publication ids. If the review returned the cursor you already acknowledged (for example a replica serving an older snapshot), you get `review_unchanged` instead of a duplicate `watchlist_reviewed`, and nothing advances. A review without a valid cursor stops with `review_cursor_missing` and keeps the previous cursor. Without a watchlist, the poller acknowledges the observed status cursor.

The default is one poll. `--max-polls N` and `--interval SECONDS` (default 300, minimum 1) set an explicit finite budget, and the command sleeps only between its own polls. Events print as JSON lines (`publication_checked`, `publication_changed_during_review`, `watchlist_reviewed`, `review_unchanged`, `quota_exhausted`, `error`, `stopped`), and the final `stopped` event's `after` is the cursor to pass next time. Without `--after`, the first published cursor counts as new.

An exhausted allowance stops immediately with `retry_after_seconds` and `retry_not_before`; the command never sleeps until the reset. Exit codes are 0 (budget finished), 75 (allowance exhausted) and 1 (error). Each poll costs one request and each review one symbol per name from the shared account bucket. If you choose to run this on a schedule, use your own existing scheduler and size the budget against that bucket. The same loop is available as `regime_analytics.poll_publication(...)`.

## 6. Interpret the result

Timestamps answer different questions and are never interchangeable. `as_of` fields are observation (data) dates; `publication.as_of` is the publication's data date, not a streaming quote time. With evidence, `source.source_generated_at` is the source document's own field verbatim (the publisher writes the data date at 00:00Z, so it is not a clock time), and `source.published_at` and `source.methodology_version` are null when not recorded. `evaluated_at` is the server's clock at evaluation, while `captured_at` is your client's receive time and `previous_received_at` is a time you supply.

Stale or unknown observations remain qualified and do not become favorable readings. Missing group or fund mappings remain null, and current classification membership is not historical point-in-time membership. ETFs carry their own date and price-derived classification limits. These observations are not probabilities or forecasts and do not establish strategy performance, causality or outperformance of the S&P 500. The [field guide](https://terminal.regimeanalytics.com/developer-field-guide.md) lists every field, unit and code.

## 7. Connect an AI client

The MCP endpoint is `https://terminal.regimeanalytics.com/mcp`. Every tool call is an analytical request: it needs an entitled account plus a customer key or OAuth token, and it uses the same analysis, output schemas and shared usage bucket as REST. There is no generic REST executor, SQL tool, URL fetcher, filesystem resource or bulk-download tool, and no analysis is available anonymously. The deployed service exposes six tools: `review_watchlist`, `review_portfolio`, `evaluate_research_rules`, `review_changes`, `get_publication_status` and `get_api_usage`.

MCP discovery (`initialize`, `tools/list` and `ping`) is public and does not consume allowance. The tool catalog it returns is the same public contract as the OpenAPI document and contains no market data. Server-side OAuth discovery is configured for `https://terminal.regimeanalytics.com/mcp`, with Clerk as the authorization server and `regime:read` as the research scope. The server advertises top-level `securitySchemes` and answers an unauthenticated tool call with an authorization challenge. Hosted-client consent, refresh and revocation remain unverified. The October 31 customer-key acceptance run connected with the official MCP client and listed all six tools without a key; an anonymous analytical call returned HTTP 401.

### Claude Code: bearer-key pilot

Use an environment variable reference in your private MCP configuration, so the key stays out of the command line and configuration file:

```json
{
  "mcpServers": {
    "regime_analytics": {
      "type": "http",
      "url": "https://terminal.regimeanalytics.com/mcp",
      "headers": {"Authorization": "Bearer ${REGIME_ANALYSIS_API_KEY}"}
    }
  }
}
```

Load that file with `claude --mcp-config /path/to/private/mcp.json` in a shell where `REGIME_ANALYSIS_API_KEY` is set through your private credential setup. Use a dedicated revocable research key for this client. Verify the connection in `/mcp`, then ask: "Review AAPL, MSFT and SPY against the current regime; retain dates, unknowns and fund limitations, and use my strategy rules before proposing any allocation."

This bearer-key path was exercised with an actual Claude Code 2.1.285 model session on October 30, 2026. One `review_watchlist` call returned three symbols with publication date October 30 and freshness `current` (zero sessions behind). It was recorded against the version deployed on October 30 and verifies the watchlist connection only, not hosted browser consent or the five tools released on October 31, 2026. The sanitized run record is `docs/review-record/api-research-workflows-20261030/claude-code-production-acceptance.json` in the release source: request ID `be163f04-d708-475d-8356-655ba70e96f2`, publication `py-2026-10-30-b16d9f`; the record binds the private raw session transcript by SHA-256.

### OpenAI Responses API: bearer-key pilot

```python
import os
from openai import OpenAI

response = OpenAI().responses.create(
    model=os.environ["OPENAI_MODEL"],
    input="Review AAPL and SPY in regime context. Preserve dates and limitations.",
    tools=[{
        "type": "mcp",
        "server_label": "regime_analytics",
        "server_url": "https://terminal.regimeanalytics.com/mcp",
        "authorization": os.environ["REGIME_ANALYSIS_API_KEY"],
        "allowed_tools": ["review_watchlist"],
        "require_approval": "always",
    }],
)
```

This example imports the tool and retains OpenAI's approval step. Complete the returned approval request according to the current Responses documentation before expecting a tool result. Running an OpenAI API model can incur charges on your OpenAI account, and the RA pilot grant does not fund model usage.

### ChatGPT, Claude web and Perplexity: OAuth connection

Interactive web clients need a provider-supported OAuth setup rather than a pasted account key. The server implementation accepts an OAuth token scoped to `regime:read` and bound to the exact MCP resource URL, and publishes standard protected-resource metadata. Server discovery and the provider's research scope are configured. Actual client registration, consent, refresh, revocation and sign-in have not been verified for these clients, so they are not advertised as available. Protocol support in the server is not a completed client test.

## Compatibility matrix

| Surface | Status | Basis |
| --- | --- | --- |
| REST `POST /api/v2/watchlist-review` (original shape) | Production pilot, tested | Called against the deployed service with a Python command-line client and a customer key |
| MCP `/mcp` `review_watchlist` transport, bearer key | Production pilot, tested | Called against the deployed service with the official generic MCP SDK client transport |
| Claude Code bearer-key MCP (section 7) | Production pilot, tested (October 30 version) | Actual Claude Code 2.1.285 model session against the October 30 deployed version: one watchlist call, three symbols, October 30 publication; not repeated after the October 31 release |
| OpenAI Responses MCP tool recipe (section 7) | Setup recipe only | Not tested with an actual Responses API call |
| `evidence` flag, `portfolio-review`, `rule-review`, `review-changes`, `publication`, `usage` and their MCP tools | Production, tested (October 31, 2026) | Six REST operations called on the canonical production origin with the supplied Python client, and six MCP tools called with the official generic MCP SDK client transport, each with a customer bearer key, after the October 31 release |
| Publication/portfolio `cursor` and watchlist `evidence.source.cursor` | Production, tested (October 31, 2026) | Returned by the deployed publication, portfolio and watchlist-evidence responses in the same acceptance run. Equal cursors mean identical served source content, not freshness, point-in-time membership or a whole-book composition |
| Public MCP discovery (`initialize`, `tools/list`, `ping`) | Deployed; anonymous client connection and catalog tested (October 31, 2026) | The official MCP client connected and listed all six tools without a key; an anonymous analytical call returned HTTP 401. A separate ping call was not exercised |
| Python client `regime_analytics` 0.1.0 | Production, tested (October 31, 2026) | Six methods called against the canonical production origin with a customer key; offline unit tests; installed from this repository, not a package index |
| Polling notifications (`python -m regime_analytics poll`) | Cursor contract deployed; poller tested offline only | Client-side finite cursor polling with local tests; not run against production; no push, webhook or email delivery exists |
| ChatGPT, Claude web, Perplexity (browser OAuth) | Pending | Server discovery and research scope configured; hosted-client consent, refresh and revocation unverified |
| Claude API MCP connector | Not verified | No completed client test |

## 8. Handle failures and revoke access

Keep the `request_id` when reporting a failed request. Honor `Retry-After` on 429; daily allowances reset at 00:00 UTC. Each accepted authenticated REST request or MCP tool call consumes request allowance, and a valid review consumes symbol allowance even if a later publication read fails. Public MCP discovery does not. The service retains aggregate usage and key-use timestamps without storing the supplied symbol list in its usage tables. The [field guide](https://terminal.regimeanalytics.com/developer-field-guide.md#error-catalog) lists every error code and the client-side codes raised by the Python client.

Revoke a key from **My account → API & MCP** when a client is retired or a key is exposed. Revocation is checked against the account store on every new authenticated request, with no positive authorization cache. To rotate without interrupting work, create a replacement, update and test the client, then revoke the old key; an already-running request can finish.

## Machine-readable reference and source standards

- [OpenAPI 3.1 document](https://terminal.regimeanalytics.com/api/v2/openapi.json)
- [Documentation index for AI tools (llms.txt)](https://terminal.regimeanalytics.com/llms.txt)
- [MCP July 28, 2026 specification](https://modelcontextprotocol.io/specification/2026-07-28)
- [MCP authorization](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization)
- [OpenAI: authentication for plugins](https://developers.openai.com/plugins/build/auth)
- [OpenAI: MCP servers for plugins](https://developers.openai.com/plugins/build/mcp-server)
- [Claude API MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector)
- [Claude Code MCP](https://code.claude.com/docs/en/mcp)
- [Perplexity local and remote MCPs](https://www.perplexity.ai/help-center/en/articles/11502712-local-and-remote-mcps-for-perplexity)

Any information returned to a client can be retained, so bounded access reduces extraction opportunity without promising that exposed observations cannot be copied or imitated.
