Text Classification
Transformers
Joblib
Safetensors
bert
sentiment-analysis
finance
macroeconomics
climate
esg
policy
ensemble
dictionary
finbert
Eval Results (legacy)
text-embeddings-inference
Instructions to use peyterho/macro-sentiment-finbert with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use peyterho/macro-sentiment-finbert with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="peyterho/macro-sentiment-finbert")# Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("peyterho/macro-sentiment-finbert") model = AutoModelForSequenceClassification.from_pretrained("peyterho/macro-sentiment-finbert", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload macro_sentiment/pipeline.py
Browse files- macro_sentiment/pipeline.py +133 -0
macro_sentiment/pipeline.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unified Macroeconomic Sentiment Pipeline.
|
| 3 |
+
|
| 4 |
+
Combines dictionary signals + transformer ensemble + topic routing
|
| 5 |
+
into a structured output with overall macro sentiment, policy stance,
|
| 6 |
+
crisis signal, and domain-specific scores.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import numpy as np
|
| 11 |
+
from typing import Dict, List
|
| 12 |
+
from dataclasses import dataclass, field, asdict
|
| 13 |
+
|
| 14 |
+
from macro_sentiment.dictionaries import CombinedDictionaryScorer
|
| 15 |
+
from macro_sentiment.transformers_ensemble import TransformerEnsemble
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class MacroSentimentResult:
|
| 20 |
+
"""Structured output from the macro sentiment pipeline."""
|
| 21 |
+
macro_sentiment: float = 0.0
|
| 22 |
+
confidence: float = 0.0
|
| 23 |
+
financial_sentiment: float = 0.0
|
| 24 |
+
policy_stance: float = 0.0
|
| 25 |
+
climate_sentiment: float = 0.0
|
| 26 |
+
crisis_signal: float = 0.0
|
| 27 |
+
uncertainty: float = 0.0
|
| 28 |
+
detected_domain: str = "general"
|
| 29 |
+
topic: str = ""
|
| 30 |
+
topic_confidence: float = 0.0
|
| 31 |
+
head_used: str = ""
|
| 32 |
+
lm_polarity: float = 0.0
|
| 33 |
+
henry_polarity: float = 0.0
|
| 34 |
+
climate_exposure: float = 0.0
|
| 35 |
+
raw_features: Dict[str, float] = field(default_factory=dict)
|
| 36 |
+
|
| 37 |
+
def to_dict(self): return asdict(self)
|
| 38 |
+
def to_json(self, indent=2): return json.dumps(self.to_dict(), indent=indent, default=str)
|
| 39 |
+
|
| 40 |
+
def summary(self):
|
| 41 |
+
s = "Very Negative" if self.macro_sentiment < -0.6 else "Negative" if self.macro_sentiment < -0.2 else "Neutral" if self.macro_sentiment < 0.2 else "Positive" if self.macro_sentiment < 0.6 else "Very Positive"
|
| 42 |
+
p = "Very Dovish" if self.policy_stance < -0.6 else "Dovish" if self.policy_stance < -0.2 else "Neutral" if self.policy_stance < 0.2 else "Hawkish" if self.policy_stance < 0.6 else "Very Hawkish"
|
| 43 |
+
c = "HIGH CRISIS" if self.crisis_signal > 0.6 else "Elevated" if self.crisis_signal > 0.3 else "Normal"
|
| 44 |
+
parts = [f"Sentiment: {s} ({self.macro_sentiment:+.3f})", f"Policy: {p} ({self.policy_stance:+.3f})", f"Crisis: {c} ({self.crisis_signal:.3f})", f"Domain: {self.detected_domain}"]
|
| 45 |
+
if self.climate_exposure > 0.1:
|
| 46 |
+
cl = "Opportunity" if self.climate_sentiment > 0.2 else "Risk" if self.climate_sentiment < -0.2 else "Neutral"
|
| 47 |
+
parts.append(f"Climate: {cl} (exp={self.climate_exposure:.2f})")
|
| 48 |
+
return " | ".join(parts)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class MacroSentimentPipeline:
|
| 52 |
+
def __init__(self, device="cpu", use_router=True, load_transformers=True):
|
| 53 |
+
self.device = device
|
| 54 |
+
self.use_transformers = load_transformers
|
| 55 |
+
self.dict_scorer = CombinedDictionaryScorer()
|
| 56 |
+
self.transformer_ensemble = TransformerEnsemble(device=device, use_router=use_router) if load_transformers else None
|
| 57 |
+
|
| 58 |
+
def __call__(self, text, mode="routed"):
|
| 59 |
+
return self.score(text, mode=mode)
|
| 60 |
+
|
| 61 |
+
def score(self, text, mode="routed"):
|
| 62 |
+
result = MacroSentimentResult()
|
| 63 |
+
dict_features = self.dict_scorer.score(text)
|
| 64 |
+
result.lm_polarity = dict_features["lm_polarity"]
|
| 65 |
+
result.henry_polarity = dict_features["henry_polarity"]
|
| 66 |
+
result.climate_exposure = dict_features["climate_exposure"]
|
| 67 |
+
result.crisis_signal = dict_features["macro_crisis_intensity"]
|
| 68 |
+
result.uncertainty = dict_features["macro_uncertainty"]
|
| 69 |
+
|
| 70 |
+
if self.use_transformers and mode != "dict_only":
|
| 71 |
+
if mode == "routed":
|
| 72 |
+
tf_features = self.transformer_ensemble.score_routed(text)
|
| 73 |
+
result.head_used = tf_features.get("head_used", "unknown")
|
| 74 |
+
result.topic = tf_features.get("topic", "")
|
| 75 |
+
result.topic_confidence = tf_features.get("topic_confidence", 0.0)
|
| 76 |
+
head = result.head_used
|
| 77 |
+
result.detected_domain = {"policy": "policy", "climate": "climate", "tweet": "social"}.get(head, "financial_news")
|
| 78 |
+
primary_tf_score = tf_features.get("sentiment_score", 0.0)
|
| 79 |
+
elif mode == "all":
|
| 80 |
+
tf_features = self.transformer_ensemble.score_all(text)
|
| 81 |
+
primary_tf_score = tf_features.get("ensemble_mean", 0.0)
|
| 82 |
+
result.detected_domain = "ensemble"
|
| 83 |
+
result.head_used = "all"
|
| 84 |
+
else:
|
| 85 |
+
tf_features = {}
|
| 86 |
+
primary_tf_score = 0.0
|
| 87 |
+
|
| 88 |
+
result.financial_sentiment = tf_features.get("finbert_composite_score", tf_features.get("sentiment_score", 0.0))
|
| 89 |
+
result.climate_sentiment = tf_features.get("climate_composite_score", dict_features.get("climate_net_sentiment", 0.0))
|
| 90 |
+
|
| 91 |
+
policy_score = tf_features.get("policy_composite_score", None)
|
| 92 |
+
dict_policy = dict_features["macro_policy_stance"]
|
| 93 |
+
if dict_policy != 0.0:
|
| 94 |
+
result.policy_stance = 0.8 * dict_policy + 0.2 * (policy_score or 0.0)
|
| 95 |
+
elif policy_score is not None:
|
| 96 |
+
result.policy_stance = policy_score
|
| 97 |
+
|
| 98 |
+
crisis_weight = min(0.4, result.crisis_signal * 0.5)
|
| 99 |
+
tf_weight = 0.65 - crisis_weight
|
| 100 |
+
dict_weight = 0.35 + crisis_weight
|
| 101 |
+
dict_composite = np.mean([dict_features["lm_polarity"], dict_features["henry_polarity"]])
|
| 102 |
+
result.macro_sentiment = tf_weight * primary_tf_score + dict_weight * dict_composite
|
| 103 |
+
|
| 104 |
+
signals = [primary_tf_score, dict_composite]
|
| 105 |
+
agreement = 1.0 - np.std(signals)
|
| 106 |
+
result.confidence = min(1.0, max(0.0, 0.5 * agreement + 0.3 * result.topic_confidence + 0.2 * (1.0 - result.uncertainty)))
|
| 107 |
+
else:
|
| 108 |
+
result.detected_domain = "dict_only"
|
| 109 |
+
result.head_used = "none"
|
| 110 |
+
dict_composite = np.mean([dict_features["lm_polarity"], dict_features["henry_polarity"]])
|
| 111 |
+
result.macro_sentiment = dict_composite
|
| 112 |
+
result.policy_stance = dict_features["macro_policy_stance"]
|
| 113 |
+
result.climate_sentiment = dict_features["climate_net_sentiment"]
|
| 114 |
+
result.financial_sentiment = dict_composite
|
| 115 |
+
result.confidence = 0.3
|
| 116 |
+
|
| 117 |
+
for attr in ["macro_sentiment", "financial_sentiment", "policy_stance", "climate_sentiment"]:
|
| 118 |
+
setattr(result, attr, float(np.clip(getattr(result, attr), -1.0, 1.0)))
|
| 119 |
+
for attr in ["crisis_signal", "uncertainty", "confidence"]:
|
| 120 |
+
setattr(result, attr, float(np.clip(getattr(result, attr), 0.0, 1.0)))
|
| 121 |
+
|
| 122 |
+
result.raw_features = {**dict_features}
|
| 123 |
+
if self.use_transformers and mode != "dict_only":
|
| 124 |
+
result.raw_features.update({f"tf_{k}": v for k, v in tf_features.items() if isinstance(v, (int, float))})
|
| 125 |
+
return result
|
| 126 |
+
|
| 127 |
+
def score_batch(self, texts, mode="routed"):
|
| 128 |
+
return [self.score(t, mode=mode) for t in texts]
|
| 129 |
+
|
| 130 |
+
def load_all(self):
|
| 131 |
+
if self.transformer_ensemble:
|
| 132 |
+
self.transformer_ensemble.load_all()
|
| 133 |
+
return self
|