How the Sentiment Analyst Agent Processes News in AI Hedge Fund

The sentiment analyst agent fetches insider trades and company news via the Financial Datasets API, maps pre-computed sentiment labels to bullish or bearish signals, and combines these with insider trade signals using a 70% news / 30% insider weighting to generate a final market sentiment recommendation and confidence score.

The sentiment analyst agent (sentiment_analyst_agent) serves as a critical decision node in the virattt/ai-hedge-fund system, translating unstructured financial news into structured trading signals. Operating within a LangChain-based agent graph, this component aggregates multiple data sources to produce weighted sentiment analysis that downstream portfolio optimizers consume for position sizing and risk management.

Step-by-Step News Processing Pipeline

The sentiment analyst agent processes each ticker through a deterministic pipeline defined in src/agents/sentiment.py. The workflow combines complementary data streams to reduce single-source bias.

Fetching Insider Trade Data

First, the agent retrieves transaction records to establish a baseline market signal. It calls get_insider_trades (via src/tools/api.py) and transforms the raw transaction amounts into discrete bullish or bearish indicators.


# Located at src/agents/sentiment.py#L24-L31

insider_trades = get_insider_trades(
    ticker=ticker,
    end_date=end_date,
    limit=100,
)

The agent parses these records to build a list of insider-derived signals before moving to news analysis.

Retrieving Company News via Financial Datasets API

Next, the agent fetches up to 100 recent news items for the ticker using get_company_news. The Financial Datasets API returns CompanyNews Pydantic models that contain a pre-computed sentiment field, eliminating the need for real-time LLM classification during this stage.


# Located at src/agents/sentiment.py#L38-L42

company_news = get_company_news(
    ticker=ticker,
    end_date=end_date,
    limit=100,
)

This design choice significantly reduces latency and API costs by leveraging sentiment labels generated earlier in the graph workflow.

Extracting and Mapping Sentiment Labels

The agent extracts the sentiment attribute from each news record into a pandas.Series, drops missing values, and applies a deterministic mapping to trading signals.


# Located at src/agents/sentiment.py#L44-L46

sentiment = pd.Series([n.sentiment for n in company_news]).dropna()
signal_mapping = {"positive": "bullish", "negative": "bearish", "neutral": "neutral"}

This transformation converts subjective sentiment classifications into objective signal categories that can be mathematically weighted against insider trade indicators.

Weighted Signal Aggregation Logic

The core intelligence of the sentiment analyst agent lies in its weighted consensus mechanism. It assigns 70% weight to news sentiment and 30% weight to insider trades, reflecting the broader market impact of news relative to individual insider activity.


# Located at src/agents/sentiment.py#L50-L58

insider_weight = 0.3
news_weight = 0.7

# Count signals from each source

insider_signals = [...]  # derived from transaction analysis

news_signals = sentiment.map(signal_mapping).tolist()

# Weighted aggregation

bullish_signals = (insider_signals.count("bullish") * insider_weight) + \
                  (news_signals.count("bullish") * news_weight)
bearish_signals = (insider_signals.count("bearish") * insider_weight) + \
                  (news_signals.count("bearish") * news_weight)

The agent determines the overall_signal by comparing weighted totals (lines 63‑68 in src/agents/sentiment.py). If bullish weight exceeds bearish weight, the recommendation is bullish; conversely for bearish. When weights are equal or insufficient data exists, the signal defaults to neutral.

Confidence Score Calculation

Confidence derives from the proportion of weighted signals supporting the chosen direction. The agent calculates this as a percentage to provide portfolio managers with quantitative certainty metrics for position sizing decisions (lines 70‑75).

Integration with the News Sentiment Agent

The pre-computed sentiment labels utilized by the sentiment analyst agent originate from the News Sentiment Agent (news_sentiment_agent), which executes earlier in the LangChain graph. This separate agent:

  • Retrieves raw news via get_company_news
  • Invokes an LLM through call_llm to classify headlines lacking sentiment metadata
  • Stores sentiment values and LLM confidence scores in the CompanyNews model

