# Yahoo Finance Stock & ETF Portfolio Backtester (MCP / Quant) (`factorlab/quant-portfolio-backtester`) Actor

Fast Yahoo Finance stock, ETF & crypto portfolio backtesting API & MCP server. Computes CAGR, Sharpe, Sortino, Max Drawdown, DCA, 200-day SMA shield, crisis stress tests & Monte Carlo in <2s.

- **URL**: https://apify.com/factorlab/quant-portfolio-backtester.md
- **Developed by:** [Daniel](https://apify.com/factorlab) (community)
- **Categories:** AI, MCP servers
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

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

## Yahoo Finance Stock & ETF Portfolio Backtester (API & MCP Server)

> **Deterministic multi-asset stock, ETF & crypto portfolio backtesting for AI Agents (Claude, Cursor, n8n, LangChain) and quant developers — runs in ~1.2s with zero proxies and zero LLM hallucination.**

Large Language Models routinely hallucinate **CAGR, Sharpe Ratio, Sortino Ratio, Maximum Drawdown, Alpha/Beta, and Monte Carlo projections**. Connect this Actor to **Apify MCP Server** or call it via REST API to compute exact, strictly causal (1-day lagged, zero lookahead) portfolio analytics across **any Yahoo Finance ticker** (US Stocks, Leveraged ETFs like `TQQQ`/`SOXL`, Index ETFs like `SPY`/`QQQ`, Gold `GLD`, Bonds `TLT`, Crypto `BTC-USD`, or Global Stocks like `005930.KS`).

### Key Capabilities

- **Multi-Asset Portfolio Backtesting & DCA**: Custom weights (`TQQQ`, `SPY`, `NVDA`, `GLD`, `BTC-USD`), lump sum + recurring monthly DCA, calendar rebalancing (`none`, `monthly`, `quarterly`, `annual`), and realistic slippage (bps).
- **Systematic Risk Overlays (Zero Lookahead)**:
  - `buy_and_hold`: Rebalanced portfolio baseline.
  - `sma200_shield`: Strictly 1-day lagged **200-day Simple Moving Average regime filter** (moves holdings below their 200MA to Treasury Bill cash yield) — always paired with a side-by-side Buy & Hold benchmark!
  - `vol_target`: Lagged 20-day realized volatility targeting.
- **Institutional Risk & Stress Telemetry**: CAGR, Total Return, Ending Wealth, Sharpe, Sortino, Calmar, Annualized Volatility, **Exact Max Drawdown Peak → Trough → Recovery Dates**, Beta/Alpha vs Benchmark, Daily 95% VaR & CVaR, Pairwise Correlation Matrix, and **Crisis Stress Tests** (`2008 GFC`, `2020 COVID`, `2022 Rate Shock`).
- **1,000-Path Block-Bootstrap Monte Carlo**: Forward `P10` (Bear), `P50` (Median), `P90` (Bull) ending wealth & probability of profit.
- **AI-Native Output**: Returns both structured JSON AND a token-compressed `llmMarkdownSummary` (`SUMMARY.md`) ready for LLM context windows.

### Use Directly Inside Claude / Cursor / AI Agents (Apify MCP)

Add the official Apify MCP server with this Actor enabled:

```json
{
  "mcpServers": {
    "apify": {
      "command": "npx",
      "args": ["-y", "@apify/actors-mcp-server", "--actors", "factorlab/quant-portfolio-backtester"],
      "env": { "APIFY_TOKEN": "YOUR_APIFY_API_TOKEN" }
    }
  }
}
```

Then ask Claude or Cursor: *"Backtest 40% TQQQ, 30% SPY, 30% GLD from 2016 with $500 monthly DCA and a 200-day SMA shield vs Buy & Hold."*

### Sample Output (Verified Live Run — 0.96s)

```json
{
  "strategy": "sma200_shield",
  "period": "2016-01-04 to 2026-11-19",
  "totalInvestedUsd": 75000.0,
  "endingValueUsd": 300061.92,
  "cagrPct": 20.78,
  "maxDrawdownPct": -28.12,
  "sharpeRatio": 0.83,
  "sortinoRatio": 0.73,
  "benchmarkCagrPct": 14.36,
  "monteCarloForecast": {
    "simulations": 1000,
    "horizonYears": 5,
    "p10BearUsd": 51918,
    "p50MedianUsd": 78840,
    "p90BullUsd": 124249,
    "probProfitPct": 98.0
  }
}
```

### Pay-Per-Event (PPE) Pricing — Zero Charge on Errors

- `backtest-completed`: **$0.02** per successful multi-asset backtest
- `monte-carlo-stress`: **$0.01** optional add-on when `runMonteCarlo: true`

*Built by [FactorLab Research](https://factorlab-research.web.app) — explore interactive 26-year leveraged ETF charts & free TradingView Pine Script v6 templates.*

# Actor input Schema

## `portfolio` (type: `object`):

JSON map of Yahoo Finance tickers to weights (auto-normalized to 100%). Supports US Stocks, Leveraged ETFs, Crypto (BTC-USD), and International tickers (e.g. 005930.KS).

## `benchmark` (type: `string`):

Reference benchmark for Alpha, Beta, and Excess Return comparisons.

## `startDate` (type: `string`):

Backtest start date (automatically aligns to earliest common trading day across all tickers).

## `endDate` (type: `string`):

Leave blank to run through the latest completed market session.

## `initialCapital` (type: `number`):

Starting lump-sum investment in USD.

## `monthlyDca` (type: `number`):

Recurring monthly cash contribution added on the first trading day of each month (0 for lump-sum only).

## `rebalance` (type: `string`):

How often portfolio weights reset to target allocations.

## `strategy` (type: `string`):

Apply a strictly 1-day lagged systematic overlay (zero lookahead) alongside Buy & Hold comparison.

## `targetVolPct` (type: `number`):

Target annualized portfolio volatility percentage when strategy='vol_target'.

## `cashYieldPct` (type: `number`):

Annualized Treasury Bill yield applied to defensive cash allocations during SMA/Vol-Target periods.

## `transactionCostBps` (type: `number`):

One-way cost in basis points (10 bps = 0.10%) applied whenever positions rebalance or switch regimes.

## `runMonteCarlo` (type: `boolean`):

Simulates 1,000 forward multi-year paths from actual historical return blocks to estimate P10/P50/P90 ending wealth.

## `forecastYears` (type: `integer`):

Number of forward years to simulate when runMonteCarlo=true.

## Actor input object example

```json
{
  "portfolio": {
    "TQQQ": 0.4,
    "SPY": 0.3,
    "GLD": 0.3
  },
  "benchmark": "SPY",
  "startDate": "2016-01-01",
  "endDate": "",
  "initialCapital": 10000,
  "monthlyDca": 0,
  "rebalance": "quarterly",
  "strategy": "sma200_shield",
  "targetVolPct": 20,
  "cashYieldPct": 3.5,
  "transactionCostBps": 10,
  "runMonteCarlo": true,
  "forecastYears": 5
}
```

# Actor output Schema

## `backtestDataset` (type: `string`):

No description

## `markdownSummary` (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 = {
    "portfolio": {
        "TQQQ": 0.4,
        "SPY": 0.3,
        "GLD": 0.3
    },
    "benchmark": "SPY",
    "startDate": "2016-01-01"
};

// Run the Actor and wait for it to finish
const run = await client.actor("factorlab/quant-portfolio-backtester").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 = {
    "portfolio": {
        "TQQQ": 0.4,
        "SPY": 0.3,
        "GLD": 0.3,
    },
    "benchmark": "SPY",
    "startDate": "2016-01-01",
}

# Run the Actor and wait for it to finish
run = client.actor("factorlab/quant-portfolio-backtester").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 '{
  "portfolio": {
    "TQQQ": 0.4,
    "SPY": 0.3,
    "GLD": 0.3
  },
  "benchmark": "SPY",
  "startDate": "2016-01-01"
}' |
apify call factorlab/quant-portfolio-backtester --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,factorlab/quant-portfolio-backtester"
        }
    }
}
```

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/Dn2LQmsH0HsJ2qlRJ/builds/s5xq32NVuBwhQnFqJ/openapi.json
