xai-stock-sentiment

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

xAI Stock Sentiment Analysis

xAI 股票情绪分析

Real-time stock sentiment from Twitter/X using Grok's native integration - a unique capability for financial analysis.
借助Grok的原生集成功能,从Twitter/X获取实时股票情绪——这是金融分析的一项独特能力。

Quick Start

快速开始

python
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
python
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:
    """获取股票代码的实时情绪。"""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""分析X平台上${ticker}股票的情绪。

            搜索近期帖子并返回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)
undefined
sentiment = get_stock_sentiment("AAPL") print(sentiment)
undefined

Financial Handles to Track

需追踪的金融账号

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

    # Options Flow
    "unusual_whales",
    "OptionsHawk",

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

    # Retail Sentiment
    "wallstreetbets",
    "StockMarketNewz"
]
python
FINANCIAL_INFLUENCERS = [
    # 突发新闻
    "DeItaone",
    "FirstSquawk",
    "LiveSquawk",

    # 期权流向
    "unusual_whales",
    "OptionsHawk",

    # 分析类
    "jimcramer",
    "Carl_C_Icahn",
    "elerianm",

    # 散户情绪
    "wallstreetbets",
    "StockMarketNewz"
]

Sentiment Functions

情绪分析功能

Single Stock Analysis

单只股票分析

python
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
python
def analyze_single_stock(ticker: str, timeframe: str = "24h") -> dict:
    """对单只股票进行全面的情绪分析。"""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""对X平台上的${ticker}进行深度情绪分析。
            时间范围:过去{timeframe}

            返回全面的JSON结果:
            {{
                "ticker": "{ticker}",
                "timestamp": "当前时间",
                "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句话的总结"
            }}"""
        }]
    )
    return response.choices[0].message.content

Multi-Stock Comparison

多只股票对比

python
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
python
def compare_stocks(tickers: list) -> dict:
    """对比多只股票的情绪。"""
    tickers_str = ", ".join([f"${t}" for t in tickers])

    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""对比以下股票在X平台上的情绪:{tickers_str}

            返回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

财报反应分析

python
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
python
def earnings_reaction(ticker: str) -> dict:
    """分析X平台对财报发布的反应。"""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""分析X平台对${ticker}财报的反应。

            搜索财报发布后的讨论并返回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

板块情绪分析

python
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
python
def sector_sentiment(sector: str, tickers: list = None) -> dict:
    """分析整个板块的情绪。"""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""分析X平台上{sector}板块的情绪。
            {"重点关注的股票代码:" + ", ".join([f"${t}" for t in tickers]) if tickers else ""}

            返回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

异常活动检测

python
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
python
def detect_unusual_activity(ticker: str) -> dict:
    """检测股票的异常情绪或活动。"""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""检查X平台上${ticker}的异常活动。

            重点关注:
            - 提及量异常
            - 情绪突然转变
            - 大额交易方/内部人士提及
            - 突发新闻
            - 期权流向讨论

            返回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

与股价数据集成

python
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
python
def sentiment_with_price(ticker: str, price_data: dict) -> dict:
    """结合情绪与股价数据以获取更全面的分析。"""
    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""结合股价走势分析${ticker}的情绪:

            当前股价:${price_data.get('price', 'N/A')}
            涨跌幅:{price_data.get('change_percent', 'N/A')}%
            52周最高价:${price_data.get('high_52w', 'N/A')}
            52周最低价:${price_data.get('low_52w', 'N/A')}

            搜索X平台的当前情绪并分析:
            1. 情绪与股价走势是否一致?
            2. 是否存在背离信号?
            3. 有没有提到支撑/阻力位?

            返回包含情绪-股价分析的JSON结果。"""
        }]
    )
    return response.choices[0].message.content

Watchlist Monitoring

关注列表监控

python
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
python
def monitor_watchlist(tickers: list) -> dict:
    """监控关注列表中股票的情绪。"""
    tickers_str = ", ".join([f"${t}" for t in tickers])

    response = client.chat.completions.create(
        model="grok-4-1-fast",
        messages=[{
            "role": "user",
            "content": f"""监控关注列表中股票在X平台的情绪:{tickers_str}

            返回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

1. 选择合适的查询时间

  • Pre-market: Catch overnight sentiment
  • Market open: Capture opening reaction
  • After hours: Earnings reactions
  • 盘前:捕捉隔夜情绪
  • 开盘时:记录开盘反应
  • 盘后:分析财报反应

2. Combine Data Sources

2. 整合多数据源

python
undefined
python
undefined

Best signal = sentiment + price + volume

最佳信号 = 情绪 + 股价 + 成交量

x_sentiment = get_stock_sentiment(ticker) price_data = finnhub.get_quote(ticker) fundamentals = fmp.get_financials(ticker)
undefined
x_sentiment = get_stock_sentiment(ticker) price_data = finnhub.get_quote(ticker) fundamentals = fmp.get_financials(ticker)
undefined

3. Filter for Quality

3. 筛选优质内容

Focus on verified accounts and high-follower influencers.
重点关注认证账号和高粉丝量的意见领袖。

4. Watch for Manipulation

4. 警惕操纵行为

  • 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
  • xai-x-search
    - 原始X平台搜索
  • xai-sentiment
    - 通用情绪分析
  • xai-crypto-sentiment
    - 加密货币领域情绪分析
  • xai-financial-integration
    - 数据集成
  • finnhub-api
    - 股价数据获取
  • fmp-api
    - 基本面数据获取

References

参考资料