Skip to content
xai-stock-sentiment logo

xAI Stock Sentiment Analysis

xai-stock-sentiment

Real-time stock sentiment analysis using Twitter/X data via Grok. Use when analyzing stock ticker sentiment, tracking retail investor mood, or gauging market reaction to events.

NeverSight/skills_feed0installs215stars

SKILL.md

Full skill instructions

xAI Stock Sentiment Analysis

Real-time stock sentiment from Twitter/​X using Grok's native integration - a unique capability for financial analysis.

Quick Start

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/​v1"
)

def get_stock_sentiment(ticker: str) -> dict:
    """Get real-time sentiment for a stock ticker."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""Analyze X sentiment for ${ticker} stock.

            Search recent posts and return JSON:
            {{
                "ticker": "{ticker}",
                "sentiment": {{
                    "overall": "bullish" | "bearish" | "neutral",
                    "score": -1.0 to 1.0,
                    "confidence": 0.0 to 1.0
                }},
                "metrics": {{
                    "bullish_percent": 0-100,
                    "bearish_percent": 0-100,
                    "neutral_percent": 0-100,
                    "volume": "high" | "medium" | "low",
                    "velocity": "increasing" | "stable" | "decreasing"
                }},
                "key_drivers": ["driver1", "driver2"],
                "notable_mentions": [
                    {{"user": "@handle", "summary": "...", "influence": "high/​med/​low"}}
                ],
                "risks": ["risk1", "risk2"],
                "catalysts": ["catalyst1", "catalyst2"]
            }}"""
        }]
    )
    return response.choices[0].message.content

# Example
sentiment = get_stock_sentiment("AAPL")
print(sentiment)

Financial Handles to Track

FINANCIAL_INFLUENCERS = [
    # Breaking News
    "DeItaone",
    "FirstSquawk",
    "LiveSquawk",

    # Options Flow
    "unusual_whales",
    "OptionsHawk",

    # Analysis
    "jimcramer",
    "Carl_C_Icahn",
    "elerianm",

    # Retail Sentiment
    "wallstreetbets",
    "StockMarketNewz"
]

Sentiment Functions

Single Stock Analysis

def analyze_single_stock(ticker: str, timeframe: str = "24h") -> dict:
    """Comprehensive single stock sentiment analysis."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""Perform deep sentiment analysis for ${ticker} on X.
            Timeframe: Last {timeframe}

            Return comprehensive JSON:
            {{
                "ticker": "{ticker}",
                "timestamp": "current time",
                "sentiment_analysis": {{
                    "overall_score": -1 to 1,
                    "label": "very bullish/​bullish/​neutral/​bearish/​very bearish",
                    "confidence": 0 to 1,
                    "sample_size": n
                }},
                "breakdown": {{
                    "retail_sentiment": {{
                        "score": -1 to 1,
                        "volume": "high/​med/​low",
                        "trending_hashtags": [...]
                    }},
                    "influencer_sentiment": {{
                        "score": -1 to 1,
                        "key_opinions": [...]
                    }},
                    "news_reaction": {{
                        "recent_news": [...],
                        "reaction_sentiment": -1 to 1
                    }}
                }},
                "trading_signals": {{
                    "momentum": "bullish/​bearish/​neutral",
                    "volume_trend": "increasing/​stable/​decreasing",
                    "unusual_activity": true/​false,
                    "options_chatter": "calls heavy/​puts heavy/​balanced/​minimal"
                }},
                "catalysts": {{
                    "upcoming": [...],
                    "recent": [...]
                }},
                "risks": [...],
                "summary": "2-3 sentence summary"
            }}"""
        }]
    )
    return response.choices[0].message.content

Multi-Stock Comparison

