Skip to content

Add Hedging Functionality to the portfolio management tool#163

Open
manu49 wants to merge 4 commits into
oracle-devrel:mainfrom
manu49:main
Open

Add Hedging Functionality to the portfolio management tool#163
manu49 wants to merge 4 commits into
oracle-devrel:mainfrom
manu49:main

Conversation

@manu49

@manu49 manu49 commented May 29, 2026

Copy link
Copy Markdown

Summary

This PR adds a new suggest_portfolio_hedge agent tool to the Agentic Financial Service Assistant (AFSA) demo app. The tool analyses a portfolio's risk factors and recommends specific hedging instruments, giving financial advisors an AI-assisted starting point for downside protection conversations.

It also establishes the project's first testing infrastructure — from scratch — covering the full stack from the backend recommendation engine through to the React frontend component rendering.


What's New

New Agent Tool: suggest_portfolio_hedge

Users can now ask the agent questions like:

  • "What hedges would you recommend for ACC-003?"
  • "How can I protect this portfolio against sector concentration risk?"
  • "Suggest currency hedges for ACC-010"

How it works:

A single Oracle SQL query (Relational + JSON + window-function analytics) fetches the full risk picture for an account — sector breakdown, regional exposure, asset class distribution, high-risk positions (rating ≥ 7), and ESG mandate from JSON metadata — in one statement. A pure-Python recommendation engine then maps detected risk factors to a curated catalogue of hedging instruments.

Risk dimensions covered (controlled by the optional risk_focus parameter):

Dimension Trigger Example instruments
market Equity > 60% of portfolio, or high-risk positions present SH (inverse S&P500), GLD, TLT
sector Any sector > 30% concentration QQQ puts, sector inverse ETFs, VXUS
regional Any region > 50% concentration EFA, ACWX, EPV
currency > 25% international exposure UUP, FXE
all All of the above (default) Combined set, de-duplicated

ESG-aware: accounts with an ESG mandate have leveraged and high-risk instruments automatically filtered out of recommendations.

Both architecture modes supported: Oracle converged mode (tools.py) and PostgreSQL sprawl mode (sprawl_tools.py).


Test Suite (first tests in this project)

Sets up testing infrastructure from scratch and adds 97 tests across the full stack.

Backend — pytest (backend/tests/)

File Tests Coverage
test_hedge_recommendations.py 39 Pure-unit tests for _build_hedge_recommendations: output structure, all four risk dimensions, ESG filtering, risk_focus scoping, edge cases (empty rows, None PCTs, malformed JSON)
test_suggest_portfolio_hedge_integration.py 8 Full _suggest_portfolio_hedge pipeline with a mock execute_query — JSON output, error messages, default args, query logger invocation, SQL param binding
test_tool_schema.py 11 Schema registration in TOOL_SCHEMAS and PRELOADED_TOOLS, required/optional params, enum values, dispatcher routing

Run with:

cd backend
pip install -r requirements.txt
pytest tests/ -v

Frontend — Vitest + @testing-library/react (frontend/src/test/)

File Tests Coverage
ToolCallBubble.test.jsx 22 Running/success/error states, expand/collapse toggle, pretty-printed JSON output, args rendering edge cases
chatReducer.test.js 17 Full WebSocket lifecycle: ADD_TOOL_CALL_STARTUPDATE_TOOL_CALLAGENT_COMPLETE, tool calls attached to assistant messages, isLoading cleared, multi-tool isolation

Run with:

cd frontend
npm install
npm test

Files Changed

backend/agent/tools.py              — tool schema, Oracle implementation, hedge catalogue + engine
backend/agent/sprawl_tools.py       — PostgreSQL sprawl-mode implementation
backend/tests/__init__.py
backend/tests/conftest.py           — shared pytest fixtures (4 portfolio scenarios)
backend/tests/test_hedge_recommendations.py
backend/tests/test_suggest_portfolio_hedge_integration.py
backend/tests/test_tool_schema.py
backend/pytest.ini
backend/requirements.txt            — added pytest, pytest-mock
frontend/vite.config.js             — vitest config (jsdom, coverage)
frontend/package.json               — test/test:watch/test:coverage scripts
frontend/src/test/setup.js
frontend/src/test/hedgeFixtures.js  — shared ToolCall fixtures
frontend/src/test/ToolCallBubble.test.jsx
frontend/src/test/chatReducer.test.js

