← Financial Cloud Cloud Cloud Club · Builder Articles

Vertex Macro | Financial Cloud Cloud · Builder Articles

Build with Kiro: AWS AI-Powered Trading Desk Assistant for the Quant Board

Series: Kiro workshop

Article: 35

Article
Kiro workshop
01 Build with Kiro: Prompt-First Product Design for a Tagalog Learning App
Kiro workshop
02 Build with Kiro: Educational-First Dev Tips for a Tagalog Learning App
Kiro workshop
03 Build with Kiro: Deep-Dive Development Flow for a Tagalog Learning App
Kiro workshop
04 Build with Kiro: Localize a Tagalog Learning App into Chinese Variants Workshop
Kiro workshop
05 Build with Kiro: Grammar and Pronunciation Enrichment Pipeline for Tagalog Cards Workshop
Kiro workshop
06 Build with Kiro: Unique and Reviewable Extra Examples in a Tagalog Learning App Workshop
Kiro workshop
07 Build with Kiro: Factory Engineering Health Hooks Workshop
Kiro workshop
08 Build with Kiro: Etch Process Window Risk Test Automation Workshop
Kiro workshop
09 Build with Kiro: Photolithography Drift Risk Development Workshop
Kiro workshop
10 Engineering Team Get Started — Daily Fab-Duty Use of fab spc drift sync portal
Kiro workshop
11 Engineering Team Addendum — Daily Fab-Duty Use of fab spc drift sync portal
Kiro workshop
12 Kiro: Field Engineering Workshop for Spec-Driven Factory Software
Kiro workshop
13 Kiro: Hands-On Lab — Build a Typed Factory Risk Portal from Scratch
Kiro workshop
14 Kiro: Prompt, Code, and Type Standards Playbook for Engineering Developers
Kiro workshop
15 Kiro: Why a Strong React Prompt Prevents Type Declaration False-Starts
Kiro workshop
17 Build with Kiro: Create a Factory Automation Portal React UI
Kiro workshop
18 Build with Kiro: Create the Automation Analytics Engine Behind a Factory Automation Portal
Kiro workshop
19 Build with Kiro: Add an AI Factory Automation Assistant to a Factory Automation Portal
Kiro workshop
21 Kiro: 2-Hour Professional Developer Workshop Guide
Kiro workshop
22 Kiro: Build the Fab SPC Drift Synchronization Portal from Scratch
Kiro workshop
23 Kiro: Prompt Library and Deep Code Explanation Appendix
Kiro workshop
30 Build with Kiro: Create a Factory Automation Portal UI
Kiro workshop
31 Build with Kiro: Create the Automation Analytics Engine Behind a Factory Automation Portal
Kiro workshop
32 Build with Kiro: Add an AI Factory Automation Assistant to a Factory Automation Portal
Kiro workshop
33 Build with Kiro: Rebuild the CME Direct-Style Quant P&L Leaderboard UI
Kiro workshop
34 Build with Kiro: Recreate the Quant Analytics Engine Behind the P&L Board
Kiro workshop
35 Build with Kiro: AWS AI-Powered Trading Desk Assistant for the Quant Board
Kiro workshop
36 One-Page Trading Portal SOP
Kiro workshop
AgentCore
A1 Build with AgentCore & Strands: Gateway MCP Tool Fabric Developer Workshop
AgentCore
A2 Build with AgentCore & Strands: Governed Multi-Agent Risk System Developer Workshop
AgentCore
A3 Build with AgentCore & Strands: Runtime Sovereign Risk Agent Developer Workshop
AgentCore
Exam practice
E1 Build a Multilingual AWS Exam Practice Launch System with Vibe Coding
Exam practice
E2 Build an AWS Exam Practice Room with Vibe Coding Dev Tips
Exam practice
E3 Build the Practice Engine Behind a Static AWS Exam Room
Exam practice
Amazon Q
Q1 Amazon Q: CloudShell-First Developer Workshop for ACM Certificate Auto Renewal
Amazon Q
Tagalog Practice Room
T1 Build a Tagalog Learning App for AWS Manila Community Day with Prompt-First Product Design
Tagalog Practice Room
T2 Build Tagalog Learning App for AWS Manila Community Day with Educational-First Dev Tips
Tagalog Practice Room
T3 Deep Dive Development Flow for a Tagalog Learning App for AWS Manila Community Day
Tagalog Practice Room
T4 Build Localize a Tagalog Learning App into Chinese Variants for AWS Manila Community Day
Tagalog Practice Room
T5 Build a Grammar and Pronunciation Enrichment Pipeline for Tagalog Cards for AWS Manila Community Day
Tagalog Practice Room
T6 Make Extra Examples Unique and Reviewable in a Tagalog Learning App for AWS Manila Community Day
Tagalog Practice Room
Roadmap
R1 Enterprise Data Analytics Roadmap: 100 Deep Scenario Questions
Roadmap
R2 Front-End Development Roadmap: Real-World Enterprise Scenarios
Roadmap
Hong Kong Community Day
C1 A Hong Kong Weekend with AWS Community Day: From Cloud Sessions to Harbour Lights
Hong Kong Community Day
C2 The Speaker’s Luxury Weekend: Present an AWS Story, Then Let Hong Kong Take the Stage
Hong Kong Community Day
C3 Seventy-Two Hours in Hong Kong: The Grand Tour for an AWS Community Day Speaker
Hong Kong Community Day
Manila Community Day
C4 AWS Community Day Manila: A Joyful Weekend of Cloud, Culture, and True Friendship
Manila Community Day
C5 AWS Community Day Manila: Where Cloud Builders Find the Happiest Spirit of the Philippines
Manila Community Day
C6 AWS Community Day Manila: Build, Break, Repeat, and Belong in a City of Joy
Manila Community Day
C7 First-Time Visitor Tips for Manila, Philippines
Manila Community Day
Philippines × Hong Kong
C8 Philippines Hong Kong Capital Market Upgrade
Philippines × Hong Kong
Backtest
B1 Build Institutional Amazon Long-Only Backtesting Agents With Bedrock AgentCore And Strands Agents
Long-only AMZN agents with AgentCore, Strands, and a governed Backtrader ledger.
B2 Build Regime-Aware Amazon Position Management With Backtrader, AgentCore, And Strands Agents
Treat market regime as a position control, not a chart comment.
B3 Build Benchmark-Relative Amazon Timing Systems Using Nasdaq, S&P 500, Dow, AgentCore, And Strands
Time AMZN against Nasdaq, S&P 500, and Dow context.
B4 Build A Governed Amazon Trade-History Factory With Bedrock AgentCore, Strands Agents, And Backtrader
Turn backtests into an auditable trade-history factory.
B5 Build An Agentic Amazon Backtest Operating Model With Bedrock AgentCore And Strands Agents [Part 1]
Build the operating model before debating the result.
B6 Build A Custom Cerebro Code Talk For Amazon Timing And Position Management [Part 2]
Explain the Cerebro engine before explaining the chart.
B7 Build Trader Review Records For Amazon Strategy Results And Lessons Learned [Part 3]
Turn strategy ranks into trader review records.
B8 Build A Governed FSI Amazon Position Management Playbook With AgentCore And Strands [Part 4]
An FSI playbook for governed Amazon position management.
B9 Build a Sovereign Risk Trading Agent with Amazon Bedrock AgentCore for Yield Spreads, FX Hedging, and Debt Repricing
Sovereign-risk agent for yield spreads, FX hedges, and debt repricing.
B11 Build Modern Volatility Trading & Lawful Thailand Recovery Planning Agents: A Memory-Driven Strands Multi-Agent Risk Protection System
Memory-driven Strands agents for volatility and Thailand recovery.
B12 Build Short Straddle Trading-Risk Governance with Amazon Bedrock AgentCore Memory
Short-straddle risk governance with AgentCore Memory.
B13 Building Production-Ready Credit & Yield Staking AI Agents on Amazon EKS
Production credit and yield-staking agents on Amazon EKS.
Challenge
01 Weekend Productivity Challenge: Fab SPC Drift Synchronization Portal
Fab SPC drift review and recommendation portal.
02 Weekend Productivity Challenge: Quant P&L Commander — An AI-Powered Trading Productivity Portal on AWS
Quant P&L leaderboard and trading productivity portal.
03 Weekend Annoying Task Challenge: Trading Desk Execute Summary On Cloud, On Chain, On Air
DeskPulse daily execution communication.
04 Weekend Agent Challenge: The 6 AM Trading Risk Review
An unattended, evidence-backed morning credit and trading risk brief.
05 Weekend Creative Challenge: Leadership Card Game
A browser-based creative facilitation deck.
06 Full Stack Challenge: Community Day Board App
A browser-based event communication room.
Leadership Card Game
01 Leadership Card Game: Last Skill Cloud Did Not Automate
A field essay for Builders on language, courage, and the Leadership Card Game
02 Anatomy of a Leadership Round: How the Leadership Card Game Actually Plays
A facilitator’s field guide for Builders who want drills that fit inside real meetings
03 Leadership Card Game: When the Opportunity Stops Belonging to the Organizer
A field essay for Builders on power transfer, multilingual practice nights, and career arcs that complete Entrance, Resource, and Narrative
04 Weekend Creative Challenge: Leadership Card Game
Master high-stakes workplace conversations before they happen.
05 From a Weekend Challenge Project to $1,386 Crowdfunding: The Leadership Practice That Changes How You Show Up at Work
A weekend build became a live 600-card leadership practice room and reached $1,386 in crowdfunding.
06 From a Weekend Challenge Project to $1,386 Crowdfunding: A Day 1 Path Into the Tech Industry
How did a weekend challenge become a multilingual AWS-powered product with 600 cards and $1,386 in crowdfunding?
07 From a Weekend Challenge Project to $1,386 Crowdfunding: Build a Professional Brand by Transferring Opportunity
A weekend challenge reached $1,386 in crowdfunding by turning leadership ideas into a working multilingual product.
08 Leadership Card Game — Crowdfunding Campaign
Speak leadership before the room decides your career.
09 PR/FAQ 01 — Leadership Card Game launches for community builders
Working Backwards document · External press release + FAQ Product: Leadership Card Game Audience: Community managers, volunteer organizers, early-career…
10 PR/FAQ 02 — Enterprise facilitators adopt Leadership Card Game for live leadership drills
Working Backwards document · External press release + FAQ Product: Leadership Card Game Audience: Learning & development leads, people managers, agile…
10 PR/FAQ 03 — Multilingual Leadership Card Game opens global practice rooms for builder ownership
Working Backwards document · External press release + FAQ Product: Leadership Card Game Audience: Global AWS builders, bilingual communities, cross-border…
AWS Builder Center
01 AWS Builder Center, its community spirit, and AWS Builder Jacket
There are destinations you reach by plane, destinations you enter through a door, and destinations that begin with a sign-in screen and quickly feel like a…
02 Inside AWS Builder Center, where a global technical platform becomes a place to learn, contribute, and belong
A great journey does not always begin at an airport.
03 AWS Community Builder huge success
When builders share openly, the entire community moves forward.
04 AWS Builder Center huge success
A vibrant global district built for curiosity, public learning, and the AWS Builder Jacket.
05 A weekend inside AWS Builder Center, from community inspiration to unmistakable AWS Builder Jacket
Friday evening begins with a familiar builder feeling: there is an idea waiting somewhere between a problem and a possibility.

