Skip to content
Portfolio Risk Assessment logo

Portfolio Risk Assessment

Comprehensive portfolio health monitoring, circuit breakers, and trade validation for risk management

mattnigh/skills_collection0installs24stars

SKILL.md

Full skill instructions

Portfolio Risk Assessment Skill

Safety-critical skill for managing trading risk and preventing catastrophic losses.

Overview

This skill provides:

  • Real-time portfolio health assessment
  • Circuit breaker monitoring and enforcement
  • Pre-trade validation
  • Post-trade result recording
  • Risk metrics calculation

Circuit Breakers (Automatic Trading Halt)

The system implements multiple circuit breakers:

  1. Daily Loss Limit: Halt trading if daily loss exceeds 2% of account value
  2. Maximum Drawdown: Halt if total drawdown exceeds 10%
  3. Consecutive Losses: Halt after 3 consecutive losing trades
  4. Volatility Spike: Halt if market volatility exceeds 3x normal
  5. Anomaly Score: Halt if trading anomalies detected

Tools

1. assess_portfolio_health

Comprehensive health check of current portfolio.

Parameters:

  • None (uses current account state)

Returns:

{
  "success": true,
  "data": {
    "overall_status": "HEALTHY",
    "account_equity": 100000.50,
    "total_pl": 150.25,
    "total_pl_pct": 0.15,
    "daily_pl": 25.50,
    "daily_pl_pct": 0.03,
    "max_drawdown": 2.5,
    "current_drawdown": 0.5,
    "position_count": 3,
    "cash_percentage": 85.0,
    "buying_power": 199500.00,
    "risk_score": 2.5,
    "warnings": []
  }
}

Health Status Levels:

  • HEALTHY: All metrics within safe ranges
  • CAUTION: Approaching risk limits (yellow flag)
  • WARNING: Risk limits being tested (orange flag)
  • CRITICAL: Circuit breakers may trigger (red flag)
  • HALTED: Trading automatically stopped

2. check_circuit_breakers

Checks if any circuit breakers should trigger.

Parameters:

  • force_check (optional): Force re-evaluation even if recently checked

Returns:

{
  "success": true,
  "data": {
    "should_halt_trading": false,
    "active_breakers": [],
    "warning_breakers": ["daily_loss_approaching"],
    "breaker_status": {
      "daily_loss": {
        "triggered": false,
        "current_value": -1.5,
        "threshold": -2.0,
        "pct_to_threshold": 75.0
      },
      "max_drawdown": {
        "triggered": false,
        "current_value": 3.5,
        "threshold": 10.0,
        "pct_to_threshold": 35.0
      },
      "consecutive_losses": {
        "triggered": false,
        "current_value": 1,
        "threshold": 3,
        "pct_to_threshold": 33.3
      }
    }
  }
}

3. validate_trade

Validates a proposed trade against risk management rules.

Parameters:

  • symbol (required): Ticker symbol
  • side (required): "buy" or "sell"
  • quantity (required): Number of shares (can be fractional)
  • order_type (required): "market", "limit", "stop", "stop_limit"
  • limit_price (optional): Limit price for limit orders
  • stop_price (optional): Stop price for stop orders

Returns:

{
  "success": true,
  "data": {
    "is_valid": true,
    "trade_approved": true,
    "estimated_cost": 150.25,
    "estimated_risk": 3.50,
    "position_size_pct": 0.15,
    "warnings": [],
    "recommendations": [
      "Consider reducing position size to 0.10% of portfolio"
    ],
    "validation_checks": {
      "sufficient_buying_power": true,
      "within_position_limits": true,
      "within_daily_trade_limit": true,
      "passes_risk_limits": true,
      "no_active_circuit_breakers": true
    }
  }
}

Validation Failures:

{
  "success": true,
  "data": {
    "is_valid": false,
    "trade_approved": false,
    "rejection_reasons": [
      "Circuit breaker active: daily_loss_limit",
      "Insufficient buying power: need $1000, have $500"
    ]
  }
}

4. record_trade_result

Records the outcome of a completed trade for risk tracking.

Parameters:

  • trade_id (required): Unique trade identifier
  • symbol (required): Ticker symbol
  • side (required): "buy" or "sell"
  • quantity (required): Shares traded
  • entry_price (required): Fill price
  • exit_price (optional): Exit price if closed
  • profit_loss (optional): Realized P/​L
  • status (required): "filled", "partial", "cancelled", "rejected"

Returns:

{
  "success": true,
  "data": {
    "recorded": true,
    "trade_id": "abc123",
    "consecutive_wins": 2,
    "consecutive_losses": 0,
    "updated_metrics": {
      "total_trades": 45,
      "winning_trades": 28,
      "win_rate": 62.2
    }
  }
}

Integration with Risk Manager

This skill wraps and extends the existing src/​core/​risk_manager.py:

from claude_skills import load_skill

risk_skill = load_skill("portfolio_risk_assessment")

# Check health before trading
health = risk_skill.assess_portfolio_health()
if health["data"]["overall_status"] != "HEALTHY":
    print(f"Warning: Portfolio status is {health['data']['overall_status']}")

# Validate trade
validation = risk_skill.validate_trade(
    symbol="AAPL",
    side="buy",
    quantity=0.5,
    order_type="market"
)