def compare_stocks(tickers: list) -> dict:
    """Compare sentiment across multiple stocks."""
    tickers_str = ", ".join([f"${t}" for t in tickers])

    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""Compare X sentiment for: {tickers_str}

            Return JSON:
            {{
                "comparison": [
                    {{
                        "ticker": "...",
                        "sentiment_score": -1 to 1,
                        "volume": "high/​med/​low",
                        "trend": "improving/​stable/​declining",
                        "key_driver": "..."
                    }}
                ],
                "rankings": {{
                    "most_bullish": "TICKER",
                    "most_bearish": "TICKER",
                    "highest_volume": "TICKER",
                    "best_momentum": "TICKER"
                }},
                "sector_sentiment": "...",
                "recommendation": "..."
            }}"""
        }]
    )
    return response.choices[0].message.content

Earnings Reaction

def earnings_reaction(ticker: str) -> dict:
    """Analyze X reaction to earnings announcement."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""Analyze X reaction to ${ticker} earnings.

            Search for post-earnings discussion and return JSON:
            {{
                "ticker": "{ticker}",
                "earnings_reaction": {{
                    "immediate_sentiment": "positive/​negative/​mixed",
                    "sentiment_score": -1 to 1,
                    "surprise_reaction": "beat expectations/​met/​missed"
                }},
                "key_topics": {{
                    "positives_mentioned": [...],
                    "concerns_raised": [...],
                    "guidance_reaction": "..."
                }},
                "influencer_reactions": [
                    {{"user": "@handle", "stance": "bullish/​bearish", "key_point": "..."}}
                ],
                "price_action_sentiment": {{
                    "pre_market_mood": "...",
                    "opening_reaction": "..."
                }},
                "forward_outlook": "bullish/​bearish/​cautious"
            }}"""
        }]
    )
    return response.choices[0].message.content

Sector Sentiment

def sector_sentiment(sector: str, tickers: list = None) -> dict:
    """Analyze sentiment for an entire sector."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""Analyze X sentiment for the {sector} sector.
            {"Key tickers to focus on: " + ", ".join([f"${t}" for t in tickers]) if tickers else ""}

            Return JSON:
            {{
                "sector": "{sector}",
                "overall_sentiment": {{
                    "score": -1 to 1,
                    "label": "bullish/​bearish/​neutral",
                    "trend": "improving/​stable/​declining"
                }},
                "key_themes": [...],
                "leaders": [
                    {{"ticker": "...", "sentiment": ..., "reason": "..."}}
                ],
                "laggards": [
                    {{"ticker": "...", "sentiment": ..., "reason": "..."}}
                ],
                "sector_catalysts": [...],
                "macro_factors": [...]
            }}"""
        }]
    )
    return response.choices[0].message.content

Unusual Activity Detection

def detect_unusual_activity(ticker: str) -> dict:
    """Detect unusual sentiment or activity for a stock."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""Check for unusual activity on X for ${ticker}.

            Look for:
            - Unusual volume of mentions
            - Sudden sentiment shifts
            - Whale/​insider mentions
            - Breaking news
            - Options flow chatter

            Return JSON:
            {{
                "ticker": "{ticker}",
                "unusual_activity_detected": true/​false,
                "alerts": [
                    {{
                        "type": "volume_spike/​sentiment_shift/​news_break/​whale_alert/​options_unusual",
                        "severity": "high/​medium/​low",
                        "description": "...",
                        "source": "..."
                    }}
                ],
                "normal_baseline": {{
                    "typical_mention_volume": "...",
                    "typical_sentiment": ...
                }},
                "current_state": {{
                    "mention_volume": "...",
                    "sentiment": ...
                }},
                "deviation": "significant/​moderate/​minor/​none",
                "recommended_action": "..."
            }}"""
        }]
    )
    return response.choices[0].message.content

Integration with Price Data

def sentiment_with_price(ticker: str, price_data: dict) -> dict:
    """Combine sentiment with price data for context."""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""Analyze ${ticker} sentiment in context of price action:

            Current Price: ${price_data.get('price', 'N/​A')}
            Change: {price_data.get('change_percent', 'N/​A')}%
            52-Week High: ${price_data.get('high_52w', 'N/​A')}
            52-Week Low: ${price_data.get('low_52w', 'N/​A')}

            Search X for current sentiment and analyze:
            1. Is sentiment aligned with price action?
            2. Any divergence signals?
            3. Support/​resistance levels mentioned?

            Return JSON with sentiment-price analysis."""
        }]
    )
    return response.choices[0].message.content

Watchlist Monitoring

