Skip to main content

Overview

The Market Data endpoint provides a holistic view of a stock by combining:
  • Current price and fundamentals
  • News sentiment analysis (FinViz + VADER)
  • Analyst ratings and price targets
  • Insider trading activity (YahooQuery)
  • Key financial metrics

Get Market Context

curl http://localhost:8000/api/market-context/AAPL
symbol
string
required
Stock ticker symbol (e.g., “AAPL”, “TSLA”, “SPY”)

Response

symbol
string
Ticker symbol in uppercase
current_price
float
Current stock price (from currentPrice, regularMarketPrice, or previousClose)

Sentiment Analysis

sentiment_score
float
Sentiment score from -1.0 (very negative) to +1.0 (very positive)
  • -1.0 to -0.05: Negative
  • -0.05 to +0.05: Neutral
  • +0.05 to +1.0: Positive
sentiment_status
string
Human-readable sentiment: "positive", "neutral", "negative", or "unknown"
recent_news
array
Array of recent news headlines (strings) used for sentiment analysis

Analyst Data

target_mean
float | null
Mean analyst price target
target_median
float | null
Median analyst price target
recommendation_key
string | null
Analyst recommendation consensus:
  • "strong_buy", "buy", "hold", "sell", "strong_sell"

Company Information

long_business_summary
string | null
Brief business description (truncated to ~300 characters)

Financial Metrics

forward_pe
float | null
Forward price-to-earnings ratio
trailing_pe
float | null
Trailing price-to-earnings ratio
debt_to_equity
float | null
Debt-to-equity ratio

Insider Trading

insider_purchases
integer
Number of recent insider purchase transactions
insider_sales
integer
Number of recent insider sale transactions
top_insiders
array
Array of recent insider transactions (up to 3)

Example Response

{
  "symbol": "AAPL",
  "current_price": 175.43,
  "sentiment_score": 0.34,
  "sentiment_status": "positive",
  "recent_news": [
    "Apple unveils new AI features in latest software update",
    "iPhone sales exceed analyst expectations in Q4",
    "Apple stock hits new all-time high on strong earnings"
  ],
  "target_mean": 195.50,
  "target_median": 192.00,
  "recommendation_key": "buy",
  "long_business_summary": "Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. The company offers iPhone, Mac, iPad, and Wearables, Home and Accessories. Apple also sells various related services...",
  "forward_pe": 28.5,
  "trailing_pe": 31.2,
  "debt_to_equity": 145.3,
  "insider_purchases": 3,
  "insider_sales": 12,
  "top_insiders": [
    {
      "name": "Tim Cook",
      "position": "CEO",
      "shares_traded": -50000
    },
    {
      "name": "Luca Maestri",
      "position": "CFO",
      "shares_traded": -15000
    },
    {
      "name": "Arthur D. Levinson",
      "position": "Director",
      "shares_traded": 5000
    }
  ]
}

Sentiment Calculation

Sentiment analysis uses:
  1. FinViz to scrape recent news headlines
  2. VADER (Valence Aware Dictionary for Sentiment Reasoning) to score each headline
  3. Aggregates scores into a composite sentiment from -1.0 to +1.0

Insider Trading Interpretation

  • High Purchases, Low Sales: Bullish signal - insiders buying
  • Low Purchases, High Sales: Could be neutral (tax planning, diversification) or bearish
  • Negative shares_traded: Sale transaction
  • Positive shares_traded: Purchase transaction
Note: Executive sales are often planned in advance and may not indicate bearish outlook.

Error Responses

404
error
Unable to retrieve price data for symbol
{
  "detail": "No se pudo obtener el precio de XYZ"
}
500
error
Internal error during data fetching
{
  "detail": "Error message"
}

Data Sources

Yahoo Finance

Price, fundamentals, analyst targets

YahooQuery

Insider transactions and holders

FinViz + VADER

News scraping and sentiment scoring

Use Cases

Pre-Trade Research

import requests

# Get full context before building strategy
context = requests.get(
    "http://localhost:8000/api/market-context/AAPL"
).json()

# Check if conditions are favorable
if context['sentiment_score'] > 0.2:
    print("Positive sentiment - consider bullish strategies")
    
if context['insider_purchases'] > context['insider_sales']:
    print("Insiders are buying - bullish signal")
    
if context['current_price'] < context['target_mean']:
    print(f"Upside to analyst target: ${context['target_mean'] - context['current_price']:.2f}")

Risk Assessment

  • High debt_to_equity: More volatile, riskier strategies
  • Negative sentiment: Avoid aggressive bullish plays
  • Heavy insider selling: Exercise caution
  • High forward PE: Growth stock, higher volatility expected

Strategy Selection

  • Positive sentiment (> 0.1)
  • Price below analyst target
  • Insider buying > selling
  • Strong recommendation (buy/strong_buy)
→ Consider: Bull Put Spreads, Call Debit Spreads

Implementation Notes

Data Freshness: Sentiment is based on recent headlines which may be delayed. Insider data is from most recent filings. Always verify critical information.
Fallback Logic: If insider transaction parsing fails, the endpoint falls back to basic YFinance insider counts. The endpoint prioritizes returning data over perfect accuracy.

Integration Example

import requests

def analyze_ticker(ticker: str):
    """Complete analysis workflow"""
    
    # 1. Get market context
    context = requests.get(
        f"http://localhost:8000/api/market-context/{ticker}"
    ).json()
    
    # 2. Determine bias from sentiment and analysts
    if context['sentiment_score'] > 0.1 and context['recommendation_key'] in ['buy', 'strong_buy']:
        bias = 'bullish'
    elif context['sentiment_score'] < -0.1:
        bias = 'bearish'
    else:
        bias = 'neutral'
    
    # 3. Get strategy recommendations
    recommendations = requests.get(
        f"http://localhost:8000/api/options/recommend/{ticker}",
        params={'bias': bias, 'risk_profile': 'balanced'}
    ).json()
    
    return {
        'context': context,
        'bias': bias,
        'strategies': recommendations['recommendations']
    }

result = analyze_ticker('AAPL')
print(f"Bias: {result['bias']}")
print(f"Recommended: {result['strategies'][0]['strategy_name']}")

Build docs developers (and LLMs) love