Обучение NLP-модели для анализа Twitter/X по криптовалютам
Twitter/X — самая быстрая среда распространения крипто-информации. Инфлюенсеры с миллионной аудиторией, анонимные аналитики, сотрудники проектов — все общаются здесь. Модель, способная в реальном времени анализировать этот поток, улавливает сигналы раньше, чем они отразятся в цене.
Twitter API v2 для крипто-данных
import tweepy
from datetime import datetime, timedelta
class TwitterCryptoCollector:
def __init__(self, bearer_token):
self.client = tweepy.Client(bearer_token=bearer_token, wait_on_rate_limit=True)
def search_recent(self, query, max_results=100):
"""
Twitter API v2 Basic: до 500k tweets/month
Academic: до 10M tweets/month + historical access
"""
tweets = self.client.search_recent_tweets(
query=query + ' lang:en -is:retweet',
max_results=min(max_results, 100),
tweet_fields=['created_at', 'public_metrics', 'author_id'],
expansions=['author_id'],
user_fields=['public_metrics', 'verified']
)
return tweets
def get_crypto_stream(self, keywords):
"""Filtered stream для realtime мониторинга"""
rules = [tweepy.StreamRule(kw) for kw in keywords]
self.client.add_stream_rules(rules)
# Запускаем stream в отдельном потоке
stream = self.CryptoStreamListener(self.client)
stream.filter(tweet_fields=['public_metrics', 'created_at'])
CRYPTO_QUERIES = {
'BTC': '(bitcoin OR btc OR #BTC OR #Bitcoin) crypto',
'ETH': '(ethereum OR eth OR #ETH OR #Ethereum) crypto',
'GENERAL': '#crypto OR #cryptocurrency OR #altcoins'
}
Специфика Twitter NLP
Твиты короткие (280 символов), содержат slang, cashtags ($BTC), emoji, аббревиатуры. Стандартные NLP модели плохо справляются без fine-tuning.
Предобработка:
import re
from emoji import demojize
def preprocess_tweet(text):
# Заменяем emoji на текстовое описание
text = demojize(text)
# Нормализуем cashtags
text = re.sub(r'\$([A-Z]{2,6})', r'TOKEN_\1', text)
# Удаляем URL
text = re.sub(r'http\S+', '[URL]', text)
# Нормализуем mentions
text = re.sub(r'@\w+', '[USER]', text)
# Крипто-специфичные замены
crypto_slang = {
'hodl': 'hold',
'rekt': 'ruined',
'wen': 'when',
'gm': 'good morning',
'ngmi': 'not going to make it',
'wagmi': 'we are all going to make it',
'degen': 'degenerate speculator',
'ape': 'invest blindly'
}
for slang, replacement in crypto_slang.items():
text = re.sub(rf'\b{slang}\b', replacement, text, flags=re.IGNORECASE)
return text
Tweet-BERT: модель для крипто-твитов
BERTweet: предобученный BERT на 850M английских твитах. Лучший baseline для Twitter NLP.
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
class CryptoTweetAnalyzer:
def __init__(self):
# BERTweet fine-tuned на крипто-твитах
self.tokenizer = AutoTokenizer.from_pretrained('vinai/bertweet-base')
self.model = AutoModelForSequenceClassification.from_pretrained(
'./crypto_bertweet_finetuned'
)
self.model.eval()
def analyze(self, tweet_text):
preprocessed = preprocess_tweet(tweet_text)
inputs = self.tokenizer(
preprocessed,
max_length=128,
truncation=True,
return_tensors='pt'
)
with torch.no_grad():
logits = self.model(**inputs).logits
probs = torch.softmax(logits, -1)[0]
return {
'bullish': probs[0].item(),
'bearish': probs[1].item(),
'neutral': probs[2].item(),
'score': probs[0].item() - probs[1].item()
}
Influence weighting
Не все твиты одинаково важны. Взвешиваем по влиянию автора:
def calculate_author_influence(user_metrics):
followers = user_metrics.get('followers_count', 0)
following = user_metrics.get('following_count', 1)
tweets_count = user_metrics.get('tweet_count', 1)
# Follower/Following ratio (качество аудитории)
ff_ratio = followers / following
# Log-scaled follower count
log_followers = np.log1p(followers)
# Верифицированный аккаунт
verified_bonus = 1.5 if user_metrics.get('verified', False) else 1.0
influence_score = log_followers * np.sqrt(ff_ratio) * verified_bonus
return min(influence_score / 20, 10) # нормализуем к [0, 10]
def weighted_sentiment(tweets_with_scores):
total_weight = sum(
t['score'] * t['engagement'] * t['author_influence']
for t in tweets_with_scores
)
total_normalizer = sum(
t['engagement'] * t['author_influence']
for t in tweets_with_scores
)
return total_weight / max(total_normalizer, 1)
Viral content detection
Быстро распространяющийся твит может быть рыночным сигналом:
def detect_viral_tweet(tweet, time_window_minutes=30, viral_threshold=500):
"""Если retweet rate > viral_threshold за 30 минут → viral"""
retweets = tweet['public_metrics']['retweet_count']
age_minutes = (datetime.utcnow() - tweet['created_at']).total_seconds() / 60
if age_minutes < time_window_minutes:
projected_retweets = retweets / age_minutes * time_window_minutes
if projected_retweets > viral_threshold:
return True, projected_retweets
return False, 0
KOL (Key Opinion Leaders) monitoring
Отдельный модуль: мониторинг твитов конкретного списка влиятельных аккаунтов:
- Vitalik Buterin, CZ, SBF (исторически), Elon Musk
- Аналитики: PlanB, Willy Woo, IntoTheBlock team
- Protocol founders
Любой твит от KOL → немедленный alert с sentiment analysis.
Стек: Python asyncio для Twitter Stream API, Redis для дедупликации и кэширования, Kafka для buffering высокого потока, PostgreSQL для хранения, GPU inference сервер для batch classification, React dashboard.
Разрабатываем систему мониторинга Twitter с BERTweet fine-tuning, influence weighting, viral detection, KOL мониторингом и realtime sentiment aggregation.