def monitor_watchlist(tickers: list) -> dict:
    """Monitor sentiment for a watchlist of stocks."""
    tickers_str = ", ".join([f"${t}" for t in tickers])

    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""Monitor X sentiment for watchlist: {tickers_str}

            Return JSON:
            {{
                "timestamp": "...",
                "stocks": [
                    {{
                        "ticker": "...",
                        "sentiment_score": -1 to 1,
                        "change_from_yesterday": -1 to 1,
                        "alert_level": "none/​watch/​action",
                        "key_update": "..."
                    }}
                ],
                "alerts": [
                    {{"ticker": "...", "alert_type": "...", "message": "..."}}
                ],
                "market_mood": "risk-on/​risk-off/​mixed"
            }}"""
        }]
    )
    return response.choices[0].message.content

Best Practices

1. Time Your Queries

  • Pre-market: Catch overnight sentiment
  • Market open: Capture opening reaction
  • After hours: Earnings reactions

2. Combine Data Sources

# Best signal = sentiment + price + volume
x_sentiment = get_stock_sentiment(ticker)
price_data = finnhub.get_quote(ticker)
fundamentals = fmp.get_financials(ticker)

3. Filter for Quality

Focus on verified accounts and high-follower influencers.

4. Watch for Manipulation

  • Sudden coordinated pumps
  • Bot-like patterns
  • Unrealistic claims

Related Skills

  • xai-x-search - Raw X search
  • xai-sentiment - General sentiment
  • xai-crypto-sentiment - Crypto focus
  • xai-financial-integration - Data integration
  • finnhub-api - Price data
  • fmp-api - Fundamentals

References

More skills from NeverSight

devops-deployer logo
NeverSight/skills_feed

devops-deployer

Comprehensive DevOps and deployment workflow that orchestrates infrastructure automation, CI/CD pipelines, container orchestration, and cloud deployment. Handles everything from infrastructure as code and pipeline setup to monitoring, scaling, and disaster recovery.

215 1
View
avnu logo
NeverSight/skills_feed

avnu

Integrate avnu SDK for Starknet DeFi: token swaps with best-price routing, DCA recurring buys, native staking, gasless transactions via paymaster, and market data. Use when building Starknet trading, DEX aggregation, or DeFi automation features.

215 0
View
post-to-x logo
NeverSight/skills_feed

post-to-x

发布内容和文章到 X (Twitter)。支持带图片的普通推文和 X Articles(长文)。使用真实的 Chrome 和 CDP 来绕过自动化检测。

215 0
View
ralph-prompt-builder logo
NeverSight/skills_feed

ralph-prompt-builder

Master orchestrator for generating Ralph Wiggum-compatible prompts. Analyzes task requirements and routes to appropriate generator (single-task, multi-task, project, or research). Use when you need to create any Ralph loop prompt and want automatic selection of the right generator.

215 0
View
branch-comparison logo
NeverSight/skills_feed

branch-comparison

Use when the user asks to compare branches, analyze git diffs, review changes between branches, update specifications based on code changes, or analyze what changed. Triggers on keywords like "compare branches", "git diff", "what changed", "branch comparison", "code changes", "spec update".

215 0
View
fastapi-development logo
NeverSight/skills_feed

fastapi-development

Build high-performance FastAPI applications with async routes, validation, dependency injection, security, and automatic API documentation. Use when developing modern Python APIs with async support, automatic OpenAPI documentation, and high performance requirements.

215 0
View
zendesk-chat logo
NeverSight/skills_feed

zendesk-chat

Enables Claude to manage Zendesk Chat conversations, support tickets, and customer service operations

215 0
View
forge logo
NeverSight/skills_feed

forge

Mine transcripts for knowledge - decisions, learnings, failures, patterns. Triggers: "forge insights", "mine transcripts", "extract knowledge".

215 0
View
mixpanel logo
NeverSight/skills_feed

mixpanel

Track product analytics and user behavior with Mixpanel's event-based platform.

215 0
View
ocpp logo
NeverSight/skills_feed

ocpp

OCPP protocol reference for EV charging infrastructure development. Covers OCPP 2.0.1 and OCPP 1.6J. Use when working with OCPP messages, charging station code, CSMS/Central System backends, smart charging, transaction handling, or EV charging protocols. Activates on keywords: OCPP, charging stat...

215 0
View
bee-collect logo
NeverSight/skills_feed

bee-collect

Gather scattered ideas into organized GitHub issues. The bee collects pollen from every flower, checks if the hive already has it, and carefully deposits new work in the comb for later. Never edits code—only organizes the work ahead. Use when creating issues from TODOs or planning work.

215 0
View
vercel-react-native-skills logo
NeverSight/skills_feed

vercel-react-native-skills

Comprehensive best practices for React Native and Expo applications. Contains rules across multiple categories covering performance, animations, UI patterns, and platform-specific optimizations.

215 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View