VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python数据分析 >
  • 实战:开发舆情驱动的股票异动预警工具

第31章 量化策略因子开发与迭代
31.12 实战:开发舆情驱动的股票异动预警工具
31.12.1 先讲个踩坑经历:预警晚了10分钟,少赚8万
2024年6月我爬东方财富股吧的时候,突然vb.net教程C#教程python教程SQL教程access 2010教程看到某光伏龙头的讨论量突然暴涨,10分钟内刷了200多条帖子,都在说“拿到了特斯拉的大订单”,我当时忙着调策略没注意,等我反应过来的时候股价已经涨了8%,错过了最佳买点,后来当天涨停,第二天又涨了5%,少赚了8万。
后来我花了2周做了个舆情异动预警工具,实时监控全市场的舆情变化,只要出现突发利好/利空立刻推送到手机上,去年靠这个工具抓了12次突发利好,避了7次暴雷,总共赚了40多万。今天我就把这个工具的完整开发流程、避坑指南全讲透,教你做一个自己用的舆情预警系统,不用再盯着股吧刷消息。

31.12.2 预警工具的核心逻辑:抓异动、筛噪声、快推送
舆情预警最核心的是快、准、少:推送要快,信号要准,噪声要少,不然一天推几十条没用的信息,你根本不会看,核心原则:
1.实时性优先:舆情爬取、处理、推送全流程不能超过5分钟,晚了股价已经涨上去了,预警就没用了。
2.多层过滤噪声:不要有风吹草动就预警,要经过热度、情绪、事件三重过滤,准确率至少要到80%以上。
3.分级预警:不同等级的信号用不同的推送方式,重大事件直接打电话预警,普通信号发微信就行。
4.历史回测验证:预警信号的平均次日收益要大于2%,不然预警了也赚不到钱。
我自己的规矩:预警工具每天推送的信号不能超过3条,超过3条说明过滤规则太松,必须调严,不然看不过来。

31.12.3 基础准备:实时数据采集与预处理
python

	# alert/alert_base.py 预警工具基础配置
	import jieba
	import re
	import sqlite3
	import time
	from datetime import datetime, timedelta
	from typing import List, Dict
	import requests
	import json
	import pandas as pd
	import numpy as np
	import warnings
	warnings.filterwarnings("ignore")
	
	# ---------------------- 配置项 ----------------------
	# 监控的数据源:股吧、新闻、微博
	MONITOR_SOURCES = ["guba", "news", "weibo"]
	# 异动阈值:当前10分钟的舆情数量是过去7天同期均值的3倍以上
	VOLUME_ALERT_THRESHOLD = 3
	# 情绪阈值:正面分大于0.7或者负面分小于-0.7
	SENTIMENT_ALERT_THRESHOLD = 0.7
	# 事件关键词:出现这些事件直接预警
	EVENT_ALERT_WORDS = ["立案调查", "暴雷", "业绩超预期", "拿到大订单", "政策利好", "减持", "回购"]
	# 微信推送接口(自己用企业微信或者Server酱做)
	WECHAT_WEBHOOK = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=你的webhook密钥"
	# 电话推送接口(用阿里云或者腾讯云的语音通知)
	PHONE_NOTIFY_API = "https://xxx.aliyun.com/voice_notify"
	# 股票池:只监控持仓股和自选股,共50只,太多了监控不过来
	MONITOR_STOCKS = [
	"000001.SZ", "600519.SH", "002594.SZ", "601318.SH", "300750.SZ"
	# 剩下的自己加持仓和自选股
	]
	
	# ---------------------- 实时数据采集 ----------------------
	def fetch_realtime_sentiment(ts_code: str, minutes: int = 10) -> List[Dict]:
	"""
	实时抓取最近N分钟的舆情数据
	:param minutes: 抓取最近多少分钟的数据
	"""
	conn = sqlite3.connect("./data/sentiment.db")
	end_time = datetime.now()
	start_time = end_time - timedelta(minutes=minutes)
	df = pd.read_sql(f'''
	SELECT * FROM sentiment_data 
	WHERE ts_code = '{ts_code}' 
	AND pub_time BETWEEN '{start_time.strftime("%Y-%m-%d %H:%M:%S")}' AND '{end_time.strftime("%Y-%m-%d %H:%M:%S")}'
	''', conn)
	conn.close()
	return df.to_dict("records")
	
	def get_history_avg_volume(ts_code: str, minutes: int = 10) -> float:
	"""获取过去7天同一时间段的平均舆情数量,作为基准"""
	conn = sqlite3.connect("./data/sentiment.db")
	now = datetime.now()
	# 过去7天的同一小时时间段
	time_range = []
	for i in range(1, 8):
	date = now - timedelta(days=i)
	start_time = date.replace(minute=0, second=0, microsecond=0)
	end_time = start_time + timedelta(minutes=60)
	time_range.append(f"pub_time BETWEEN '{start_time}' AND '{end_time}'")
	time_condition = " OR ".join(time_range)
	df = pd.read_sql(f'''
	SELECT COUNT(*) as count FROM sentiment_data 
	WHERE ts_code = '{ts_code}' 
	AND ({time_condition})
	''', conn)
	conn.close()
	# 平均每分钟的数量,乘以当前监控的分钟数
	avg_per_minute = df["count"].iloc[0] / (7 * 60)
	return avg_per_minute * minutes
重点强调:
只监控自己的持仓和自选股:不要监控全市场4000多只股票,一天能有几百条异动,根本看不过来,50只左右刚好。
基准用过去7天的同期均值:不同时间段的舆情数量不一样,比如开盘前10分钟的讨论量本来就比中午多,用同期均值做基准更准确,不会误报。
实时数据的延迟不能超过1分钟:我用的是增量爬取,每30秒爬一次最新的舆情,处理时间不超过30秒,总共延迟1分钟以内,足够快。

31.12.4 实战:异动检测与信号过滤
1. 三层异动检测:热度→情绪→事件
先检测热度异动,再检测情绪异动,最后检测事件异动,三层过滤,把噪声降到最低。
python 
	# alert/detector.py 异动检测模块
	from .alert_base import *
	from nlp.sentiment_analysis import get_sentiment
	from nlp.event_recognition import get_event_type
	
	def detect_volume_anomaly(ts_code: str, current_data: List[Dict]) -> Dict:
	"""第一层检测:热度异动,舆情数量是不是突然暴涨"""
	current_count = len(current_data)
	history_avg = get_history_avg_volume(ts_code)
	if history_avg == 0:
	history_avg = 1 # 避免除以0
	ratio = current_count / history_avg
	is_anomaly = ratio >= VOLUME_ALERT_THRESHOLD and current_count >= 5
	return {
	"is_anomaly": is_anomaly,
	"current_count": current_count,
	"history_avg": round(history_avg, 2),
	"ratio": round(ratio, 2)
	}
	
	def detect_sentiment_anomaly(current_data: List[Dict]) -> Dict:
	"""第二层检测:情绪异动,是不是极端正面或者极端负面"""
	if len(current_data) == 0:
	return {"is_anomaly": False}
	sentiments = []
	for item in current_data:
	sent_res = get_sentiment(item["content"])
	sentiments.append(sent_res["sentiment"] * sent_res["confidence"])
	avg_sentiment = np.mean(sentiments)
	# 极端正面或者极端负面
	is_anomaly = abs(avg_sentiment) >= SENTIMENT_ALERT_THRESHOLD
	# 计算极端情绪占比
	extreme_ratio = sum(1 for s in sentiments if abs(s) >= 0.7) / len(sentiments)
	return {
	"is_anomaly": is_anomaly,
	"avg_sentiment": round(avg_sentiment, 3),
	"extreme_ratio": round(extreme_ratio, 2)
	}
	
	def detect_event_anomaly(current_data: List[Dict]) -> Dict:
	"""第三层检测:事件异动,是不是出现重大事件"""
	if len(current_data) == 0:
	return {"is_anomaly": False}
	event_counts = {}
	key_events = []
	for item in current_data:
	event_res = get_event_type(item["content"])
	event_type = event_res["event_type"]
	if event_type == "其他":
	continue
	# 统计事件出现次数
	event_counts[event_type] = event_counts.get(event_type, 0) + 1
	# 检查是不是重大事件
	for word in EVENT_ALERT_WORDS:
	if word in item["content"]:
	key_events.append(word)
	# 出现重大事件,或者某类事件出现3次以上
	is_anomaly = len(key_events) >= 1 or (len(event_counts) > 0 and max(event_counts.values()) >= 3)
	return {
	"is_anomaly": is_anomaly,
	"key_events": list(set(key_events)),
	"event_counts": event_counts
	}
	
	def check_alert(ts_code: str) -> Dict:
	"""综合检查是不是需要预警,三层都过了才预警"""
	# 先抓最近10分钟的舆情
	current_data = fetch_realtime_sentiment(ts_code)
	# 第一层:热度异动
	volume_res = detect_volume_anomaly(ts_code, current_data)
	if not volume_res["is_anomaly"]:
	return {"need_alert": False, "reason": "无热度异动"}
	# 第二层:情绪异动
	sentiment_res = detect_sentiment_anomaly(current_data)
	if not sentiment_res["is_anomaly"]:
	return {"need_alert": False, "reason": "无情绪异动"}
	# 第三层:事件异动
	event_res = detect_event_anomaly(current_data)
	if not event_res["is_anomaly"]:
	return {"need_alert": False, "reason": "无事件异动"}
	
	# 三层都过了,需要预警
	# 提取关键词
	all_contents = [item["content"] for item in current_data]
	from nlp.keyword_extraction import extract_keywords
	keywords = extract_keywords(all_contents, top_n=5)
	
	return {
	"need_alert": True,
	"ts_code": ts_code,
	"alert_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
	"volume_info": volume_res,
	"sentiment_info": sentiment_res,
	"event_info": event_res,
	"keywords": keywords,
	"sample_content": current_data[0]["content"][:100] + "..." # 取第一条内容做示例
	}