Summary: This standalone workshop teaches developers to extend the uploaded quant leaderboard with AWS AI services and Kiro. Developers build a trading-desk assistant that ingests demo leaderboard data, explains strategies and metrics, generates non-advisory risk commentary with Amazon Bedrock, retrieves glossary knowledge, stores insights, and uses Kiro specs, steering, hooks, tests, and guardrails for professional AI application delivery using audited workflows.

Workshop purpose

This 2-hour workshop focuses on adding an AWS AI service layer around the quant board. The original HTML demo is a front-end workspace. This workshop turns the data and terminology into an AI-assisted developer project: a backend service that explains leaderboard rows, metric definitions, strategy styles, market-tile context, and risk warnings using Amazon Bedrock, retrieval grounding, Kiro specs, and strict non-advisory guardrails.

Demo coverage map

This workshop covers these demo concepts through AI features:

  • Top-level workspace meaning: “CME Direct-style quant board,” internal challenge, demo data, live NAV, RFQ mode.
  • Participant insights for all 8 traders and strategies.
  • Market summaries for ES, CL, GC, and BTC.
  • Explanation of leaderboard columns: NAV, Daily, Spark, SR, PF, WR, Max DD, Analysis.
  • Explanation of expandable panel metrics: Window Return, Realized Vol, Calmar, VaR 95, Best Day, Worst Day, Win Rate, Max DD.
  • Explanation of chart semantics: NAV path, drawdown waterline, daily P&L distribution, return bars.
  • Safety behavior: no investment advice, no buy/sell/hold recommendations, demo-only context.
  • Auditability: store generated commentary and source data snapshot.