if validation["data"]["trade_approved"]:
    # Execute trade
    pass
else:
    print("Trade rejected:", validation["data"]["rejection_reasons"])

Safety Features

  1. Automatic Halting: System automatically stops trading when circuit breakers trigger
  2. Pre-Trade Validation: Every trade validated before execution
  3. Real-Time Monitoring: Continuous health assessment
  4. Audit Trail: All decisions logged for compliance
  5. Fail-Safe Defaults: System errs on the side of caution

Alert Thresholds

MetricCautionWarningCritical
Daily Loss-1.0%-1.5%-2.0%
Drawdown5%7.5%10%
Consecutive Losses234
Position Size8%10%12%
Portfolio Heat4%5%6%

Usage in Trading Loop

# Daily trading routine
while market_open:
    # 1. Check circuit breakers
    breakers = risk_skill.check_circuit_breakers()
    if breakers["data"]["should_halt_trading"]:
        print("Trading halted by circuit breakers")
        break

    # 2. Assess portfolio health
    health = risk_skill.assess_portfolio_health()
    print(f"Portfolio status: {health['data']['overall_status']}")

    # 3. Generate signals (from RL agent)
    signal = rl_agent.get_signal()

    # 4. Validate trade
    validation = risk_skill.validate_trade(**signal)

    # 5. Execute if approved
    if validation["data"]["trade_approved"]:
        result = execute_trade(signal)

        # 6. Record result
        risk_skill.record_trade_result(**result)

CLI Usage

# Check portfolio health
python scripts/​risk_assessment.py assess_portfolio_health

# Check circuit breakers
python scripts/​risk_assessment.py check_circuit_breakers

# Validate a trade
python scripts/​risk_assessment.py validate_trade \
    --symbol AAPL \
    --side buy \
    --quantity 0.5 \
    --order-type market

More skills from mattnigh

spring-framework-patterns logo
mattnigh/skills_collection

spring-framework-patterns

Comprehensive Spring Framework and Spring Boot best practices including dependency injection patterns, bean lifecycle and scopes, REST API development, Spring Data JPA, service layer design, Spring Security, testing strategies, caching, AOP, async processing, error handling, and common anti-patte...

24 0
View

TypeScript厳格モードによる型安全性設計を専門とするスキル。 📖 参照書籍: - 『Effective TypeScript』(Dan Vanderkam): 型設計 📚 リソース参照: - `resources/Level1_basics.md`: レベル1の基礎ガイド - `resources/Level2_intermediate.md`: レベル2の実務ガイド - `resources/Level3_advanced.md`: レベル3の応用ガイド - `resources/Level4_expert.md`: レベル4の専門ガイド - `resources/di...

24 0
View
deploying-cloud-k8s logo
mattnigh/skills_collection

deploying-cloud-k8s

Deploys applications to cloud Kubernetes (AKS/GKE/DOKS) with CI/CD pipelines. Use when deploying to production, setting up GitHub Actions, troubleshooting deployments. Covers build-time vs runtime vars, architecture matching, and battle-tested debugging.

24 0
View
moai-alfred-agent-guide logo
mattnigh/skills_collection

moai-alfred-agent-guide

19-agent team structure, decision trees for agent selection, Haiku vs Sonnet model selection, and agent collaboration principles. Use when deciding which sub-agent to invoke, understanding team responsibilities, or learning multi-agent orchestration.

24 0
View
mermaid-diagram-generator logo
mattnigh/skills_collection

mermaid-diagram-generator

Converts architecture descriptions, module specs, or workflow docs into Mermaid diagrams. Use when visualizing brick module relationships, workflows (DDD, investigation), or system architecture. Supports: flowcharts, sequence diagrams, class diagrams, state machines, entity relationship diagrams,...

24 0
View
pre-flight-check logo
mattnigh/skills_collection

pre-flight-check

INVOKE FIRST before any code work. Validates git workflow (branch, issue, worklog) and checks approach. Use at START of every task and END before completing. Prevents skipped steps.

24 0
View
browser-dev-tools logo
mattnigh/skills_collection

browser-dev-tools

This skill should be used when working with browser-rendered artifacts (i.e. Bun, React/React Native) to proactively validate that development work on localhost is being built appropriately and to support debugging browser-rendered content. Use this skill after making frontend changes to verify t...

24 0
View
lead-dev logo
mattnigh/skills_collection

lead-dev

Lead Développeur - Coordination technique opérationnelle, code review, mentoring et livraison. Pair de web-dev-process au niveau OPÉRATIONS.

24 0
View
worker-monitor logo
mattnigh/skills_collection

worker-monitor

Monitor Docker workers, RQ queue health, and auto-scale workers (max 4). Use when: checking job progress, monitoring queue depth, scaling workers up/down, diagnosing slow processing, or waiting for jobs to complete. Referenced by data-quality skill during reprocessing.

24 0
View
quality-advisor logo
mattnigh/skills_collection

quality-advisor

Proactive quality guidance system that monitors artifact creation and provides real-time feedback on documentation quality

24 0
View
bump-version logo
mattnigh/skills_collection

bump-version

This skill should be used when the user wants to bump the version number in the workspace. It updates versions across all pyproject.toml files (root, tde, and tda packages) and the CHANGELOG.md to keep them synchronized.

24 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View