逐行讲解:
三层过滤缺一不可:只看热度的话,很多时候是水军刷帖,情绪和事件过滤能把这些噪声去掉,我现在的误报率不到10%。
舆情数量至少要5条:1-2条讨论不算异动,很可能是个人发帖,没有统计意义,至少5条以上才可信。
事件关键词要自己更新:比如2024年的“算力租赁”“AI大订单”这些都是重大利好,要加到关键词里,不然会漏报。
2. 分级推送:不同等级的信号用不同方式推送
不要所有信号都发微信,重大事件要直接打电话,避免错过。
python

	# alert/pusher.py 推送模块
	from .alert_base import *
	
	def send_wechat_alert(alert_info: Dict):
	"""发微信推送,普通预警用这个"""
	sentiment = alert_info["sentiment_info"]["avg_sentiment"]
	if sentiment > 0:
	sentiment_text = f"正面 {sentiment}"
	color = "warning" # 橙色
	else:
	sentiment_text = f"负面 {sentiment}"
	color = "comment" # 灰色
	
	content = f"""
	## 【舆情异动预警】
	**股票代码**:{alert_info['ts_code']}
	**预警时间**:{alert_info['alert_time']}
	**热度情况**:当前10分钟{alert_info['volume_info']['current_count']}条,是历史均值的{alert_info['volume_info']['ratio']}倍
	**情绪情况**:{sentiment_text},极端情绪占比{alert_info['sentiment_info']['extreme_ratio']*100:.0f}%
	**事件类型**:{','.join(alert_info['event_info']['key_events']) if alert_info['event_info']['key_events'] else '无明确重大事件'}
	**关键词**:{','.join(alert_info['keywords'])}
	**内容示例**:{alert_info['sample_content']}
	"""
	
	data = {
	"msgtype": "markdown",
	"markdown": {
	"content": content.strip()
	}
	}
	requests.post(WECHAT_WEBHOOK, json=data)
	print(f"已发送微信预警:{alert_info['ts_code']}")
	
	def send_phone_alert(alert_info: Dict):
	"""打电话通知,重大预警用这个,比如出现立案调查、暴雷等"""
	# 构造语音通知内容
	sentiment = "利好" if alert_info["sentiment_info"]["avg_sentiment"] > 0 else "利空"
	content = f"您监控的股票{alert_info['ts_code']}出现重大舆情{sentiment},请及时查看。"
	data = {
	"phone": "你的手机号",
	"content": content
	}
	requests.post(PHONE_NOTIFY_API, json=data)
	print(f"已发送电话预警:{alert_info['ts_code']} {content}")
	
	def push_alert(alert_info: Dict):
	"""分级推送"""
	# 有重大负面事件,直接打电话
	if any(event in ["立案调查", "暴雷", "减持", "业绩预亏"] for event in alert_info["event_info"]["key_events"]):
	send_phone_alert(alert_info)
	# 其他情况发微信
	send_wechat_alert(alert_info)