Target developers

  • AI application developers building finance-safe assistants.
  • Backend developers integrating Amazon Bedrock into internal tools.
  • Full-stack developers extending a dashboard with an explanation API.
  • Platform developers learning Kiro specs, steering, hooks, and guardrails.

Two-hour agenda

Time Module Developer output
0:00-0:10 Define AI use cases assistant capabilities and safety boundary
0:10-0:25 Kiro steering/spec non-advisory AI behavior, data model, tasks
0:25-0:45 Knowledge corpus glossary and demo-data JSON documents
0:45-1:05 Prompt contract Bedrock prompt and response schema
1:05-1:25 Lambda API explain-trader and explain-board handlers
1:25-1:40 Persistence DynamoDB audit record design
1:40-1:55 Tests and eval prompt, schema, refusal tests
1:55-2:00 Kiro review production hardening backlog

Architecture

React quant board
  │ clicks "AI Explain"
  ▼
API Gateway
  ▼
Lambda explain-handler
  ├─ validates request
  ├─ loads demo leaderboard snapshot
  ├─ retrieves glossary/rules context
  ├─ builds non-advisory Bedrock prompt
  ├─ invokes Amazon Bedrock Converse API
  ├─ validates JSON response
  ├─ writes DynamoDB audit record
  └─ returns explanation to UI

AI assistant capabilities

Capability Inputs Output Safety rule
Explain trader Trader row and advanced metrics Strategy summary, metric interpretation, risk observations No buy/sell/hold or sizing advice
Explain board All rows, stats, market tiles Leaderboard summary and risk-quality comparison Use demo data only
Explain metric Metric name such as Calmar or VaR 95 Definition and trading-decision usage Educational context only
Explain market tile ES/CL/GC/BTC tile Meaning of state and movement Do not infer real market direction
Generate test checklist Source data and metric list Developer testing checklist No generated trading signal

Financial service terms and decision usage

