quantinvbench / scripts /compute_sentiment.py
ywliu
Publish QuantInvBench dataset
8f8fb44 verified
Raw History Blame Contribute Delete
6.03 kB
#!/usr/bin/env python3
"""Create the derived FinBERT sentiment file required by generate.py."""
from __future__ import annotations
import argparse
import glob
import json
from datetime import datetime, timezone
from pathlib import Path
import torch
import torch.nn.functional as functional
from transformers import AutoModelForSequenceClassification, AutoTokenizer
MODEL_ID = "ProsusAI/finbert"
CRYPTO_KEYWORDS = {
"bitcoin": ("bitcoin", "btc"),
"ethereum": ("ethereum", "eth", "ether"),
"tether": ("tether", "usdt"),
"xrp": ("xrp", "ripple"),
"bnb": ("bnb", "binance coin", "binance"),
}
GENERAL_KEYWORDS = (
"crypto",
"cryptocurrency",
"digital currency",
"blockchain",
"defi",
"digital asset",
"altcoin",
"token",
)
def parse_args() -> argparse.Namespace:
project_root = Path(__file__).resolve().parents[3]
release_root = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input-dir", type=Path, default=project_root / "smdata")
parser.add_argument(
"--output",
type=Path,
default=release_root / "cache" / "crypto_news_sentiment.json",
)
parser.add_argument("--batch-size", type=int, default=16)
parser.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto")
parser.add_argument(
"--local-files-only",
action="store_true",
help="Use the already cached tokenizer/model without contacting Hugging Face",
)
return parser.parse_args()
def article_text(article: dict) -> str:
title = article.get("title", "") or article.get("original_content", "")
full = article.get("full_content", "") or ""
if len(full) > 50 and not full.startswith(("HTTP", "Could not")):
return f"{title}. {full[:400]}" if title else full[:500]
return title
def mentioned_coins(text: str) -> list[str]:
lowered = text.lower()
matches = [
coin
for coin, keywords in CRYPTO_KEYWORDS.items()
if any(keyword in lowered for keyword in keywords)
]
if matches:
return matches
if any(keyword in lowered for keyword in GENERAL_KEYWORDS):
return list(CRYPTO_KEYWORDS)
return list(CRYPTO_KEYWORDS)
def score_articles(articles: list[dict], tokenizer, model, device, batch_size: int) -> list[float]:
scores = []
texts = [article_text(article) for article in articles]
for start in range(0, len(texts), batch_size):
batch = texts[start : start + batch_size]
inputs = tokenizer(
batch,
padding=True,
truncation=True,
max_length=512,
return_tensors="pt",
).to(device)
with torch.no_grad():
logits = model(**inputs).logits
probabilities = functional.softmax(logits, dim=-1)
scores.extend((probabilities[:, 0] - probabilities[:, 1]).cpu().tolist())
print(f"Scored {min(start + batch_size, len(texts))}/{len(texts)}", end="\r")
print()
return scores
def main() -> None:
args = parse_args()
if args.batch_size <= 0:
raise ValueError("batch size must be positive")
paths = sorted(Path(path) for path in glob.glob(str(args.input_dir / "crypto_strong_news_*_scored.json")))
if not paths:
raise FileNotFoundError(f"No scored news files found in {args.input_dir}")
articles = []
seen_articles = set()
for path in paths:
with path.open(encoding="utf-8") as handle:
payload = json.load(handle)
source_articles = payload if isinstance(payload, list) else payload.get("articles", [])
for article in source_articles:
if article.get("language") != "English" or not article_text(article).strip():
continue
identity = (
article.get("timestamp", ""),
article.get("title", ""),
article.get("url", ""),
)
if identity in seen_articles:
continue
seen_articles.add(identity)
articles.append(article)
articles.sort(key=lambda article: article.get("timestamp", ""))
if args.device == "auto":
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
else:
device = torch.device(args.device)
print(f"Loading {MODEL_ID} on {device}; {len(articles)} articles")
tokenizer = AutoTokenizer.from_pretrained(
MODEL_ID,
local_files_only=args.local_files_only,
)
# FinBERT is published with both .bin and .safetensors weights. Newer
# Transformers rejects torch.load for older PyTorch versions, so force the
# safe checkpoint even when the legacy .bin file is also cached.
model = AutoModelForSequenceClassification.from_pretrained(
MODEL_ID,
use_safetensors=True,
local_files_only=args.local_files_only,
).to(device).eval()
scores = score_articles(articles, tokenizer, model, device, args.batch_size)
derived = [
{
"timestamp": article.get("timestamp", ""),
"sentiment": round(float(score), 6),
"coins": mentioned_coins(article_text(article)),
}
for article, score in zip(articles, scores)
]
output = {
"metadata": {
"model": MODEL_ID,
"model_revision": getattr(model.config, "_commit_hash", None),
"score_formula": "P(positive) - P(negative)",
"generated_at": datetime.now(timezone.utc).isoformat(),
"article_count": len(derived),
"contains_article_text": False,
},
"articles": derived,
}
args.output.parent.mkdir(parents=True, exist_ok=True)
with args.output.open("w", encoding="utf-8") as handle:
json.dump(output, handle, ensure_ascii=False, allow_nan=False)
handle.write("\n")
print(f"Wrote {len(derived)} derived records to {args.output}")
if __name__ == "__main__":
main()