File size: 7,511 Bytes
12a6efa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1766315
12a6efa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/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()