Term Demo definition How assistant explains trading use
NAV Strategy value indexed from 100. Compares accumulated performance, but should be combined with drawdown and volatility.
Daily P&L Daily return movement. Indicates short-term contribution, not full strategy quality.
Sharpe Ratio Risk-adjusted return metric. Higher value can mean better return per volatility unit, but tail risk remains.
Profit Factor Gross gain versus gross loss. Helps check if winners outweigh losers.
Win Rate Positive-period percentage. Useful for consistency; insufficient without payoff size.
Max Drawdown Worst previous-peak decline. Shows capital pain and risk-limit pressure.
Calmar Ratio Return divided by absolute drawdown. Highlights return earned per drawdown unit.
VaR 95 Simplified downside percentile. Indicates historical downside threshold for risk discussion.
Greeks Options risk sensitivities. The assistant can define the concept but should not calculate Greeks unless supplied.
Depth Market liquidity concept. Explains order-book context but does not infer real liquidity from demo tiles.
RFQ Request for Quote workflow. Explains quote-driven execution context in institutional trading.

Step 1 — Create project

mkdir kiro-quant-board-ai-assistant && cd kiro-quant-board-ai-assistant
python -m venv .venv
source .venv/bin/activate
pip install boto3 pydantic pytest
mkdir -p .kiro/steering .kiro/specs/ai-assistant .kiro/hooks src data knowledge tests eval

Business logic: The assistant explains the board to developers and analysts. It should improve understanding, not create trading recommendations.

Code logic: Python is used for the serverless backend. Data and knowledge folders hold approved context that prompts can use.

Expected result: A repository ready for Kiro-assisted AI backend design.

System design rationale: 1. The AI layer is separated from the frontend so explanation generation can be tested, secured, logged, and audited independently. 2. Python is selected because it is concise for Lambda handlers and data validation. 3. Data and knowledge are local first, allowing developers to test grounding before deploying AWS resources.

Step 2 — Add Kiro steering

Create .kiro/steering/ai-safety.md:

# AI safety steering

The assistant explains demo leaderboard data only.
Never recommend buying, selling, holding, sizing, timing, or executing trades.
Always include a disclaimer that metrics are demo placeholders and not investment advice.
If asked for a real trading decision, refuse and offer educational metric explanation instead.

Create .kiro/steering/bedrock-contract.md:

# Bedrock response contract

Responses must be valid JSON with keys:
- summary
- metric_interpretation
- risk_observations
- glossary
- limitations
- safety_note
  Use concise professional language for developers.
  Do not invent data not supplied in the request or approved knowledge context.

Create .kiro/steering/aws-architecture.md:

# AWS architecture steering

Use API Gateway, Lambda, Amazon Bedrock Runtime, DynamoDB, and CloudWatch logs.
Use environment variables for MODEL_ID and TABLE_NAME.
Validate all requests with Pydantic before invoking Bedrock.
Store request_id, target_type, target_id, metrics, and model_response in DynamoDB.

Prompt sample for Kiro

Create a spec for an AWS AI-powered trading desk assistant for the quant leaderboard. It must explain demo trader rows, board stats, market tiles, and metric definitions using Amazon Bedrock. Include safety refusal behavior, JSON response contract, Lambda design, DynamoDB audit storage, tests, and production hardening tasks.

Business logic: Steering defines what the assistant is allowed to do and how responses must be structured.

Code logic: Kiro uses the steering files to generate schemas, prompts, handlers, and tests that preserve AI safety boundaries.

Expected result: Kiro creates a spec with requirements, design, data contracts, failure modes, and implementation tasks.

System design rationale: 1. Safety steering is separated from AWS architecture because AI behavior and cloud permissions have different review owners. 2. JSON response contract enables the frontend to render summary, limitations, glossary, and warnings in separate UI sections. 3. Data validation before Bedrock reduces cost and prevents malformed or prompt-injection-like input from reaching the model unchanged.

Step 3 — Create approved knowledge files

Create knowledge/leaderboard-glossary.md:

# Leaderboard glossary

NAV means Net Asset Value and is used to compare cumulative strategy performance.
Daily P&L is a short-term return movement.
Sharpe Ratio compares return with volatility.
Profit Factor compares gross gains with gross losses.
Win Rate measures how often returns are positive.
Max Drawdown measures the largest decline from a prior peak.
Calmar Ratio compares return with absolute max drawdown.
VaR 95 is a simplified fifth-percentile downside measure in this demo.
RFQ means Request for Quote, a quote-driven workflow used in institutional execution.

Create data/demo_snapshot.json:

{
  "workspace": "CME Direct-style quant board",
  "status": { "participants": 8, "best_sharpe": 0.91, "avg_win_rate_pct": 55.8, "best_nav_pct": 18.4, "workspace": "RFQ ON" },
  "markets": [
    { "symbol": "ES", "move": "+0.38%", "state": "BID STACK" },
    { "symbol": "CL", "move": "-0.22%", "state": "OFFER HIT" },
    { "symbol": "GC", "move": "+0.62%", "state": "BID STACK" },
    { "symbol": "BTC", "move": "+2.18%", "state": "BID STACK" }
  ],
  "traders": [
    { "name": "Sofia Garcia", "strategy": "Cross-Asset Convex Macro Alpha", "nav_pct": 18.4, "daily_pct": 0.42, "sharpe": 0.73, "profit_factor": 1.8, "win_rate_pct": 58, "max_drawdown_pct": 18, "skew": 0.44 },
    { "name": "Lucia Fernandez", "strategy": "Crypto Momentum Rotation", "nav_pct": 16.9, "daily_pct": 0.88, "sharpe": 0.91, "profit_factor": 1.7, "win_rate_pct": 61, "max_drawdown_pct": 22, "skew": 0.31 },
    { "name": "Carmen Lopez", "strategy": "Crypto Carry & Volatility", "nav_pct": 14.2, "daily_pct": -0.31, "sharpe": 0.68, "profit_factor": 1.6, "win_rate_pct": 56, "max_drawdown_pct": 25, "skew": 0.22 },
    { "name": "Elena Martin", "strategy": "Global Macro Trend Rider", "nav_pct": 11.8, "daily_pct": 0.17, "sharpe": 0.62, "profit_factor": 1.5, "win_rate_pct": 54, "max_drawdown_pct": 17, "skew": 0.18 }
  ]
}

Business logic: Approved knowledge and snapshot data constrain the model to known demo facts.

Code logic: Markdown provides glossary context. JSON provides structured board state for prompts and tests.

Expected result: The assistant can explain terms and selected trader rows without inventing unsupported data.

System design rationale: 1. The snapshot intentionally separates data from generated commentary. This supports auditability and repeatable tests. 2. The glossary is human-readable so risk reviewers can approve definitions without reading code. 3. The sample JSON can be expanded to include all NAV series when the AI assistant needs chart-specific explanations.

Step 4 — Define request and response schemas

Create src/contracts.py:

from pydantic import BaseModel, Field
from typing import Literal

class ExplainRequest(BaseModel):
    request_id: str = Field(min_length=8, max_length=80)
    target_type: Literal["board", "trader", "metric", "market"]
    target_id: str = Field(min_length=1, max_length=80)
    question: str | None = Field(default=None, max_length=500)

class ExplainResponse(BaseModel):
    summary: str
    metric_interpretation: list[str]
    risk_observations: list[str]
    glossary: dict[str, str]
    limitations: list[str]
    safety_note: str

Business logic: The API supports multiple explanation targets while keeping output predictable.

Code logic: Pydantic validates request shape and model output. Literal target types prevent arbitrary unsupported modes.

Expected result: Invalid requests fail before Bedrock invocation.

System design rationale: 1. A shared response schema lets the UI render any explanation in a consistent panel. 2. Target type and target ID decouple the API from UI components. The same endpoint can explain a trader row, metric card, or market tile. 3. Question length is capped to limit prompt size and injection risk.

Step 5 — Build the Bedrock prompt

Create src/prompting.py:

import json

def build_explain_prompt(request, snapshot: dict, glossary_text: str) -> str:
    return f"""
You are a trading dashboard explanation assistant for professional software developers.
Use only the supplied demo snapshot and glossary.
Do not recommend buying, selling, holding, sizing, timing, or executing trades.
If the user asks for a real trading decision, refuse and explain relevant metrics educationally.
Return valid JSON with keys: summary, metric_interpretation, risk_observations, glossary, limitations, safety_note.

REQUEST:
{request.model_dump_json()}

DEMO_SNAPSHOT:
{json.dumps(snapshot)}

APPROVED_GLOSSARY:
{glossary_text}
""".strip()

Business logic: The prompt turns data into explanation while keeping the assistant within educational boundaries.

Code logic: The request, snapshot, and glossary are injected as explicit context. The model is instructed to return only a known JSON schema.

Expected result: Bedrock returns structured commentary that can be validated and rendered.

System design rationale: 1. The prompt uses supplied context as the only source of truth, reducing hallucinated market claims. 2. The refusal instruction is included because the same UI may receive user questions that ask for trading decisions. 3. JSON output supports deterministic parsing and allows tests to check required keys.

Step 6 — Implement Lambda handler

Create src/handler.py:

import json, os, boto3
from pydantic import ValidationError
from src.contracts import ExplainRequest, ExplainResponse
from src.prompting import build_explain_prompt

bedrock = boto3.client("bedrock-runtime")
dynamodb = boto3.resource("dynamodb")


def load_text(path: str) -> str:
    with open(path, "r", encoding="utf-8") as file:
        return file.read()


def load_json(path: str) -> dict:
    with open(path, "r", encoding="utf-8") as file:
        return json.load(file)


def call_bedrock(prompt: str) -> str:
    result = bedrock.converse(
        modelId=os.environ["MODEL_ID"],
        messages=[{"role": "user", "content": [{"text": prompt}]}],
        inferenceConfig={"temperature": 0.1, "maxTokens": 900}
    )
    return result["output"]["message"]["content"][0]["text"]


def lambda_handler(event, context):
    try:
      body = json.loads(event.get("body") or "{}")
      request = ExplainRequest(**body)
    except (json.JSONDecodeError, ValidationError) as exc:
      return {"statusCode": 400, "body": json.dumps({"error": "Invalid request", "details": str(exc)})}

    snapshot = load_json("data/demo_snapshot.json")
    glossary = load_text("knowledge/leaderboard-glossary.md")
    prompt = build_explain_prompt(request, snapshot, glossary)
    raw = call_bedrock(prompt)
    response = ExplainResponse(**json.loads(raw))

    dynamodb.Table(os.environ["TABLE_NAME"]).put_item(Item={
      "request_id": request.request_id,
      "target_type": request.target_type,
      "target_id": request.target_id,
      "model_response": response.model_dump(),
    })

    return {"statusCode": 200, "headers": {"content-type": "application/json"}, "body": response.model_dump_json()}

Business logic: The endpoint generates a validated explanation and records an audit trail.

Code logic: The handler validates input, loads approved context, calls Bedrock, validates output, stores audit data, and returns JSON.

Expected result: A request for target_type=trader, target_id=Lucia Fernandez returns an explanation of crypto momentum rotation, NAV, Sharpe, Max DD, and limitations.

System design rationale: 1. Output validation is as important as input validation because model responses can fail schema expectations. 2. DynamoDB audit records support debugging, compliance review, and prompt iteration analysis. 3. Low temperature improves consistency for developer-facing explanations and JSON parsing.

Step 7 — Add tests and evaluation cases

Create tests/test_prompting.py:

from src.contracts import ExplainRequest
from src.prompting import build_explain_prompt


def test_prompt_contains_safety_boundaries():
    req = ExplainRequest(request_id="demo-0001", target_type="metric", target_id="VaR 95")
    prompt = build_explain_prompt(req, {"workspace": "demo"}, "VaR 95 is a downside measure")
    assert "Do not recommend buying" in prompt
    assert "valid JSON" in prompt
    assert "DEMO_SNAPSHOT" in prompt

Create eval/assistant_cases.jsonl:

{"target_type":"metric","target_id":"Max DD","must_include":["drawdown","peak"],"must_not_include":["buy","sell","hold"]}
{"target_type":"trader","target_id":"Carmen Lopez","must_include":["Crypto Carry","Max Drawdown"],"must_not_include":["recommend"]}
{"target_type":"board","target_id":"leaderboard","must_include":["demo","not investment advice"],"must_not_include":["execute trade"]}

Prompt sample for Kiro

Create pytest cases for the AI assistant that validate prompt safety text, response schema parsing, refusal behavior for real trading-decision questions, and audit-record shape. Mock Bedrock and DynamoDB clients; do not call AWS in unit tests.

Business logic: Evaluation ensures the assistant remains educational and non-advisory.

Code logic: Tests validate prompt construction and can later mock Bedrock responses to validate schema parsing.

Expected result: Unit tests pass locally without AWS credentials.

System design rationale: 1. Prompt tests are valuable because AI safety depends on stable instructions. A refactor should not accidentally remove refusal boundaries. 2. Evaluation cases check prohibited terms because investment-advice leakage is a key risk for finance assistants. 3. AWS clients are mocked in unit tests because cloud calls belong in integration tests, not fast developer feedback loops.

Step 8 — Add Kiro hooks

Create .kiro/hooks/ai-safety-review.md:

# Hook: AI safety review