You can examine the LLM prompt construction at src/agents/news_sentiment.py#L76-L84 and the confidence aggregation at lines 66‑84. This architectural separation ensures that the computationally expensive LLM operations occur once, while the sentiment analyst agent performs fast, deterministic arithmetic aggregation.

Practical Implementation Example

Below is a minimal invocation pattern demonstrating how the sentiment analyst agent operates within the graph state framework:

from src.graph.state import AgentState
from src.agents.sentiment import sentiment_analyst_agent

# Initialize shared state

state = AgentState()
state["data"] = {
    "tickers": ["AAPL", "MSFT"],
    "end_date": "2024-12-31",
    "analyst_signals": {}
}
state["metadata"] = {"show_reasoning": True}

# Execute sentiment analysis

result = sentiment_analyst_agent(state)

# Access structured output

print(state["data"]["analyst_signals"]["sentiment_analyst_agent"])

This script populates the shared state with per-ticker sentiment analysis, including the weighted reasoning payload and confidence percentages that downstream agents consume.

Key Source Files and Architecture

File Purpose Critical Lines
src/agents/sentiment.py Core sentiment analyst implementation L12-17 (entry), L44-46 (label extraction), L50-58 (weighting)
src/agents/news_sentiment.py LLM-based sentiment labeling for news items L66-84 (confidence logic), L76-84 (prompt construction)
src/tools/api.py API wrappers for news and insider data News retrieval functions
src/graph/state.py AgentState definition for inter-agent communication State schema definition

Summary

  • The sentiment analyst agent processes news by extracting pre-computed sentiment labels from CompanyNews objects rather than performing real-time natural language processing.
  • It combines these signals with insider trade data using a fixed 70% news / 30% insider weighting scheme defined in src/agents/sentiment.py.
  • The agent outputs a deterministic trading signal (bullish, bearish, or neutral) with a calculated confidence score based on weighted signal proportions.
  • All sentiment labels originate from the News Sentiment Agent, which runs earlier in the workflow to minimize redundant LLM calls and reduce latency.
  • Results are stored in the shared AgentState under analyst_signals["sentiment_analyst_agent"] for consumption by portfolio optimization agents.

Frequently Asked Questions

How does the sentiment analyst agent differ from the news sentiment agent?

The news sentiment agent (src/agents/news_sentiment.py) performs the computationally expensive work of calling an LLM to classify raw news headlines into positive, negative, or neutral categories. The sentiment analyst agent (src/agents/sentiment.py) consumes these pre-computed labels, maps them to trading signals, and mathematically weights them against insider trade data to produce a final recommendation. This separation of concerns ensures that LLM inference happens once per news item, while the sentiment analyst performs fast arithmetic aggregation.

What API does the sentiment analyst agent use to fetch news?

The agent uses the Financial Datasets API via the get_company_news function located in src/tools/api.py. This API returns structured CompanyNews objects that include the sentiment field populated by the upstream news sentiment agent, allowing the sentiment analyst to work with cached, labeled data rather than raw text.

How are the 70/30 weights configured in the sentiment analyst agent?

The weights are hardcoded constants within the sentiment_analyst_agent function: insider_weight = 0.3 and news_weight = 0.7 (lines 50‑51 of src/agents/sentiment.py). These values are applied when calculating weighted bullish and bearish signal totals. Currently, these weights are not exposed as configurable parameters in the function signature, though they could be modified in the source code to adjust the relative importance of insider activity versus market news.

What data structure does the sentiment analyst agent return?

The agent returns a LangChain HumanMessage containing a JSON-serialized dictionary of sentiment analysis results. Additionally, it updates the shared AgentState object by storing structured analysis data under state["data"]["analyst_signals"]["sentiment_analyst_agent"]. This dictionary includes the overall_signal, confidence percentage, weighted signal counts, and detailed reasoning metrics for each processed ticker.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →