finsight / src /agent.py
margotbtn's picture
Refinement
1766315
Raw History Blame Contribute Delete
7.51 kB
#!/usr/bin/env python3
"""
Market Intelligence Agent
Answers investment questions by orchestrating two MCP servers:
- mcp_sql/server.py → structured price, indicator, fundamental data (DuckDB)
- mcp_rag/server.py → semantic news search (ChromaDB)
Usage:
python agent.py "Is NVIDIA a good buy right now?"
python agent.py # interactive mode
"""
import asyncio
import json
import os
import sys
from collections.abc import AsyncGenerator
import anthropic
from dotenv import load_dotenv
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
load_dotenv()
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
SYSTEM_PROMPT = """You are a financial market intelligence analyst with access to real market data.
You have two data sources:
1. **SQL database** — stock prices (OHLCV), technical indicators (RSI-14, MACD, SMA-20/50/200), and fundamentals (P/E, EPS, market cap, sector) for 25 major tickers.
2. **News database** — recent financial news articles indexed for semantic search.
When answering an investment question, always follow this process:
1. Call `get_indicators` for each relevant ticker to retrieve technicals and fundamentals.
2. Call `search_news` with a descriptive query and the ticker to surface recent events and sentiment.
3. If the question compares multiple stocks, call `compare_stocks` as well.
4. Synthesise all signals into a structured answer.
Structure your response with these sections:
- **Technical picture**: RSI level, MACD trend, price vs key SMAs, golden cross/death cross
- **Fundamental context**: valuation (P/E), market cap, sector, EPS
- **News & sentiment**: key recent headlines and what they imply
- **Overall assessment**: balanced conclusion based on the data
Always ground your claims in specific numbers from the tools. Your output is rendered as markdown: escape every dollar sign as \\$ to prevent LaTeX interpretation (e.g. write \\$150.00 not $150.00). End every response with:
"*Disclaimer: This is a data-driven analysis tool, not licensed financial advice. Always do your own research before investing.*"
"""
# ---------------------------------------------------------------------------
# Core: async generator — usable from both CLI and Streamlit
# ---------------------------------------------------------------------------
async def run_agent_stream(
question: str, api_key: str
) -> AsyncGenerator[dict, None]:
"""
Async generator that yields typed events:
{"type": "log", "text": "..."} — tool call activity
{"type": "result", "text": "..."} — final markdown answer
"""
sql_params = StdioServerParameters(
command=sys.executable,
args=[os.path.join(ROOT_DIR, "mcp_sql", "server.py")],
)
rag_params = StdioServerParameters(
command=sys.executable,
args=[os.path.join(ROOT_DIR, "mcp_rag", "server.py")],
)
async with stdio_client(sql_params) as (sql_r, sql_w):
async with ClientSession(sql_r, sql_w) as sql_session:
await sql_session.initialize()
async with stdio_client(rag_params) as (rag_r, rag_w):
async with ClientSession(rag_r, rag_w) as rag_session:
await rag_session.initialize()
sql_tools = (await sql_session.list_tools()).tools
rag_tools = (await rag_session.list_tools()).tools
tool_sessions: dict[str, ClientSession] = {
t.name: sql_session for t in sql_tools
} | {
t.name: rag_session for t in rag_tools
}
anthropic_tools = [
{
"name": t.name,
"description": t.description or "",
"input_schema": t.inputSchema,
}
for t in (*sql_tools, *rag_tools)
]
client = anthropic.Anthropic(api_key=api_key)
messages: list[dict] = [{"role": "user", "content": question}]
yield {"type": "log", "text": "Analysing..."}
while True:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=4096,
system=SYSTEM_PROMPT,
tools=anthropic_tools,
messages=messages,
)
tool_uses = [b for b in response.content if b.type == "tool_use"]
if tool_uses:
names = ", ".join(b.name for b in tool_uses)
yield {"type": "log", "text": f"Tools: {names}"}
tool_results = []
for block in tool_uses:
yield {"type": "log", "text": f" -> {block.name}({json.dumps(block.input)})"}
session = tool_sessions.get(block.name)
if session is None:
result_text = json.dumps({"error": f"Unknown tool: {block.name}"})
else:
result = await session.call_tool(block.name, block.input)
result_text = result.content[0].text if result.content else ""
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result_text,
})
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason == "tool_use":
messages.append({"role": "user", "content": tool_results})
continue
# Final answer
answer = "\n".join(
block.text for block in response.content if hasattr(block, "text")
)
yield {"type": "result", "text": answer}
break
# ---------------------------------------------------------------------------
# CLI shim — wraps the generator, prints to stdout
# ---------------------------------------------------------------------------
async def run_agent(question: str) -> None:
api_key = os.environ.get("ANTHROPIC_API_KEY", "")
async for event in run_agent_stream(question, api_key):
if event["type"] == "log":
print(event["text"])
elif event["type"] == "result":
print("\n" + "=" * 70)
print(event["text"])
print("=" * 70 + "\n")
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def main() -> None:
if len(sys.argv) > 1:
question = " ".join(sys.argv[1:])
else:
print("Market Intelligence Agent")
print("-" * 40)
question = input("Question: ").strip()
if not question:
print("No question provided.")
sys.exit(1)
asyncio.run(run_agent(question))
if __name__ == "__main__":
main()