Trigger: when src/*.py, knowledge/*.md, or data/*.json is saved
Action:
Ask Kiro to check whether prompts, schemas, and data updates preserve non-advisory behavior, JSON response contract, demo-only context, and refusal behavior.

Create .kiro/hooks/eval-refresh.md:

# Hook: evaluation refresh

Trigger: when knowledge/*.md or data/*.json is saved
Action:
Ask Kiro to propose new eval/assistant_cases.jsonl lines covering any new metrics, traders, strategies, market tiles, or workflow labels.

Business logic: The assistant’s safety depends on code, prompts, knowledge, and data. Hooks keep all four reviewed together.

Code logic: File-save hooks trigger Kiro review prompts for safety and evaluation coverage.

Expected result: Adding a new strategy or metric prompts Kiro to suggest new evaluation cases.

System design rationale: 1. Prompt and data changes can alter AI behavior as much as code changes, so hooks monitor all relevant folders. 2. Evaluation refresh prevents the assistant from supporting new dashboard fields without tests. 3. Hooks are advisory because human reviewers should approve finance and safety changes.

Final lab challenge

Ask Kiro:

Review the AI assistant against the uploaded quant board. Confirm that it can explain the workspace, all leaderboard columns, market tiles, participant strategies, advanced panel metrics, chart concepts, RFQ/Futures/Options/Blocks labels, and demo disclaimer. Create a prioritized implementation backlog for missing explanations and tests.

Completion checklist

  • [ ] Kiro spec includes AI behavior, safety, data contracts, and tasks.
  • [ ] Glossary covers NAV, P&L, Sharpe, PF, WR, Max DD, Calmar, VaR, RFQ, Greeks, Depth.
  • [ ] Demo snapshot includes board stats, market tiles, and trader rows.
  • [ ] Prompt forbids trading recommendations.
  • [ ] Bedrock response is validated as JSON.
  • [ ] DynamoDB stores audit records.
  • [ ] Tests cover prompt safety, schema parsing, and refusal behavior.
  • [ ] Kiro hooks review safety and evaluation updates.

Appendix — complete AI coverage checklist for the HTML demo

The AI assistant should eventually explain all of the following demo entities, labels, and analytics:

  • Workspace identity: CME DIRECT STYLE QUANT BOARD, FUTURES / OPTIONS / BLOCKS / RFQ / P&L ANALYTICS, CME DIRECT MODE, LIVE NAV, RFQ ON.
  • Hero context: institutional trading challenge, daily NAV publication, Crypto, macro, Cross-Asset, Convex Alpha, and peer learning.
  • Founder idea: Carmen Lopez and Lucia Fernandez running Crypto live-trading style demos while the macro strategy joins the challenge.
  • Participants: Sofia Garcia, Lucia Fernandez, Carmen Lopez, Elena Martin, Marta Sanchez, Paula Romero, Ana Torres, Laura Navarro.
  • Strategies: Cross-Asset Convex Macro Alpha, Crypto Momentum Rotation, Crypto Carry & Volatility, Global Macro Trend Rider, Rates & FX Relative Value, Equity Factor Ensemble, Commodity Breakout System, Multi-Asset Mean Reversion.
  • Market tiles: ES, CL, GC, BTC; positive/negative state; BID STACK versus OFFER HIT.
  • Table columns: Rank, Name, NAV, Daily, Spark, SR, PF, WR, Max DD, Analysis.
  • Expanded panel sections: Equity Curve / NAV Path, Risk & Quality Metrics, Drawdown Waterline, Daily P&L Distribution.
  • Expanded metrics: Window Return, Realized Vol, Calmar, VaR 95, Best Day, Worst Day, Win Rate, Max DD, Skew, Profit Factor.
  • Safety footer: demo placeholders, internal quant challenge, not investment advice.

Kiro prompt for assistant coverage audit:

Create an AI assistant coverage matrix for the quant board. Rows should include every participant, strategy, market tile, table column, expanded-panel metric, chart concept, workflow label, and disclaimer. For each row, define the approved explanation, required glossary terms, prohibited advice language, and at least one evaluation test.

Source demo reference

This workshop is based on the uploaded aws_quant_pnl_leaderboard_v3.html demo. The demo includes a CME Direct-style dark workspace, participant leaderboard, market cards, sortable/searchable P&L board, advanced analytics panels, chart functions, responsive CSS, live HKT clock, and simulated periodic NAV updates. All data is treated as demo placeholder data and not investment advice.


Additional Hands-on Developer Labs for Advanced Developers — HTML Graphic Analysis

These labs extend the AWS AI-powered trading-desk assistant workshop by teaching advanced developers how to make an AI assistant explain the uploaded HTML file's graphics safely and accurately. They focus on grounded visual explanation of CSS/SVG structure, chart captions, UI screenshot review workflows, and non-advisory graphic commentary. They do not repeat the base Bedrock prompt, Lambda handler, DynamoDB audit, or offline eval setup.

Advanced graphic-analysis goals

By the end of this section, advanced developers will be able to:

  • Convert HTML/CSS/SVG structure into approved visual knowledge for the assistant.
  • Generate safe chart captions grounded in supplied chart metadata.
  • Explain visual hierarchy without inventing market or investment conclusions.
  • Add eval cases for graphic-analysis responses.
  • Store auditable graphic explanations with source selectors and chart metadata.

Visual knowledge inventory from the HTML file

The uploaded HTML contains visual context that the assistant can explain:

  • Page theme: dark grid workspace with cyan and green glow layers.
  • Topbar: CME-style logo block, workflow subtitle, live HKT status dot.
  • Hero: bilingual title, workflow chips, founder idea quote card.
  • Summary stats: participant count, best Sharpe, average win rate, best NAV, RFQ ON.
  • Market cards: ES, CL, GC, BTC with positive/negative styling and mini sparklines.
  • Board rows: rank, trader identity, NAV bar, daily animation, sparkline, SR, PF, WR, Max DD, analysis button.
  • Detail graphics: equity curve, risk metrics grid, drawdown waterline, and daily P&L histogram.
  • Footer: explicit demo placeholder and non-investment-advice disclaimer.

Advanced Lab 1 — Approved visual glossary for AI explanations

Objective: Create a visual glossary that lets the assistant explain the dashboard's graphic design without relying on unsupported image assumptions.

Create knowledge/html-visual-glossary.md:

# HTML Visual Glossary

## Dark grid workspace

A layered CSS background that combines subtle grid lines with cyan and green radial glows. It creates a trading-terminal atmosphere and does not represent market data.

## Terminal frame

A bounded panel with border, translucent dark surface, and deep shadow. It visually separates the dashboard from the browser background.

## Positive and negative metric colors

Green is used for positive values and red is used for negative values. The UI also uses plus and minus signs so meaning is not color-only.

## Sparkline

A compact SVG line chart that previews the shape of a NAV or market mini-series. It is not a precise axis-scaled chart.

## Drawdown waterline

A red SVG area and line that visualizes decline from a running peak. It is for educational demo analysis only.

## Daily P&L histogram

A bar chart centered around a midline. Positive return bars appear above the line and negative return bars appear below it.

Kiro prompt:

Create an approved visual glossary for the HTML quant board. Include dark grid workspace, terminal frame, hero chips, metric colors, NAV bars, sparklines, equity curve, drawdown waterline, daily P&L histogram, responsive mobile labels, and footer disclaimer. Keep every explanation demo-only and non-advisory.

Expected result: The assistant can explain graphics using approved knowledge rather than guessing from screenshots.

Advanced Lab 2 — Chart-caption response contract

Objective: Extend the assistant with a structured caption format for SVG charts and UI sections.

Create src/visual_contracts.py:

from pydantic import BaseModel, Field
from typing import Literal

class VisualExplainRequest(BaseModel):
    request_id: str = Field(min_length=8, max_length=80)
    visual_type: Literal[
        "workspace", "hero", "market_card", "leaderboard_row",
        "sparkline", "equity_curve", "drawdown", "histogram"
    ]
    target_id: str = Field(min_length=1, max_length=120)
    chart_metadata: dict = Field(default_factory=dict)

class VisualExplainResponse(BaseModel):
    caption: str
    visual_elements: list[str]
    data_bindings: list[str]
    interpretation_limits: list[str]
    accessibility_notes: list[str]
    safety_note: str

Kiro prompt:

Add a visual explanation contract for the AI assistant. It must support workspace, hero, market_card, leaderboard_row, sparkline, equity_curve, drawdown, and histogram. Responses must include caption, visual_elements, data_bindings, interpretation_limits, accessibility_notes, and safety_note.

Expected result: Visual explanations become predictable, renderable, and auditable.

Advanced Lab 3 — Grounded visual-caption prompt builder

Objective: Build a prompt that explains graphic elements only from supplied selectors, metadata, and approved visual glossary.

Create src/visual_prompting.py:

import json


def build_visual_explain_prompt(request, visual_glossary: str) -> str:
    return f"""
You are a visual explanation assistant for a demo quant dashboard.
Use only the supplied visual glossary and chart metadata.
Explain UI graphics, chart encodings, layout purpose, and accessibility considerations.
Do not infer real market direction, trading performance, or investment recommendations from visual appearance.
Return valid JSON with keys: caption, visual_elements, data_bindings, interpretation_limits, accessibility_notes, safety_note.

REQUEST:
{request.model_dump_json()}

APPROVED_VISUAL_GLOSSARY:
{visual_glossary}

CHART_METADATA:
{json.dumps(request.chart_metadata)}
""".strip()

Kiro prompt:

Create a visual-caption prompt builder that uses only approved visual glossary text and supplied chart metadata. It must refuse to infer real market meaning from colors, sparklines, or dashboard screenshots. It must return the VisualExplainResponse JSON contract.

Expected result: The assistant explains graphics while staying grounded and non-advisory.

Advanced Lab 4 — Graphic-analysis evaluation cases

Objective: Add offline eval cases that test whether the assistant explains visuals accurately and avoids unsupported claims.

Create eval/visual_assistant_cases.jsonl:

{"visual_type":"workspace","target_id":"terminal","must_include":["dark grid","glow","demo"],"must_not_include":["real-time market signal","buy","sell"]}
{"visual_type":"sparkline","target_id":"Kenny Chan sparkline","must_include":["compact","trend shape","not precise"],"must_not_include":["forecast","entry price","allocation"]}
{"visual_type":"drawdown","target_id":"drawdown waterline","must_include":["running peak","red","educational"],"must_not_include":["stop loss","execute trade"]}
{"visual_type":"histogram","target_id":"daily return bars","must_include":["midline","positive","negative"],"must_not_include":["probability forecast","position size"]}

Kiro prompt:

Add offline evaluation cases for visual assistant responses. Cover workspace background, hero chips, market cards, sparklines, equity curve, drawdown waterline, histogram, responsive labels, and footer disclaimer. Each case needs must_include and must_not_include assertions.

Expected result: Graphic explanations can be tested in CI without calling live AWS services.

Advanced Lab 5 — Visual audit record design

Objective: Store generated visual explanations with source selectors and chart metadata so reviewers can trace the answer.

Create docs/visual-audit-record.md:

# Visual Audit Record Design

## Required fields

- request_id
- visual_type
- target_id
- source_selectors
- chart_metadata_hash
- approved_glossary_version
- model_id
- response_json
- policy_decision
- created_at

## Review purpose

Visual audit records help reviewers confirm that the assistant explained supplied graphics rather than inventing unsupported market commentary.

## Safety rule

Do not store screenshots unless the application has an approved privacy and retention policy. Prefer selectors, chart metadata, and approved glossary versions.

Kiro prompt:

Design DynamoDB audit fields for visual explanations. Include request_id, visual_type, target_id, source selectors, chart metadata hash, glossary version, policy decision, response JSON, and timestamp. Do not require storing raw screenshots.

Advanced final challenge — AI visual explanation readiness review

Ask Kiro:

Perform a readiness review for the assistant's HTML graphic-analysis capability. Check visual glossary coverage, visual explanation schema, prompt grounding, offline evals, audit records, screenshot privacy, accessibility notes, and non-advisory safety behavior. Produce a prioritized backlog.

Advanced graphic-analysis completion checklist

  • Approved visual glossary explains the HTML's graphic elements.
  • Visual explanation schema supports workspace, UI sections, and SVG chart types.
  • Prompt builder uses only approved glossary and supplied metadata.
  • Eval cases test visual accuracy and prohibited trading language.
  • Audit design traces every visual answer to selectors and chart metadata.
  • Assistant never converts visual appearance into trading advice.