# Risk & Volatility  (Sharpe, Sortino, Drawdowns, Recovery & VaR) (`khnaami/risk-volatility-sharpe-sortino-drawdowns-recovery-var`) Actor

Institutional quantitative risk analytics for Stocks, ETFs, Crypto, Forex, and Indices: Annualized Sharpe & Sortino ratios, Maximum Drawdown depth and recovery timelines, 1-year rolling Sharpe series, return skewness/kurtosis, and Value at Risk (VaR / CVaR).

- **URL**: https://apify.com/khnaami/risk-volatility-sharpe-sortino-drawdowns-recovery-var.md
- **Developed by:** [khalid naami](https://apify.com/khnaami) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

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

## 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

## 🛡️ Risk & Volatility Intelligence Actor

**Quantitative risk profiling, peak drawdown analysis, recovery timelines, rolling Sharpe ratios, and Value at Risk (VaR / CVaR) across global Stocks, ETFs, Crypto, Forex, Indices, and Commodities.**

***

### 🌟 Overview

The **Risk & Volatility Intelligence Actor** calculates quantitative risk and portfolio protection metrics used by hedge funds and institutional risk managers:

1. **Risk-Adjusted Performance Ratios:**
   - **Annualized Sharpe Ratio:** Measures excess return per unit of total risk against a configurable risk-free rate.
   - **Annualized Sortino Ratio:** Measures excess return against downside volatility only (ignores upside volatility).
   - **Calmar Ratio:** Compound annual return (CAGR) relative to the maximum peak drawdown.
2. **Drawdown Profile & Peak-to-Trough Recovery Timelines:**
   - Maximum historical drawdown percentage and day-by-day drawdown curve.
   - Granular **Drawdown Events Ledger** tracking every drawdown period: Start date, Trough date, Recovery date, duration in business days, and Ongoing status.
   - Average and longest recovery duration in trading days.
3. **1-Year (252-Day) Rolling Sharpe Ratio:**
   - Moving 1-year window Sharpe ratio time-series to track regime shifts in risk-adjusted performance.
4. **Return Distribution & Gaussian Fit (Bell Curve):**
   - 50-bin return frequency histogram, parametric Gaussian probability density function (PDF), Skewness, Kurtosis, and standard deviation bounds ($\mu \pm 1\sigma, \pm 2\sigma$).
5. **Value at Risk (VaR) & Expected Shortfall (CVaR):**
   - 95% and 99% daily Value at Risk and 95% Conditional Value at Risk (Expected Shortfall).

***

### 📥 Input Parameters

| Field | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `symbols` | Array / String | `["SPY", "QQQ", "AAPL", "NVDA"]` | Tickers or symbols to analyze. Supports Stocks, ETFs, Crypto (`BTC-USD`), Forex (`EURUSD=X`), Futures/Commodities (`GC=F`), and Indices (`^SPX`, `^NDX`, `^VIX`). |
| `yearsBack` | Integer | `5` | Historical lookback horizon in years (1 to 50). |
| `startDate` | String | `null` | Optional explicit start date (`YYYY-MM-DD`). |
| `endDate` | String | `null` | Optional explicit end date (`YYYY-MM-DD`). |
| `riskFreeRate` | Number | `4.0` | Annual risk-free rate percentage for Sharpe/Sortino ratios (e.g. `4.0` for 4%). |
| `rollingWindow` | Integer | `252` | Window size for rolling Sharpe calculations (default 252 trading days). |
| `includeTimeSeries` | Boolean | `true` | Include day-by-day drawdown series and rolling Sharpe curves in output. |
| `includeReturnDistribution` | Boolean | `true` | Include 50-bin histogram and Gaussian PDF curve. |

***

### 📤 Output Dataset Format

Each asset record in the dataset provides complete quantitative risk analytics:

```json
{
  "symbol": "SPY",
  "name": "SPDR S&P 500 ETF Trust",
  "dataProvider": "Yahoo Finance",
  "latestPrice": 570.25,
  "currentSharpe": 1.12,
  "currentSortino": 1.65,
  "calmarRatio": 0.58,
  "maxDrawdownPct": -25.49,
  "avgDrawdownRecoveryDays": 24.6,
  "longestDrawdownDays": 182,
  "annualizedVolatilityPct": 16.85,
  "annualizedCagrPct": 14.78,
  "totalPeriodReturnPct": 98.42,
  "valueAtRisk95Pct": -1.54,
  "valueAtRisk99Pct": -2.68,
  "expectedShortfall95Pct": -2.25,
  "drawdownEvents": [
    {
      "year": 2022,
      "duration_business_days": 182,
      "drawdown_start_date": "2022-01-04",
      "drawdown_trough_date": "2022-10-12",
      "recovery_end_date": "2023-12-14",
      "trough_drawdown_pct": -25.49,
      "is_ongoing": false
    }
  ],
  "riskAssessment": {
    "grade": "EXCELLENT RISK-ADJUSTED (TIER 1)",
    "color_tag": "EMERALD",
    "assumed_risk_free_rate_pct": 4.0
  }
}
```

***

### 💻 Python Client Usage

```python
from apify_client import ApifyClient

client = ApifyClient("<YOUR_APIFY_API_TOKEN>")

run = client.actor("your-username/risk-volatility-actor").call(run_input={
    "symbols": ["SPY", "QQQ", "BTC-USD", "NVDA", "AAPL"],
    "yearsBack": 5,
    "riskFreeRate": 4.0,
    "includeTimeSeries": True,
    "includeReturnDistribution": True
})

for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(f"Asset: {item['symbol']} | Sharpe: {item['currentSharpe']} | Max DD: {item['maxDrawdownPct']}%")
```

# Actor input Schema

## `symbols` (type: `array`):

List of tickers or symbols to analyze (e.g. SPY, QQQ, AAPL, NVDA, TSLA, BTC-USD, EURUSD=X, GC=F).

## `yearsBack` (type: `integer`):

Historical time horizon in years for drawdown analysis and risk calculation (e.g., 5, 10, 20).

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

Optional explicit start date (YYYY-MM-DD). If provided, overrides yearsBack.

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

Optional explicit end date (YYYY-MM-DD). Defaults to current date.

## `riskFreeRate` (type: `number`):

Benchmark risk-free rate percentage used for Sharpe and Sortino calculations (e.g. 4.0 for 4%).

## `rollingWindow` (type: `integer`):

Window size for rolling Sharpe ratio calculation (default 252 trading days / 1 year).

## `includeTimeSeries` (type: `boolean`):

Include day-by-day drawdown series and rolling Sharpe time series arrays in the output.

## `includeReturnDistribution` (type: `boolean`):

Include 50-bin return frequency distribution, Gaussian PDF curve, and Value at Risk (VaR / CVaR).

## Actor input object example

```json
{
  "symbols": [
    "SPY",
    "QQQ",
    "AAPL",
    "NVDA"
  ],
  "yearsBack": 5,
  "riskFreeRate": 4,
  "rollingWindow": 252,
  "includeTimeSeries": true,
  "includeReturnDistribution": true
}
```

# Actor output Schema

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

Dataset items and records produced by the Actor

## `overview` (type: `string`):

Summary report stored in Key-Value store

# 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 = {
    "symbols": [
        "SPY",
        "QQQ",
        "AAPL",
        "NVDA"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("khnaami/risk-volatility-sharpe-sortino-drawdowns-recovery-var").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 = { "symbols": [
        "SPY",
        "QQQ",
        "AAPL",
        "NVDA",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("khnaami/risk-volatility-sharpe-sortino-drawdowns-recovery-var").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 '{
  "symbols": [
    "SPY",
    "QQQ",
    "AAPL",
    "NVDA"
  ]
}' |
apify call khnaami/risk-volatility-sharpe-sortino-drawdowns-recovery-var --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,khnaami/risk-volatility-sharpe-sortino-drawdowns-recovery-var"
        }
    }
}
```

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/34L7ynAnqfhjyoQ1k/builds/0kVlWzxZUw9U3GNeO/openapi.json