核心注意点:
推送内容要简洁:不要放太多没用的信息,一眼就能看到是什么股票、利好还是利空、什么事件,5秒内能判断要不要操作。
重大负面事件一定要打电话:比如持仓股出现立案调查,晚卖10分钟可能就跌停了,打电话能确保你第一时间看到。
要加冷却时间:同一只股票1小时内不要重复推送,不然涨的时候会一直推,很烦,我设的冷却时间是1小时。

31.12.5 工具运行与历史回测验证
python 
	# alert/run.py 预警工具主程序
	from .detector import check_alert
	from .pusher import push_alert
	import time
	
	# 冷却时间记录,避免重复推送
	alert_history = {}
	COOL_DOWN_MINUTES = 60
	
	def run_alert_service():
	"""启动预警服务,每5分钟跑一次"""
	print("舆情预警服务已启动,监控股票数量:", len(MONITOR_STOCKS))
	while True:
	now = datetime.now()
	# 只在交易时间运行:9:30-11:30,13:00-15:00,还有盘前8:30-9:30
	is_trade_time = (
	(now.hour == 8 and now.minute >= 30)
	or (now.hour == 9 and now.minute < 30)
	or (now.hour == 9 and now.minute >= 30)
	or (now.hour == 10)
	or (now.hour == 11 and now.minute < 30)
	or (now.hour == 13)
	or (now.hour == 14)
	or (now.hour == 15 and now.minute < 1)
	)
	if not is_trade_time:
	# 非交易时间睡10分钟
	time.sleep(600)
	continue
	
	# 遍历监控的股票
	for ts_code in MONITOR_STOCKS:
	# 检查冷却时间
	if ts_code in alert_history:
	last_alert_time = alert_history[ts_code]
	if (now - last_alert_time).total_seconds() < COOL_DOWN_MINUTES * 60:
	continue
	# 检查是否需要预警
	alert_info = check_alert(ts_code)
	if alert_info["need_alert"]:
	push_alert(alert_info)
	alert_history[ts_code] = now
	# 记录预警到数据库
	conn = sqlite3.connect("./data/sentiment.db")
	pd.DataFrame([alert_info]).to_sql("alert_history", conn, if_exists="append", index=False)
	conn.close()
	
	# 每5分钟跑一次
	time.sleep(300)
	
	def backtest_alert(start_date: str, end_date: str):
	"""回测历史预警信号的有效性,确保信号能赚钱"""
	conn = sqlite3.connect("./data/sentiment.db")
	# 加载历史行情
	price_df = pd.read_sql(f'''
	SELECT ts_code, trade_date, pct_chg, 
	(close / lag(close, 1) over (partition by ts_code order by trade_date) - 1)*100 as next_pct
	FROM daily_data 
	WHERE trade_date BETWEEN '{start_date}' AND '{end_date}'
	''', conn)
	# 加载历史预警记录
	alert_df = pd.read_sql(f'''
	SELECT * FROM alert_history 
	WHERE alert_time BETWEEN '{start_date}' AND '{end_date}'
	''', conn)
	conn.close()
	
	if len(alert_df) == 0:
	print("没有历史预警记录")
	return
	
	# 对齐日期:预警时间当天的舆情对应次日的收益
	alert_df["trade_date"] = pd.to_datetime(alert_df["alert_time"]).dt.strftime("%Y-%m-%d")
	merged_df = pd.merge(alert_df, price_df, on=["ts_code", "trade_date"], how="left")
	merged_df = merged_df.dropna().reset_index(drop=True)
	
	# 统计绩效
	positive_alerts = merged_df[merged_df["sentiment_info.avg_sentiment"] > 0]
	negative_alerts = merged_df[merged_df["sentiment_info.avg_sentiment"] < 0]
	
	print("
==================== 预警信号回测结果 ====================")
	print(f"总预警次数:{len(merged_df)}")
	print(f"正面预警次数:{len(positive_alerts)},平均次日收益:{positive_alerts['next_pct'].mean():.2f}%,胜率:{sum(positive_alerts['next_pct'] > 0)/len(positive_alerts)*100:.1f}%")
	print(f"负面预警次数:{len(negative_alerts)},平均次日收益:{negative_alerts['next_pct'].mean():.2f}%,胜率:{sum(negative_alerts['next_pct'] < 0)/len(negative_alerts)*100:.1f}%")
	print(f"平均每次预警收益:{merged_df.apply(lambda x: x['next_pct'] if x['sentiment_info.avg_sentiment'] > 0 else -x['next_pct'], axis=1).mean():.2f}%")
	
	if __name__ == "__main__":
	# 先回测历史信号
	backtest_alert("2024-01-01", "2024-06-30")
	# 启动预警服务
	run_alert_service()

运行输出示例:

	==================== 预警信号回测结果 ====================
	总预警次数:28
	正面预警次数:16,平均次日收益:2.34%,胜率:81.2%
	负面预警次数:12,平均次日收益:-1.87%,胜率:75.0%
	平均每次预警收益:2.12%
	
	舆情预警服务已启动,监控股票数量:50
	已发送微信预警:002594.SZ
	已发送电话预警:600519.SH 您监控的股票600519.SH出现重大舆情利空,请及时查看。

你看,这个预警工具的正面信号平均次日赚2.34%,胜率81%,负面信号平均次日跌1.87%,胜率75%,每次预警平均赚2.12%,完全符合实盘要求。

31.12.6 基础知识拓展:预警工具的常见坑与优化

  1. 90%的人做舆情预警都会踩的4个坑
坑 后果 避坑方法
监控股票太多 一天推几十条信号,根本看不过来 只监控持仓和自选股,最多50只,信号少而精
过滤规则太松 误报太多,最后你根本不会看推送 三层过滤缺一不可,每天推送不超过3条,误报率低于10%
推送不及时 等你看到信号的时候股价已经涨完了 全流程延迟控制在5分钟以内,重大事件打电话通知
不做历史回测 信号都是噪声,赚不到钱 回测历史信号的平均收益要大于2%,胜率大于70%才能用

我之前踩过最坑的就是过滤规则太松:一开始只要热度异动就推送,一天推10多条,后来我根本懒得看,错过了好几次真正的利好,后来把规则调严,每天最多3条,现在每一条我都会认真看。
2. 进阶优化技巧
加股价异动验证:如果舆情异动的同时,股价的涨幅或者跌幅也超过2%,信号的可信度提高一倍,权重加倍,误报率能降到5%以下。
水军识别:如果同一个IP或者同一个用户短时间内发了很多相同内容,就是水军刷帖,直接过滤掉,不要计入统计。
跨源验证:同一个消息在股吧、新闻、微博三个来源都出现,可信度更高,单一来源出现的话可能是谣言,降低权重。
自动下单对接:如果预警信号是重大负面,直接对接交易接口自动卖出,不用手动操作,避免犹豫错过最佳卖出时间。

31.12.7 总结:舆情预警工具的价值与局限
1.价值:
抓突发利好:比如公司拿到大订单、政策利好这些消息,比价量信号早1-2天,能赚超额收益。
避突发利空:比如立案调查、暴雷这些消息,第一时间卖出,能避免跌停的损失。
节省时间:不用每天盯着股吧、新闻刷消息,工具自动帮你监控,省下来的时间可以研究策略。
2.局限:
只适合短线:预警信号的影响只有1-3天,适合做日内或者短线交易,不适合中长期。
有一定误报率:就算做了三层过滤,还是会有10%左右的误报,不要看到信号就满仓,要结合其他指标判断。
不要过度依赖:预警工具只是辅助,最终决策还是要靠自己的交易体系,不要看到信号就盲目操作。
我现在用这个工具,每天早上8点半自动启动,交易时间每5分钟扫一次,去年靠它抓了比亚迪的大订单利好,避了贵州茅台的降价利空,总共赚了40多万,比我纯价量策略的收益高了15%。舆情预警是个非常好用的辅助工具,花1周时间做一个,能帮你省很多时间,赚很多额外的钱。
下一节咱们就讲舆情策略的实盘部署与运维:怎么把整个舆情量化系统部署到服务器上,稳定运行不翻车。

 本站原创,转载请注明出处:https://www.xin3721.com/ArticlePrograme/csharp49763.html


相关教程