# Quant Finance, Portfolio Risk, Kelly & DCF Math Engine (MCP) (`durative_hairstreak/quant-portfolio-dcf-math-engine`) Actor

Eliminate LLM math hallucinations. Deterministic quantitative finance API & MCP server computing portfolio Sharpe, Sortino, Max Drawdown, VaR/CVaR, Half-Kelly sizing, multi-stage DCF + 5x5 sensitivity, XIRR/IRR & Black-Scholes Greeks in <1s. Zero external APIs, 100% uptime.

- **URL**: https://apify.com/durative_hairstreak/quant-portfolio-dcf-math-engine.md
- **Developed by:** [Tao Zhu](https://apify.com/durative_hairstreak) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 calculation executeds

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

## Quant Finance, Portfolio Risk, Kelly & DCF Math Engine (MCP Server & API)

> **Eliminate LLM financial math hallucinations forever.** Deterministic institutional-grade quantitative finance calculator API & hosted MCP server computing **Portfolio Risk (Sharpe, Sortino, Calmar, Max Drawdown, Historical & Parametric VaR/CVaR)**, **Multi-Stage DCF Valuation + 5×5 WACC/Growth Sensitivity Matrix**, **Half-Kelly & Stop-Loss Constrained Position Sizing**, **Exact Newton-Raphson IRR / XIRR / NPV & Loan Amortization**, and **Black-Scholes-Merton Option Pricing, Greeks & Implied Volatility**.

**Zero external APIs · Zero proxies · 100.00% uptime · Sub-second deterministic execution (`<1s`).**

***

### Why AI Agents & Finance Workflows Call This Tool

Large Language Models routinely hallucinate multi-period compounding, Newton-Raphson XIRR roots, standard normal CDF integrals (`Black-Scholes`), downside deviation (`Sortino`), and 25-cell DCF sensitivity tables. Connecting your **Claude Desktop, Cursor, LangGraph, CrewAI, n8n, or autonomous finance agent** to this hosted MCP engine guarantees **auditable, exact IEEE-754 financial math** on every call.

| Mode (`mode`) | Institutional Outputs Returned | Core Use Cases |
| :--- | :--- | :--- |
| **`portfolio_risk`** | CAGR, Annualized Vol, Sharpe, Sortino, Calmar, Peak-to-Trough Max Drawdown & Recovery Periods, 95%/99% Historical & Parametric VaR/CVaR, Win Rate, Profit Factor, Skewness, Excess Kurtosis | Backtest auditing, wealth management reviews, automated portfolio risk alerts |
| **`dcf_valuation`** | Discounted FCF Schedule, Gordon Growth Terminal Value & Optional Exit Multiple cross-check, EV, Equity Value, Implied Share Price, Margin of Safety %, Bear/Base/Bull Scenarios, **5×5 WACC × Terminal Growth Matrix** | AI equity research assistants, investment memo automation, CFO modeling |
| **`kelly_position_sizing`** | Expectancy (`R`), Full/Half/Quarter Kelly %, Max Single Position Cap, Stop-Loss Risk Budget Max Shares, `finalActionableShares`, Max Dollar Loss at Stop | Systematic trading risk guardrails, automated trade pre-checks |
| **`cashflow_irr_npv`** | Exact **IRR & Dated XIRR**, NPV, MOIC, Net Profit, Simple Payback Period, plus full Mortgage/Loan Amortization (`monthlyPayment`, `totalInterestPaid`) | Private equity / VC deal memos, capex evaluation, mortgage & refinancing agents |
| **`option_greeks`** | Black-Scholes-Merton European Call/Put Price, Intrinsic/Time Value, **Implied Volatility Solver**, Delta, Gamma, Vega, Daily Theta, Rho, `d1`/`d2`, ITM/ATM/OTM | Options desk tooling, derivatives education, automated hedging calculators |

***

### Live Verified Sample Outputs

| Calculation Task | Mode | Verdict | Headline Output |
| :--- | :--- | :--- | :--- |
| Multi-Stage Tech DCF Valuation | `dcf_valuation` | `UNDERVALUED` | `$450.54 (+210.72%)` with full 5×5 WACC × Terminal Growth grid |
| Monthly Equity Curve Risk Audit | `portfolio_risk` | `INSTITUTIONAL_QUALITY` | `Sharpe 2.45 \| MDD -3.85%`, Sortino, Calmar, 95% HistVaR/CVaR |
| Half-Kelly Risk-Capped Sizing | `kelly_position_sizing` | `STANDARD_POSITION` | `16.00% (128 shares)` auto-tightened by 2% portfolio stop-loss cap |

***

### Connect to Claude Desktop, Cursor, or Any MCP Client

```json
{
  "mcpServers": {
    "quant-finance-math-engine": {
      "url": "https://mcp.apify.com/?actors=durative_hairstreak/quant-portfolio-dcf-math-engine"
    }
  }
}
```

#### Direct REST API Example (cURL / Python)

```bash
curl -X POST "https://api.apify.com/v2/acts/durative_hairstreak~quant-portfolio-dcf-math-engine/run-sync-get-dataset-items?token=YOUR_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "calculations": [
      {
        "label": "ATM Call Option + IV Check",
        "mode": "option_greeks",
        "params": {
          "spot": 100, "strike": 100, "timeToExpiryYears": 1,
          "riskFreeRate": 0.05, "volatility": 0.20, "optionType": "call"
        }
      }
    ]
  }'
```

***

### Frequently Asked Questions (FAQ)

**Does this Actor depend on Yahoo Finance, Bloomberg, or any external scraper that can break?**
No. It is a **100% pure deterministic mathematical engine** operating strictly on parameters passed in the request (by your user, SEC XBRL feed, brokerage CSV, or upstream AI agent). That means **zero upstream rate limits, zero proxy costs, and sub-second execution**.

**Can I pass multiple calculations in a single API/MCP call?**
Yes! Pass an array in `calculations` mixing any combination of `dcf_valuation`, `portfolio_risk`, `kelly_position_sizing`, `cashflow_irr_npv`, and `option_greeks` to return structured JSON records in a single run.

**Is this investment advice?**
No. All outputs are strictly deterministic mathematical calculations derived from user-supplied assumptions and inputs. Nothing returned constitutes investment, financial, tax, or legal advice.

***

### Companion RiskOps MCP Suite by `durative_hairstreak`

- **[SEC 8-K Risk Signals & Corporate Distress Monitor](https://apify.com/durative_hairstreak/sec-8k-risk-signals)** — Real-time US SEC Form 8-K cyber breaches (Item 1.05), restatements (Item 4.02), auditor exits (Item 4.01) & C-suite departures.
- **[SaaS & Cloud Status Page SLA Uptime Monitor](https://apify.com/durative_hairstreak)** — Live outages and merged-interval 30d/90d SLA % across 22+ AI & Cloud Statuspage APIs.
- **[B2B Vendor Security Posture & Trust Signal Auditor](https://apify.com/durative_hairstreak)** — Zero-WAF DNS CNAME fingerprinting for Vanta/SafeBase/Drata Trust Centers, DMARC/SPF/MX & TLS posture.
- **[Open-Source Supply-Chain & CVE Risk Auditor](https://apify.com/durative_hairstreak)** — Pre-install `BLOCK`/`WARN`/`ALLOW` gatekeeper for Claude Code & Cursor via OSV.dev, CISA KEV & OpenSSF Scorecard.

# Actor input Schema

## `calculations` (type: `array`):

Array of calculation objects. Each object requires `mode` (`portfolio_risk` | `dcf_valuation` | `kelly_position_sizing` | `cashflow_irr_npv` | `option_greeks`), optional `label`, and `params` for that mode.

## `precision` (type: `integer`):

Decimal places for rounded numeric outputs (2 to 8).

## Actor input object example

```json
{
  "calculations": [
    {
      "label": "Multi-Stage Tech DCF Valuation",
      "mode": "dcf_valuation",
      "params": {
        "currentSharePrice": 145,
        "sharesOutstanding": 2450,
        "netDebt": -25000,
        "wacc": 0.095,
        "terminalGrowthRate": 0.035,
        "projectedFreeCashFlows": [
          42000,
          51000,
          60000,
          69000,
          78000
        ]
      }
    },
    {
      "label": "Monthly Equity Curve Risk Audit",
      "mode": "portfolio_risk",
      "params": {
        "equityCurve": [
          100000,
          104500,
          102100,
          108900,
          114200,
          109800,
          118500,
          123400,
          119000,
          127800,
          134200,
          139600,
          146000
        ],
        "periodsPerYear": 12,
        "riskFreeRateAnnual": 0.0425,
        "confidenceLevel": 0.95
      }
    },
    {
      "label": "Half-Kelly Risk-Capped Position Sizing",
      "mode": "kelly_position_sizing",
      "params": {
        "winProbability": 0.56,
        "rewardToRiskRatio": 1.85,
        "portfolioValue": 100000,
        "entryPrice": 125,
        "stopLossPrice": 112,
        "maxPortfolioRiskPct": 0.02,
        "kellyFractionMultiplier": 0.5,
        "maxSinglePositionPct": 0.2
      }
    }
  ],
  "precision": 4
}
```

# Actor output Schema

## `quantCalculationsDataset` (type: `string`):

No description

## `batchSummary` (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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("durative_hairstreak/quant-portfolio-dcf-math-engine").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("durative_hairstreak/quant-portfolio-dcf-math-engine").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 '{}' |
apify call durative_hairstreak/quant-portfolio-dcf-math-engine --silent --output-dataset

```

## MCP server setup

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

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/Bxm5QGgPKyVarWNrJ/builds/clWqRq0V5AdZL667a/openapi.json
