import os, requests, time
AV_KEY = os.environ["ALPHA_VANTAGE_KEY"]
AV_BASE = "https://www.alphavantage.co/query"
MV = os.environ["MAVERA_API_KEY"]
MV_BASE = "https://app.mavera.io/api/v1"
MV_H = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
TICKERS = {"AAPL": "Apple", "MSFT": "Microsoft", "GOOGL": "Google"}
OUR_TICKER = "AAPL"
# 1. Fetch news sentiment per ticker
sentiment_data = {}
for ticker, name in TICKERS.items():
r = requests.get(AV_BASE, params={
"function": "NEWS_SENTIMENT", "tickers": ticker,
"limit": 20, "apikey": AV_KEY,
})
r.raise_for_status()
feed = r.json().get("feed", [])
scores = []
articles_summary = []
for item in feed:
for ts in item.get("ticker_sentiment", []):
if ts.get("ticker") == ticker:
score = float(ts.get("ticker_sentiment_score", 0))
scores.append(score)
articles_summary.append(
f"- {item.get('title','')[:100]} (score: {score:.2f}, "
f"relevance: {ts.get('relevance_score','N/A')})"
)
avg = sum(scores) / len(scores) if scores else 0
sentiment_data[ticker] = {
"name": name, "avg_sentiment": avg, "article_count": len(feed),
"positive": sum(1 for s in scores if s > 0.15),
"negative": sum(1 for s in scores if s < -0.15),
"neutral": sum(1 for s in scores if -0.15 <= s <= 0.15),
"articles": articles_summary[:10],
}
print(f"{name} ({ticker}): avg={avg:.3f}, articles={len(feed)}, "
f"+{sentiment_data[ticker]['positive']}/-{sentiment_data[ticker]['negative']}")
time.sleep(15)
# 2. Build sentiment landscape
landscape = "\n\n".join(
f"## {d['name']} ({t})\n"
f"Average Sentiment: {d['avg_sentiment']:.3f}\n"
f"Distribution: {d['positive']} positive, {d['neutral']} neutral, {d['negative']} negative\n"
f"Top Headlines:\n" + "\n".join(d['articles'][:5])
for t, d in sentiment_data.items()
)
# 3. Mave positioning analysis
analysis = requests.post(f"{MV_BASE}/mave/chat", headers=MV_H, json={
"message": f"Brand strategist specializing in market-sentiment-aligned positioning.\n\n"
f"SENTIMENT LANDSCAPE (our ticker: {OUR_TICKER}):\n\n{landscape}\n\n"
"Analyze:\n"
"1. **Sentiment Map** — Where does each player sit? Who's gaining/losing favor?\n"
"2. **Our Position** — Given our sentiment vs competitors, what positioning plays are available?\n"
"3. **Messaging Recommendations** — 3 specific messaging angles based on the sentiment gap\n"
"4. **Timing** — Is sentiment trending up/down? Should we act now or wait?\n"
"5. **Risk** — What happens if sentiment reverses?\n\n"
"Be specific. Reference actual headline themes."
}).json()
print(f"\n{'='*60}\nSENTIMENT-BASED POSITIONING ANALYSIS\n{'='*60}")
print(analysis.get("content", "")[:2500])