Skip to main content
Glama
financial-analyst-mcp

financial-analyst-mcp

Финансовый аналитик на базе MCP

Локальный AI-финансовый аналитик, построенный вокруг настоящего MCP-сервера (Model Context Protocol). Вместо одного чат-бота, который пытается угадать движения акций, работают два агента:

  • Агент-валидатор — проверяет данные, полученные из интернета (Yahoo Finance, новостные API), на пропуски, некорректные значения или несоответствие тикеров до того, как что-либо попадёт в LLM.

  • Агент-аналитик — рассуждает над проверенными данными и результатами MCP-инструментов, чтобы составить структурированную сводку (тренд, скользящие средние, волатильность и релевантные новостные настроения).

Оба агента вызывают инструменты, предоставляемые кастомным MCP-сервером — это ядро проекта, а не просто связующий код LangChain.

Что я добавил помимо базовой версии из туториала

  • Разделение на двух агентов (Validator → Analyst) вместо одного агента, который делает всё

  • Настоящий MCP-сервер с тремя инструментами, включая валидацию как отдельный инструмент

  • Трассировка LangSmith на обоих агентах

  • Кэширующий слой Neon Postgres (позволяет не обращаться повторно к API с лимитами)

  • Небольшой набор eval-тестов с эталонными значениями, рассчитанными вручную

  • Развёрнутое веб-приложение (FastAPI на Render, статический фронтенд на Vercel)

Related MCP server: AlphaVantage MCP Server

Архитектура

User query (ticker + date range)
        │
        ▼
  Validator agent ──calls──▶ MCP server ──▶ fetch_price_data (Yahoo Finance)
        │                                 ▶ validate_data
        │  (retries once on bad data)
        ▼
  Analyst agent ──calls──▶ MCP server ──▶ analyze_chart (moving averages, volatility)
        │                                ▶ get_news_sentiment
        ▼
  Structured summary + chart data → FastAPI → frontend

Структура проекта

backend/
  mcp_server/          # the MCP server + its 3 tools (this is the centerpiece)
  agents/               # Validator agent, Analyst agent
  orchestration/         # LangGraph wiring: Validator -> Analyst
  db/                    # Neon Postgres cache + eval result storage
  evals/                 # hand-checked test cases + eval runner
  main.py                # FastAPI app, deployed on Render
frontend/
  index.html             # single-page UI, deployed on Vercel
  vercel.json
render.yaml               # Render deployment config for the backend
requirements.txt
.env.example