Checklist

  • Code formatted with Ruff (Python) and Prettier (JS/JSX) — passes ruff check and prettier --check
  • All 97 tests pass (58 backend, 39 frontend)
  • Both Oracle converged and PostgreSQL sprawl modes implemented
  • ESG mandate filtering applied to recommendations
  • Output includes a disclaimer that recommendations are algorithmic and require advisor review
  • Oracle Contributor Agreement signed (required before merge — see OCA)

claude and others added 4 commits May 28, 2026 22:21
Adds a new agent tool that analyses a portfolio's risk factors — sector
concentration, regional exposure, asset class distribution, and high-risk
positions — then maps them to specific hedging instruments (inverse ETFs,
commodities, bonds, defensive equities, options strategies).

Changes:
- tools.py: tool schema, Oracle SQL implementation (_suggest_portfolio_hedge),
  pure-Python hedge catalogue + recommendation engine (_build_hedge_recommendations),
  dispatcher routing for both converged and sprawl modes
- sprawl_tools.py: PostgreSQL equivalent (suggest_portfolio_hedge_sprawl)

Supports risk_focus parameter: market | sector | regional | currency | all

https://claude.ai/code/session_014SVg1DDKFLVDTfAfQ3mGuR
Sets up testing infrastructure from scratch (no prior tests existed) and
adds 97 tests covering the feature end-to-end.

Backend (pytest):
- pytest.ini + pytest/pytest-mock added to requirements.txt
- tests/conftest.py: shared row fixtures (tech-heavy, ESG, balanced,
  intl-heavy portfolios) used across all backend test files
- test_hedge_recommendations.py (39 tests): pure-unit tests for
  _build_hedge_recommendations — output structure, market/sector/
  regional/currency risk detection, ESG filtering, risk_focus scoping,
  edge cases (empty rows, None PCTs, malformed JSON)
- test_suggest_portfolio_hedge_integration.py (8 tests): integration
  tests for _suggest_portfolio_hedge with a mock execute_query — verifies
  JSON output, error messages, default args, query_logger invocation,
  account_id SQL param binding
- test_tool_schema.py (11 tests): schema registration, PRELOADED_TOOLS
  inclusion, required/optional params, enum values, dispatcher routing

Frontend (vitest + @testing-library/react):
- vite.config.js: vitest config (jsdom environment, coverage)
- package.json: test / test:watch / test:coverage scripts
- src/test/setup.js: @testing-library/jest-dom matchers
- src/test/hedgeFixtures.js: shared ToolCall fixtures (success/running/error)
- ToolCallBubble.test.jsx (22 tests): running spinner, success checkmark,
  error icon, elapsed time, expand/collapse toggle, pretty-printed JSON
  output, args rendering edge cases (null/empty args)
- chatReducer.test.js (17 tests): ADD_TOOL_CALL_START → UPDATE_TOOL_CALL
  → AGENT_COMPLETE lifecycle — status transitions, output attachment to
  assistant messages, isLoading, multi-tool-call isolation

All 97 tests pass (58 backend, 39 frontend).

https://claude.ai/code/session_014SVg1DDKFLVDTfAfQ3mGuR
Runs Ruff (linter + formatter) on all changed Python files and Prettier
on all changed JS/JSX files to comply with the repository's pre-commit
hook standards defined in .pre-commit-config.yaml.

Changes: import ordering, unused import removal, line-length normalisation
in tests/conftest.py, test_hedge_recommendations.py, test_tool_schema.py,
test_suggest_portfolio_hedge_integration.py, tools.py, sprawl_tools.py,
chatReducer.test.js, and hedgeFixtures.js. All 97 tests still pass.

https://claude.ai/code/session_014SVg1DDKFLVDTfAfQ3mGuR
Add portfolio hedge recommendation tool with comprehensive risk analysis
@oracle-contributor-agreement

oracle-contributor-agreement Bot commented May 29, 2026

Copy link
Copy Markdown

Thank you for your pull request and welcome to our community! To contribute, please sign the Oracle Contributor Agreement (OCA).
The following contributors of this PR have not signed the OCA:

To sign the OCA, please create an Oracle account and sign the OCA in Oracle's Contributor Agreement Application.

When signing the OCA, please provide your GitHub username. After signing the OCA and getting an OCA approval from Oracle, this PR will be automatically updated.

If you are an Oracle employee, please make sure that you are a member of the main Oracle GitHub organization, and your membership in this organization is public.

@oracle-contributor-agreement oracle-contributor-agreement Bot added the OCA Required At least one contributor does not have an approved Oracle Contributor Agreement. label May 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

OCA Required At least one contributor does not have an approved Oracle Contributor Agreement.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants