An Explainable, Risk-Aware Portfolio Decision Engine
Continuous decision-making for risk-aware portfolio management.
(Hackathon Prototype β Do not use with real assets.)
This prototype is designed for hackathon judges, reviewers, and developers who want to explore an explainable, rule-based portfolio decision engine. It demonstrates risk-aware capital allocation logic without requiring real trading credentials.The Market is open from 9:30 AM to 4:00 PM ET.
- Python 3.8+ (tested on 3.10+)
- pip for installing dependencies
- A terminal/command line interface
No API keys required. Run the full system with mock data:
# 1. Clone the repository
git clone https://github.com/mrhapile/BuriBuri_Trading.git
cd BuriBuri_Trading
# 2. Install dependencies
pip3 install -r requirements.txt
# 3. Run the full system demo
python3 full_system_demo.pyThis runs the complete decision pipeline using cached historical data and demo profiles.
To use live market data during market hours, set your Alpaca paper trading credentials:
export ALPACA_API_KEY=your_paper_api_key
export ALPACA_SECRET_KEY=your_paper_secret
export ALPACA_BASE_URL=https://paper-api.alpaca.marketsSafe fallback: If credentials are missing or the API is unavailable, the system automatically uses historical data mode. No crashes, no errors.
When you run the demo, the console will display:
- System Mode β LIVE or HISTORICAL data source
- Market Posture β Current risk assessment (RISK_OFF β AGGRESSIVE)
- Position Analysis β Health scores for each holding (0-100)
- Decisions β Recommended actions with clear explanations
- Blocked Actions β Any decisions rejected by safety guardrails
Example output:
π Posture: NEUTRAL | Risk: MEDIUM
π Analyzing position vitals...
π‘οΈ Evaluating concentration limits...
β
Final decisions ready: 3 approved
[Primary Decision]
REDUCE SLOW_UTIL (Score: 42)
Reason: Vitals critically low. Reduce exposure.
β οΈ This is an advisory-only system. No trades are executed.
All recommendations are for demonstration and educational purposes only.
Do not use with real assets or production trading accounts.
Traditional trading systems treat positions as isolated events. Once opened, they stop reasoning until a fixed exit is hit.
In reality:
- Capital gets stuck in stagnant trades
- Risk accumulates silently (volatility, concentration)
- Better opportunities appear while capital is locked
BuriBuri Trading addresses this by treating capital as a resource that must continuously justify its allocation.
| Name | Role |
|---|---|
| Nishtha Vadhwani | Team Lead |
| Akash Anand | Tech Lead |
| Mohit Ray | UI/UX |
| Dev Jaiswal | Reviewer / Tester |
| Principle | Meaning |
|---|---|
| Portfolio-first | Optimizes entire portfolios, not single trades |
| Safety > Aggressiveness | Capital preservation is more important than growth |
| Explainability | Every decision has human-readable reasons |
| No Forced Action | "Doing nothing" is often the best decision |
| Transparency | Data source is always clearly labeled |
This system is an advisor. It generates high-fidelity recommendations but intentionally disables execution.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PORTFOLIO INTELLIGENCE SYSTEM β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββ ββββββββββββββ ββββββββββββββ β
β β PHASE 1 βββββΆβ PHASE 2 βββββΆβ PHASE 3 β β
β β INGEST β β SIGNALS β β DECISIONS β β
β ββββββββββββββ ββββββββββββββ ββββββββββββββ β
β β β β β
β βΌ βΌ βΌ β
β ββββββββββββββ ββββββββββββββ ββββββββββββββ β
β β Portfolio β β Volatility β β Actions β β
β β Positions β β News Score β β + Reasons β β
β β Candidates β β Confidence β β β β
β ββββββββββββββ ββββββββββββββ ββββββββββββββ β
β β β
β βΌ β
β βββββββββββββββββββββββββββββββ β
β β PHASE 4: RISK GUARDRAILS β β
β β (Concentration, Cash, β β
β β Volatility Guards) β β
β βββββββββββββββββββββββββββββββ β
β β β
β βΌ β
β βββββββββββββββββββββββββββββββ β
β β PHASE 5: EXECUTION PLAN β β
β β (Advisory Only - No Exec) β β
β βββββββββββββββββββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Phase | Module(s) | Input | Output |
|---|---|---|---|
| Phase 1 | data_router.py, broker/*.py, historical_data_service.py |
Market status, credentials | Portfolio, positions, candidates |
| Phase 2 | volatility_metrics.py, news_scorer.py, sector_confidence.py |
Candles, headlines | ATR, volatility state, news score, confidence |
| Phase 3 | decision_engine.py, position_vitals.py, concentration_guard.py |
Signals + positions | Proposed actions with reasons |
| Phase 4 | risk_guardrails.py |
Proposed actions + context | Allowed vs blocked actions |
| Phase 5 | execution_planner.py, execution_summary.py |
Safe actions | Sequential plan (advisory) |
The system automatically selects the appropriate data source based on market status:
| Market Status | Data Mode | Data Source | Symbol Selection | Time Range |
|---|---|---|---|---|
| OPEN | LIVE | Alpaca + Polygon API | From live portfolio | Disabled |
| CLOSED | HISTORICAL | Alpaca Historical Cache | User selectable | User selectable |
- Market OPEN β LIVE DATA ONLY: No fallbacks, no mixing
- Market CLOSED β HISTORICAL DATA ONLY: Uses cached Alpaca data
- Session Immutability: Data mode is locked at session start
Cached symbols for historical validation:
- SPY β S&P 500 ETF
- QQQ β NASDAQ-100 ETF
- IWM β Russell 2000 ETF
Time ranges: 1 Month, 4 Months, 6 Months, 1 Year
- Alpaca Integration is READ-ONLY
- Only paper trading URL allowed (
https://paper-api.alpaca.markets) - Credentials from environment variables only
- No write operations, no order submission
The system includes 5 behavioral scenarios that demonstrate specific agent intelligence:
| Scenario | Trigger | What It Demonstrates |
|---|---|---|
| π¨ Crash Reflex | Volatility spike | Capital preservation overrides profit-seeking |
| π‘οΈ Concentration Guard | 75%+ sector exposure | Refuses perfect trades due to structural limits |
| π Disciplined Observer | Noisy market signals | Chooses inaction over forced action |
| β»οΈ Dead Capital Rotator | Stagnant positions | Identifies and redeploys underperforming capital |
| πͺ€ Greedy Trap | High hype + high volatility | Anti-FOMO skepticism in conflicting signals |
For testing specific portfolio states:
| Profile | Capital | Scenario | Expected Response |
|---|---|---|---|
BALANCED_TECH |
$500k | Healthy, diversified | MAINTAIN structure |
OVERCONCENTRATED_TECH |
$1M | 82% in TECH | TRIM_RISK, block new TECH |
LOSING_PORTFOLIO |
$750k | Multiple losers | RISK_OFF posture |
ROTATION_SCENARIO |
$800k | TECH cooling, ENERGY rising | FREE_CAPITAL β reallocate |
CASH_HEAVY |
$500k | 40% idle cash | WAIT (reject weak trades) |
Every decision includes human-readable reasoning:
{
"action": "TRIM_RISK",
"target": "AMD",
"score": 31.0,
"reasons": [
"Position vitals critically low (Score: 31/100)",
"Sector TECH is over-concentrated (>60%)",
"High-confidence upgrade opportunity available in ENERGY"
]
}This ensures a human operator can always understand why a recommendation was made.
Safety rules applied after decisions, before execution:
| Guard | Trigger | Effect |
|---|---|---|
| Sector Concentration | Any sector > 60% | Block new allocations to that sector |
| Cash Reserve | Cash < minimum threshold | Block outflows, encourage inflows |
| Volatility Γ Aggression | High volatility + aggressive action | Scale down or block |
Rule: Safety always overrides aggressiveness. A profitable trade will be blocked if it violates safety rules.
The system maintains memory between runs:
- Tracks previous market posture
- Computes risk trend (INCREASING / DECREASING / STABLE)
- Provides context for decision continuity
Real-time visibility into the agent's thought process:
- Step-by-step signal interpretation
- Decision rationale at each phase
- Visible in the frontend "Brain Log" panel
Toggle to test defensive behavior:
- Forces RISK_OFF posture
- Demonstrates capital preservation logic
- Validates guardrail effectiveness
| Feature | Status | Details |
|---|---|---|
| Position vitals (0β100) | β | Efficiency score per position |
| Sector concentration guard | β | Warning at 60%, breach at 70% |
| Capital lock-in detection | β | Flags dead capital in cold sectors |
| Volatility regime | β | EXPANDING / STABLE / CONTRACTING |
| News sentiment | β | Keyword-based scoring (no LLM) |
| Market posture | β | RISK_OFF β AGGRESSIVE spectrum |
| Decision synthesis | β | Multi-factor, explainable output |
| Risk guardrails | β | Concentration, cash, volatility gates |
| Demo profiles | β | 5 hardcoded scenarios |
| Behavioral scenarios | β | 5 intelligence demonstrations |
| Alpaca integration | β | READ-ONLY paper trading |
| Market-aware routing | β | Auto-switches LIVE β HISTORICAL |
| Historical validation | β | SPY, QQQ, IWM cached data |
| Agent memory | β | Cross-run risk tracking |
| Reasoning stream | β | Real-time thought log |
| Crash simulation | β | Toggle for defensive testing |
| Backend API | β | Flask REST endpoint |
| Frontend dashboard | β | Full UI with market-aware controls |
| Unit tests | β | Comprehensive test suite |
| Cloud deployment | β | Render.yaml configuration |
| Broker execution | β | Intentionally disabled |
git clone https://github.com/mrhapile/BuriBuri_Trading.git
cd BuriBuri_Trading
pip3 install -r requirements.txtpython3 backend/app.pyAPI available at http://localhost:10000
Open index.html in a browser, or serve locally:
python3 -m http.server 8080
# Open http://localhost:8080 in browserpython3 full_system_demo.pyThe system automatically detects market status and uses appropriate data source.
python3 tests/test_system.pyCreate a .env file (see .env.example):
# Alpaca Paper Trading (Optional - for live mode)
ALPACA_API_KEY=your_paper_api_key
ALPACA_SECRET_KEY=your_paper_secret
ALPACA_BASE_URL=https://paper-api.alpaca.marketsNote: Alpaca credentials are optional. Without them, the system operates in HISTORICAL mode only.
| Module | Purpose |
|---|---|
data_router.py |
Market-aware data source routing |
market_mode.py |
Market status detection (OPEN/CLOSED) |
market_aware_runner.py |
Unified analysis runner |
historical_data_service.py |
Historical data access (cached Alpaca data) |
position_vitals.py |
Health and efficiency scoring (0-100) |
volatility_metrics.py |
ATR computation + regime classification |
capital_lock_in.py |
Dead capital detection |
concentration_guard.py |
Sector exposure monitoring |
news_scorer.py |
Keyword-based sentiment scoring |
sector_confidence.py |
Volatility + news β confidence |
opportunity_logic.py |
Weak vs. strong position comparison |
decision_engine.py |
Core orchestrator |
decision_explainer.py |
Human-readable explanations |
risk_guardrails.py |
Safety filtering |
execution_planner.py |
Action sequencing |
broker/alpaca_adapter.py |
READ-ONLY Alpaca client |
broker/mock_adapter.py |
Mock data generator |
demo/demo_profiles.py |
Hardcoded demo scenarios |
demo/trend_overlays.py |
Signal modifiers |
backend/app.py |
Flask REST API |
backend/api_routes.py |
REST endpoint definitions |
backend/scenarios.py |
Behavioral demo scenarios |
tests/test_system.py |
Comprehensive test suite |
.
βββ full_system_demo.py # CLI entry point
βββ decision_engine.py # Phase 3: Decision synthesis
βββ risk_guardrails.py # Phase 4: Safety gates
βββ execution_planner.py # Phase 5: Advisory planning
β
βββ data_router.py # Market-aware data routing
βββ market_mode.py # Market status detection
βββ market_aware_runner.py # Unified analysis runner
βββ historical_data_service.py # Historical data access
β
βββ volatility_metrics.py # Phase 2: Volatility signals
βββ news_scorer.py # Phase 2: News sentiment
βββ sector_confidence.py # Phase 2: Confidence scoring
β
βββ position_vitals.py # Position health scoring
βββ concentration_guard.py # Concentration detection
βββ capital_lock_in.py # Capital efficiency
βββ opportunity_logic.py # Candidate evaluation
β
βββ broker/
β βββ alpaca_adapter.py # READ-ONLY Alpaca client
β βββ mock_adapter.py # Mock data generator
β
βββ demo/
β βββ demo_profiles.py # Hardcoded portfolio profiles
β βββ trend_overlays.py # Signal modifiers for demos
β
βββ backend/
β βββ app.py # Flask server
β βββ api_routes.py # REST endpoints
β βββ scenarios.py # Behavioral demo scenarios
β βββ market_status.py # Market status helper
β
βββ historical_cache/ # Cached Alpaca historical data
β βββ SPY_*.json
β βββ QQQ_*.json
β βββ IWM_*.json
β
βββ tests/
β βββ test_system.py # Comprehensive test suite
β βββ test_historical_mode.py
β βββ test_live_mode.py
β
βββ validation/ # Validation utilities
β βββ data_manager.py
β βββ metrics.py
β βββ replay.py
β βββ runner.py
β
βββ index.html # Frontend dashboard
βββ script.js # Frontend logic
βββ styles.css # Frontend styling
β
βββ render.yaml # Cloud deployment config
βββ Procfile # Heroku/Render process file
β
βββ archive/ # Deprecated files (reference only)
- β No Order Execution β Intentionally disabled
- β No Price Prediction β Manages risk, not forecasts
- β No Black Box ML β All logic is rule-based and explainable
- β No High-Frequency Trading β Portfolio management, not scalping
- β No Live Trading β Paper trading only
- β No LLM/AI Models β Uses keyword-based sentiment, not neural networks
This system was built with engineering maturity:
- Mock First β Validated logic with synthetic data before API integration
- Phased Intelligence β Built independent signal layers
- Safety Integrated β Added guardrails as first-class citizens
- Explainability β Retrofitted all logic to explain itself
- Market-Aware Routing β Added automatic LIVE/HISTORICAL switching
- Hardening β Added demo profiles, scenarios, and regression tests
What to look for:
- Run the backend + open frontend β See market-aware controls
- Select different symbols and time ranges β Observe data source transparency
- Try behavioral scenarios β See specific agent intelligence demonstrated
- Toggle Crash Simulation β Watch defensive posture activate
- Check the Brain Log β Real-time reasoning visibility
- Review decision reasons β Each action is explained
What this proves:
- The system can reason about portfolio risk
- Safety is a first-class concern
- Decisions are explainable and auditable
- Market-awareness provides flexibility for demos
- The architecture is clean and maintainable
ARCHITECTURE.mdβ Data contracts & module dependencies- Inline docstrings in all modules
- Runnable tests:
python3 tests/test_system.py
- Capital is finite β idle capital is hidden risk
- Portfolio management > price prediction
- Explainability > black-box models
- Safety > aggressiveness
- Deterministic logic over ML heuristics
This system manages the present β it does not predict the future.
| Limitation | Reason |
|---|---|
| Historical data limited to SPY, QQQ, IWM | Cached subset for demo purposes |
| No real-time news API | Uses keyword-based scoring on mock headlines |
| Sector inference is simplified | Basic symbol-to-sector mapping |
| No portfolio persistence | Each session starts fresh |
Last updated: 2026-02-01
Β© 2026 BuriBuri Trading Team