Настройка

  1. Клонирование и установка

    git clone <your-repo-url>
    cd financial-analyst-mcp
    python -m venv venv && source venv/bin/activate
    pip install -r requirements.txt
  2. Переменные окружения — скопируйте .env.example в .env и заполните:

    • GROQ_API_KEY — бесплатно, оплата не требуется (регистрация на console.groq.com); используется агентом-аналитиком и проверкой релевантности новостей

    • DATABASE_URL — строка подключения к вашей RDS Postgres

    • NEWSAPI_KEY — бесплатный тариф на newsapi.org (100 запросов в день, карта не требуется)

    • LANGCHAIN_API_KEY, LANGCHAIN_PROJECT — для трассировки LangSmith (необязательно, бесплатный уровень)

  3. Создание таблиц в базе данных

    python -m backend.db.database --init
  4. Запуск бэкенда локально

    uvicorn backend.main:app --reload --port 8000
  5. Запуск фронтенда локально — просто откройте frontend/index.html в браузере или раздайте его:

    cd frontend && python -m http.server 5500

    Обновите константу API_BASE_URL в верхней части index.html, чтобы она указывала на ваш бэкенд (http://localhost:8000 локально, ваш URL на Render после развёртывания).

  6. Запуск набора eval-тестов

    python -m backend.evals.run_evals

Развёртывание (бесплатный уровень AWS)

Всё ниже укладывается в 12-месячный бесплатный уровень AWS (при условии, что вы выбираете указанные размеры инстансов из бесплатного уровня). Здесь не нужно менять код — то же FastAPI-приложение и MCP-сервер работают как есть.

1. База данных → RDS (Postgres)

  1. AWS Console → RDS → Создать базу данных.

  2. Движок: PostgreSQL. Шаблоны: Бесплатный уровень.

  3. Класс инстанса: db.t3.micro (или db.t4g.micro — какой из них консоль предложит в качестве бесплатного уровня).

  4. Задайте мастер-имя пользователя и пароль, сохраните их.

  5. В разделе Connectivity выставьте Public access: Yes (это нужно, чтобы база была доступна с вашего EC2-инстанса и вашей собственной машины — для портфолио-проекта это нормально; позже можно ужесточить).

  6. Когда база запустится, скопируйте endpoint (выглядит как xxxx.rds.amazonaws.com) и соберите строку подключения:

    DATABASE_URL=postgresql://<username>:<password>@<endpoint>:5432/postgres
  7. В Security Group инстанса RDS добавьте входящее правило: PostgreSQL (порт 5432), источник = ваш IP (для локального тестирования) и позже — security group вашего EC2-инстанса.

2. Бэкенд → EC2

  1. AWS Console → EC2 → Запустить инстанс.

  2. AMI: Amazon Linux 2023 (или Ubuntu 22.04). Тип инстанса: t2.micro (подходит для бесплатного уровня).

  3. Создайте или скачайте пару ключей (файл .pem) — она нужна для подключения по SSH.

  4. Security group: разрешите входящий SSH (порт 22, ваш IP) и пользовательский TCP-порт 8000 отовсюду (0.0.0.0/0), чтобы фронтенд мог обращаться к API.

  5. Запустите его, затем подключитесь по SSH:

    ssh -i your-key.pem ec2-user@<instance-public-ip>
  6. На инстансе:

    git clone <your-repo-url> financial-analyst-mcp
    cd financial-analyst-mcp
    nano .env          # paste in GROQ_API_KEY (free, from console.groq.com), DATABASE_URL (from RDS), NEWSAPI_KEY, etc.
    bash aws/ec2-setup.sh

    Это установит Python, зависимости, создаст таблицы в базе данных и запустит бэкенд как службу systemd (financial-analyst), которая продолжит работать после вашего отключения и автоматически перезапустится при перезагрузке инстанса.

  7. Проверьте, что он работает: curl http://<instance-public-ip>:8000/health

3. Фронтенд → статический сайт на S3

  1. Обновите API_BASE_URL в верхней части frontend/index.html, указав http://<your-ec2-public-ip>:8000.

  2. С вашей собственной машины (с установленным AWS CLI и однократно выполненным aws configure с вашими учётными данными):

    BUCKET_NAME=your-unique-bucket-name bash aws/deploy-frontend-s3.sh
  3. Скрипт создаёт bucket, включает статический хостинг сайта и загружает index.html. В конце он выводит ваш рабочий URL (http://<bucket>.s3-website-<region>.amazonaws.com).

  4. Когда бы вы ни меняли фронтенд, просто запустите тот же скрипт заново, чтобы перезагрузить файлы.

Заметки

  • Публичный IP EC2 меняется при остановке/запуске инстанса (если не прикрепить Elastic IP — он тоже бесплатен, пока прикреплён к запущенному инстансу). Если IP изменился, обновите API_BASE_URL и запустите скрипт развёртывания S3 заново.

  • Чтобы расходы оставались нулевыми, придерживайтесь размеров бесплатного уровня t2.micro/db.t3.micro и помните, что бесплатный уровень AWS действует только первые 12 месяцев.

Будет ли это стоить денег на бесплатном уровне AWS?

Нет, если вы остаётесь в этих лимитах (всё это часть 12-месячного бесплатного уровня AWS для новых аккаунтов):

Сервис

Лимит бесплатного уровня

Использование в этом проекте

EC2 (t2.micro/t3.micro)

750 часов/месяц

1 инстанс работает 24/7 ≈ 730 часов — укладывается в лимит

RDS (db.t3.micro/t4g.micro)

750 часов/месяц + 20 ГБ хранилища

1 инстанс базы данных — укладывается в лимит

S3

5 ГБ хранилища, 20 000 GET / 2 000 PUT запросов в месяц

Один HTML-файл и лёгкий трафик портфолио — далеко до лимита

Исходящий трафик

100 ГБ/месяц (первые 12 месяцев)

Трафик уровня портфолио не приблизится к этому

Что будет стоить денег, поэтому избегайте этого:

  • Запуск второго EC2-инстанса или базы RDS одновременно (бесплатны только первые часы каждого сервиса — работа двух инстансов съедает двойные часы)

  • Использование инстанса большего размера, чем t2.micro/t3.micro (EC2) или db.t3.micro/db.t4g.micro (RDS)

  • Запрос Elastic IP и не прикрепление его к запущенному инстансу — AWS берёт плату за непривязанные Elastic IP именно чтобы это предотвратить

  • Если ваш аккаунт AWS не новый — бесплатный уровень действует 12 месяцев с момента создания аккаунта; если аккаунт старше, эти сервисы будут тарифицироваться как обычно

Один предохранитель, который в любом случае стоит настроить: AWS Console → Billing → Budgets → создайте бюджетное оповещение на $1. Оно отправит вам письмо в тот момент, когда что-то начнёт стоить денег, так что сюрпризов не будет.

Заметки о MCP-слое

MCP-сервер (backend/mcp_server/server.py) — это отдельный процесс, который общается по протоколу Model Context Protocol через stdio. Агенты подключаются к нему как MCP-клиенты через langchain-mcp-adapters, который автоматически преобразует MCP-инструменты в совместимые с LangChain инструменты. Это значит, что тот же MCP-сервер можно подключить к Claude Desktop, Cursor или любому другому MCP-совместимому хосту без каких-либо изменений — в этом весь смысл такого подхода вместо захардкоженных схем инструментов внутри агента.

Related MCP Connectors

  • Real SEC, 13F, insider, congress & macro data your AI agent can cite. Hosted MCP, 24 tools.

    https://mcp.ko.io/mcp
  • Your agent needs markets — prices and fundamentals for listed companies, the filings behind them, crypto, and what the prediction markets put the odds at. **What you can ask for** • "Pull this company's income statement, cash flow and balance sheet for the last 8 quarters." • "What did insiders buy or sell, and when?" • "Snapshot prices for these 50 tickers, then the OHLC history for the three that moved." • "What are the current odds on this event across Kalshi and Polymarket?" • "Screen for companies matching these financial criteria." **How to use it** Point any MCP client at https://mcp.aisa.one/finance/mcp and sign in with OAuth — there is no key to create or paste. 49 tools: prices and snapshots, income statements, balance sheets and cash flows, metrics and ratios, earnings and analyst estimates, filings and line-item search, insider trades, macro interest rates, news, a screener; CoinGecko spot prices, market tables, OHLC, per-venue tickers and trending; Kalshi and Polymarket markets and trades; plus EDINET filings for Japan. **Why this rather than the source** Equities, crypto and event markets behind one account, so a cross-asset question is one conversation. **It is also a door to the rest** The same login reaches 26 sources and 580+ operations. Read the number here, then ask the same agent what X is saying about the ticker today — without adding a second server. **What it costs** Finding and inspecting an operation is free. Running one is billed per call at API prices, with no seat and no monthly minimum, and every call takes max_price_usd so an agent cannot overspend by accident. **Where else it reaches** https://mcp.aisa.one/marketpulse/mcp · /crypto-market-data/mcp · /prediction-market-data/mcp · /stock-pulse/mcp for one slice each.

  • Your agent needs the two halves of a move at once — what people are posting about a ticker right now, and what the price and the news actually did. **What you can ask for** • "What is X saying about $NVDA today, and what did the stock do?" • "Show the chatter and the price move for these five tickers side by side." • "Which tickers are being talked about most right now?" • "Pull the news and the snapshot behind this spike." **How to use it** Point any MCP client at https://mcp.aisa.one/stock-pulse/mcp and sign in with OAuth — there is no key to create or paste. 4 tools: a combined stock-pulse call that joins X/Twitter chatter to the tickers mentioned, plus advanced tweet search, price snapshots and financial news. **Why this rather than the source** One call instead of four, with the join already done. **It is also a door to the rest** The same login reaches 26 sources and 580+ operations. Spot the move here, then ask the same agent for the filings or the fundamentals behind it — without adding a second server. **What it costs** Finding and inspecting an operation is free. Running one is billed per call at API prices, with no seat and no monthly minimum, and every call takes max_price_usd so an agent cannot overspend by accident. **Where else it reaches** https://mcp.aisa.one/finance/mcp for equities, crypto and prediction markets in one place.

  • Your agent needs company financials it can compute on — statements, ratios, earnings, estimates, filings and insider activity as structured data, not a PDF. **What you can ask for** • "Give me 8 quarters of income statement, balance sheet and cash flow for this ticker." • "What do analysts estimate for next quarter, and how did the last four surprise?" • "Find this exact line item across every filing." • "Who bought or sold as an insider in the last 90 days?" • "Screen for profitable companies under this valuation with growing revenue." **How to use it** Point any MCP client at https://mcp.aisa.one/marketpulse/mcp and sign in with OAuth — there is no key to create or paste. 21 tools: prices and snapshots, income statements, balance sheets, cash-flow statements, financial metrics and snapshots, earnings, analyst estimates, company facts, filings and filing items, line-item search, a screener, insider trades, macro interest rates, news, plus EDINET documents and filing digests for Japanese issuers. **Why this rather than the source** Statements as fields you can compute on, and a screener in the same place. **It is also a door to the rest** The same login reaches 26 sources and 580+ operations. Read the fundamentals here, then ask the same agent what social is saying about the ticker — without adding a second server. **What it costs** Finding and inspecting an operation is free. Running one is billed per call at API prices, with no seat and no monthly minimum, and every call takes max_price_usd so an agent cannot overspend by accident. **Where else it reaches** https://mcp.aisa.one/finance/mcp for equities, crypto and prediction markets in one place.

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables AI agents to retrieve real-time stock data, manage watchlists, and perform comprehensive technical analysis using Yahoo Finance API. Provides 18+ tools for stock price tracking, trend analysis, volatility assessment, and financial indicators through MCP integration.
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables AI agents to access financial data and perform analysis by exposing AlphaVantage API endpoints as MCP tools, including company overview, income statement, balance sheet, cash flow, and earnings reports.
    1
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    Provides 10 financial data tools (market data, economic indicators, news, insider trades, and calendars) via a single MCP layer, enabling any MCP-compatible LLM to access diverse financial data through a unified interface.
    1
    MIT
  • A
    license
    A
    quality
    C
    maintenance
    Provides live financial data for any LLM agent, including stock quotes, crypto prices, SEC filings, XBRL financials, FX rates, and macro indicators, through ten MCP tools.
    11
    109 npm
    1
    MIT