xai-sentiment
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesexAI Sentiment Analysis
xAI情感分析
Real-time sentiment analysis on Twitter/X content using Grok's native integration and built-in NLP capabilities.
借助Grok的原生集成功能和内置NLP能力,对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 analyze_sentiment(topic: str) -> dict:
"""Analyze sentiment for a topic on X."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Analyze sentiment on X for: {topic}
Search recent posts and return JSON:
{{
"topic": "{topic}",
"sentiment": "bullish" | "bearish" | "neutral",
"score": -1.0 to 1.0,
"confidence": 0.0 to 1.0,
"positive_percent": 0-100,
"negative_percent": 0-100,
"neutral_percent": 0-100,
"sample_size": number,
"key_themes": ["theme1", "theme2"],
"notable_posts": [
{{"author": "@handle", "summary": "...", "sentiment": "..."}}
]
}}"""
}]
)
return response.choices[0].message.contentpython
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("XAI_API_KEY"),
base_url="https://api.x.ai/v1"
)
def analyze_sentiment(topic: str) -> dict:
"""分析X平台上某一话题的情感倾向。"""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""分析X平台上关于以下话题的情感倾向: {topic}
搜索近期帖子并返回JSON格式结果:
{{
"topic": "{topic}",
"sentiment": "bullish" | "bearish" | "neutral",
"score": -1.0 to 1.0,
"confidence": 0.0 to 1.0,
"positive_percent": 0-100,
"negative_percent": 0-100,
"neutral_percent": 0-100,
"sample_size": number,
"key_themes": ["theme1", "theme2"],
"notable_posts": [
{{"author": "@handle", "summary": "...", "sentiment": "..."}}
]
}}"""
}]
)
return response.choices[0].message.contentExample
示例
result = analyze_sentiment("$AAPL stock")
print(result)
undefinedresult = analyze_sentiment("$AAPL stock")
print(result)
undefinedSentiment Score Scale
情感分数区间
| Score Range | Label | Description |
|---|---|---|
| 0.6 to 1.0 | Very Bullish | Strong positive sentiment |
| 0.2 to 0.6 | Bullish | Moderately positive |
| -0.2 to 0.2 | Neutral | Mixed or balanced |
| -0.6 to -0.2 | Bearish | Moderately negative |
| -1.0 to -0.6 | Very Bearish | Strong negative sentiment |
| 分数区间 | 标签 | 说明 |
|---|---|---|
| 0.6 至 1.0 | 极度乐观 | 强烈正面情绪 |
| 0.2 至 0.6 | 乐观 | 中度正面情绪 |
| -0.2 至 0.2 | 中立 | 情绪混合或平衡 |
| -0.6 至 -0.2 | 悲观 | 中度负面情绪 |
| -1.0 至 -0.6 | 极度悲观 | 强烈负面情绪 |
Sentiment Analysis Functions
情感分析功能
Basic Sentiment
基础情感分析
python
def get_basic_sentiment(query: str) -> dict:
"""Get simple sentiment score."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Search X for "{query}" and analyze sentiment.
Return only JSON:
{{"positive": 0-100, "neutral": 0-100, "negative": 0-100, "score": -1 to 1}}"""
}]
)
return response.choices[0].message.contentpython
def get_basic_sentiment(query: str) -> dict:
"""获取简单的情感分数。"""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""在X平台搜索"{query}"并分析情感倾向。
仅返回JSON格式结果:
{{"positive": 0-100, "neutral": 0-100, "negative": 0-100, "score": -1 to 1}}"""
}]
)
return response.choices[0].message.contentDetailed Sentiment Analysis
详细情感分析
python
def get_detailed_sentiment(topic: str, timeframe: str = "24h") -> dict:
"""Get comprehensive sentiment analysis."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Perform detailed sentiment analysis on X for: {topic}
Timeframe: Last {timeframe}
Return JSON:
{{
"overall_sentiment": {{
"label": "bullish/bearish/neutral",
"score": -1 to 1,
"confidence": 0 to 1
}},
"breakdown": {{
"positive": {{"percent": 0-100, "count": n}},
"negative": {{"percent": 0-100, "count": n}},
"neutral": {{"percent": 0-100, "count": n}}
}},
"themes": [
{{"theme": "...", "sentiment": "...", "frequency": n}}
],
"influencer_sentiment": [
{{"handle": "@...", "sentiment": "...", "followers": n}}
],
"trending_hashtags": ["#tag1", "#tag2"],
"sentiment_drivers": {{
"positive_factors": ["..."],
"negative_factors": ["..."]
}}
}}"""
}]
)
return response.choices[0].message.contentpython
def get_detailed_sentiment(topic: str, timeframe: str = "24h") -> dict:
"""获取全面的情感分析结果。"""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""对X平台上关于{topic}的内容进行详细情感分析
时间范围: 过去{timeframe}
返回JSON格式结果:
{{
"overall_sentiment": {{
"label": "bullish/bearish/neutral",
"score": -1 to 1,
"confidence": 0 to 1
}},
"breakdown": {{
"positive": {{"percent": 0-100, "count": n}},
"negative": {{"percent": 0-100, "count": n}},
"neutral": {{"percent": 0-100, "count": n}}
}},
"themes": [
{{"theme": "...", "sentiment": "...", "frequency": n}}
],
"influencer_sentiment": [
{{"handle": "@...", "sentiment": "...", "followers": n}}
],
"trending_hashtags": ["#tag1", "#tag2"],
"sentiment_drivers": {{
"positive_factors": ["..."],
"negative_factors": ["..."]
}}
}}"""
}]
)
return response.choices[0].message.contentComparative Sentiment
对比情感分析
python
def compare_sentiment(topics: list) -> dict:
"""Compare sentiment across multiple topics."""
topics_str = ", ".join(topics)
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Compare X sentiment for: {topics_str}
Return JSON:
{{
"comparison": [
{{
"topic": "...",
"sentiment_score": -1 to 1,
"volume": "high/medium/low",
"trend": "improving/declining/stable"
}}
],
"winner": "most positive topic",
"loser": "most negative topic",
"insights": ["..."]
}}"""
}]
)
return response.choices[0].message.contentpython
def compare_sentiment(topics: list) -> dict:
"""对比多个话题的情感倾向。"""
topics_str = ", ".join(topics)
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""对比X平台上以下话题的情感倾向: {topics_str}
返回JSON格式结果:
{{
"comparison": [
{{
"topic": "...",
"sentiment_score": -1 to 1,
"volume": "high/medium/low",
"trend": "improving/declining/stable"
}}
],
"winner": "most positive topic",
"loser": "most negative topic",
"insights": ["..."]
}}"""
}]
)
return response.choices[0].message.contentSentiment Over Time
情感趋势分析
python
def sentiment_timeline(topic: str, periods: list) -> dict:
"""Track sentiment changes over time."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Analyze how sentiment for "{topic}" has changed on X.
Return JSON with sentiment for different time periods:
{{
"topic": "{topic}",
"timeline": [
{{"period": "last hour", "score": -1 to 1}},
{{"period": "last 24 hours", "score": -1 to 1}},
{{"period": "last week", "score": -1 to 1}}
],
"trend": "improving/declining/stable",
"momentum": "accelerating/decelerating/steady",
"key_events": [
{{"time": "...", "event": "...", "impact": "..."}}
]
}}"""
}]
)
return response.choices[0].message.contentpython
def sentiment_timeline(topic: str, periods: list) -> dict:
"""追踪情感倾向随时间的变化。"""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""分析X平台上{topic}的情感倾向变化。
返回包含不同时间段情感数据的JSON结果:
{{
"topic": "{topic}",
"timeline": [
{{"period": "last hour", "score": -1 to 1}},
{{"period": "last 24 hours", "score": -1 to 1}},
{{"period": "last week", "score": -1 to 1}}
],
"trend": "improving/declining/stable",
"momentum": "accelerating/decelerating/steady",
"key_events": [
{{"time": "...", "event": "...", "impact": "..."}}
]
}}"""
}]
)
return response.choices[0].message.contentFinancial Sentiment Analysis
金融情感分析
Stock Sentiment
股票情感分析
python
def stock_sentiment(ticker: str) -> dict:
"""Analyze stock sentiment with financial context."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Analyze X sentiment for ${ticker} stock.
Return JSON:
{{
"ticker": "{ticker}",
"sentiment": {{
"overall": "bullish/bearish/neutral",
"score": -1 to 1,
"strength": "strong/moderate/weak"
}},
"trading_signals": {{
"retail_sentiment": "...",
"smart_money_mentions": "...",
"options_chatter": "..."
}},
"catalysts_mentioned": ["earnings", "product", "macro"],
"price_predictions": {{
"bullish_targets": [...],
"bearish_targets": [...]
}},
"risk_factors": ["..."],
"recommendation": "..."
}}"""
}]
)
return response.choices[0].message.contentpython
def 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 to 1,
"strength": "strong/moderate/weak"
}},
"trading_signals": {{
"retail_sentiment": "...",
"smart_money_mentions": "...",
"options_chatter": "..."
}},
"catalysts_mentioned": ["earnings", "product", "macro"],
"price_predictions": {{
"bullish_targets": [...],
"bearish_targets": [...]
}},
"risk_factors": ["..."],
"recommendation": "..."
}}"""
}]
)
return response.choices[0].message.contentCrypto Sentiment
加密货币情感分析
python
def crypto_sentiment(coin: str) -> dict:
"""Analyze cryptocurrency sentiment."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Analyze X sentiment for {coin} cryptocurrency.
Return JSON:
{{
"coin": "{coin}",
"sentiment_score": -1 to 1,
"fear_greed_indicator": "extreme fear/fear/neutral/greed/extreme greed",
"whale_mentions": "high/medium/low",
"influencer_sentiment": [...],
"trending_narratives": [...],
"fud_detection": {{
"level": "high/medium/low",
"sources": [...]
}},
"fomo_detection": {{
"level": "high/medium/low",
"triggers": [...]
}}
}}"""
}]
)
return response.choices[0].message.contentpython
def crypto_sentiment(coin: str) -> dict:
"""分析加密货币的情感倾向。"""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""分析X平台上关于{coin}加密货币的情感倾向。
返回JSON格式结果:
{{
"coin": "{coin}",
"sentiment_score": -1 to 1,
"fear_greed_indicator": "extreme fear/fear/neutral/greed/extreme greed",
"whale_mentions": "high/medium/low",
"influencer_sentiment": [...],
"trending_narratives": [...],
"fud_detection": {{
"level": "high/medium/low",
"sources": [...]
}},
"fomo_detection": {{
"level": "high/medium/low",
"triggers": [...]
}}
}}"""
}]
)
return response.choices[0].message.contentBatch Sentiment Analysis
批量情感分析
python
def batch_sentiment(topics: list) -> list:
"""Analyze sentiment for multiple topics efficiently."""
topics_formatted = "\n".join([f"- {t}" for t in topics])
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Analyze X sentiment for each:
{topics_formatted}
Return JSON array:
[
{{"topic": "...", "score": -1 to 1, "label": "...", "volume": "high/med/low"}}
]"""
}]
)
return response.choices[0].message.contentpython
def batch_sentiment(topics: list) -> list:
"""高效分析多个话题的情感倾向。"""
topics_formatted = "\n".join([f"- {t}" for t in topics])
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""分析以下每个话题在X平台上的情感倾向:
{topics_formatted}
返回JSON数组:
[
{{"topic": "...", "score": -1 to 1, "label": "...", "volume": "high/med/low"}}
]"""
}]
)
return response.choices[0].message.contentSentiment Alerts
情感预警
python
def check_sentiment_alert(topic: str, threshold: float = 0.5) -> dict:
"""Check if sentiment has crossed alert threshold."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Check X sentiment for {topic}.
Alert threshold: {threshold} (positive) or {-threshold} (negative)
Return JSON:
{{
"topic": "{topic}",
"current_score": -1 to 1,
"alert_triggered": true/false,
"alert_type": "bullish/bearish/none",
"reason": "...",
"recommended_action": "..."
}}"""
}]
)
return response.choices[0].message.contentpython
def check_sentiment_alert(topic: str, threshold: float = 0.5) -> dict:
"""检查情感分数是否超过预警阈值。"""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""检查X平台上{topic}的情感倾向。
预警阈值: {threshold}(正面) 或 {-threshold}(负面)
返回JSON格式结果:
{{
"topic": "{topic}",
"current_score": -1 to 1,
"alert_triggered": true/false,
"alert_type": "bullish/bearish/none",
"reason": "...",
"recommended_action": "..."
}}"""
}]
)
return response.choices[0].message.contentBest Practices
最佳实践
1. Request Confidence Scores
1. 请求置信度分数
Always ask for confidence levels to gauge reliability.
始终要求提供置信度以评估结果的可靠性。
2. Specify Sample Size
2. 指定样本量
Request the number of posts analyzed for context.
请求说明分析的帖子数量,以便了解结果背景。
3. Account for Sarcasm
3. 考虑讽刺内容
Grok may misinterpret sarcasm - request explicit sarcasm detection:
python
"Note: Flag any potentially sarcastic posts separately"Grok可能会误判讽刺内容 - 要求明确标记讽刺帖子:
python
"Note: Flag any potentially sarcastic posts separately"4. Filter by Quality
4. 筛选高质量内容
Combine with handle filtering for higher-quality signals:
python
"Focus on verified accounts and accounts with >10k followers"结合账号筛选,获取更优质的信号:
python
"Focus on verified accounts and accounts with >10k followers"5. Combine with Price Data
5. 结合价格数据
Sentiment is most valuable when combined with price action.
将情感分析与价格走势结合使用,价值更高。
Limitations
局限性
| Limitation | Mitigation |
|---|---|
| Sarcasm detection | Request explicit flagging |
| Bot content | Ask to filter suspicious patterns |
| Historical accuracy | Focus on recent data |
| Sample size | Request volume metrics |
| 局限性 | 缓解方案 |
|---|---|
| 讽刺检测 | 要求明确标记 |
| 机器人内容 | 要求过滤可疑模式 |
| 历史数据准确性 | 侧重近期数据 |
| 样本量 | 请求提供数据量指标 |
Related Skills
相关技能
- - X search functionality
xai-x-search - - Stock-specific analysis
xai-stock-sentiment - - Crypto analysis
xai-crypto-sentiment - - Combine with price data
xai-financial-integration
- - X平台搜索功能
xai-x-search - - 股票专项分析
xai-stock-sentiment - - 加密货币分析
xai-crypto-sentiment - - 与价格数据集成
xai-financial-integration