news 2026/5/21 12:44:28

【期货量化进阶】期货量化交易中的情绪分析(实战技巧)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【期货量化进阶】期货量化交易中的情绪分析(实战技巧)

一、前言

市场情绪是影响价格波动的重要因素。通过分析市场情绪,可以更好地理解市场行为,提高策略的准确性。本文将介绍如何量化分析市场情绪并应用于交易策略。

本文将介绍:

二、为什么选择天勤量化(TqSdk)

TqSdk情绪分析支持:

功能说明
实时数据支持获取实时行情数据
历史数据支持获取历史数据
数据处理pandas/numpy支持数据处理
灵活扩展支持自定义情绪指标

安装方法

pipinstalltqsdk pandas numpy

三、市场情绪指标

3.1 情绪指标类型

指标类型说明数据来源
持仓情绪多空持仓比例持仓量数据
价格情绪价格波动特征价格数据
成交量情绪成交量变化成交量数据
波动率情绪市场恐慌程度波动率数据

3.2 情绪指标应用

应用说明
趋势判断判断市场趋势
反转识别识别市场反转
风险预警预警市场风险
策略优化优化交易策略

四、持仓情绪分析

4.1 持仓量分析

#!/usr/bin/env python# -*- coding: utf-8 -*-""" 功能:市场情绪分析 说明:本代码仅供学习参考 """fromtqsdkimportTqApi,TqAuthimportpandasaspdimportnumpyasnpdefanalyze_open_interest_sentiment(klines):"""分析持仓量情绪"""# 持仓量变化oi_change=klines['open_oi'].pct_change()# 持仓量与价格关系price_change=klines['close'].pct_change()# 持仓情绪指标sentiment=pd.DataFrame(index=klines.index)sentiment['oi_change']=oi_change sentiment['price_change']=price_change# 持仓量增加且价格上涨:看涨情绪sentiment['bullish']=((oi_change>0)&(price_change>0)).astype(int)# 持仓量增加且价格下跌:看跌情绪sentiment['bearish']=((oi_change>0)&(price_change<0)).astype(int)# 持仓量减少:平仓情绪sentiment['closing']=(oi_change<0).astype(int)returnsentiment# 使用示例api=TqApi(auth=TqAuth("快期账户","快期密码"))klines=api.get_kline_serial("SHFE.rb2510",3600,500)api.wait_update()sentiment=analyze_open_interest_sentiment(klines)print(f"看涨情绪:{(sentiment['bullish']==1).sum()}")print(f"看跌情绪:{(sentiment['bearish']==1).sum()}")api.close()

4.2 多空持仓比

defcalculate_long_short_ratio(klines):"""计算多空持仓比(简化处理)"""# 实际应用中需要获取多空持仓数据# 这里用价格和持仓量变化来估算price_change=klines['close'].pct_change()oi_change=klines['open_oi'].pct_change()# 价格上涨且持仓增加:多头占优long_strength=((price_change>0)&(oi_change>0)).astype(int)# 价格下跌且持仓增加:空头占优short_strength=((price_change<0)&(oi_change>0)).astype(int)# 计算多空比long_short_ratio=long_strength.rolling(20).sum()/(short_strength.rolling(20).sum()+1)returnlong_short_ratio# 使用示例long_short_ratio=calculate_long_short_ratio(klines)print(f"当前多空比:{long_short_ratio.iloc[-1]:.2f}")

五、价格情绪分析

5.1 价格波动情绪

defanalyze_price_sentiment(klines):"""分析价格波动情绪"""returns=klines['close'].pct_change()sentiment=pd.DataFrame(index=klines.index)# 波动率volatility=returns.rolling(20).std()sentiment['volatility']=volatility# 恐慌指数(高波动率)sentiment['fear']=(volatility>volatility.quantile(0.8)).astype(int)# 贪婪指数(低波动率)sentiment['greed']=(volatility<volatility.quantile(0.2)).astype(int)# 价格动量momentum=returns.rolling(5).sum()sentiment['momentum']=momentum# 趋势强度trend_strength=abs(momentum)/volatility sentiment['trend_strength']=trend_strengthreturnsentiment# 使用示例price_sentiment=analyze_price_sentiment(klines)print(f"恐慌指数:{price_sentiment['fear'].iloc[-1]}")print(f"贪婪指数:{price_sentiment['greed'].iloc[-1]}")

5.2 价格位置情绪

defanalyze_price_position_sentiment(klines,window=20):"""分析价格位置情绪"""high_max=klines['high'].rolling(window).max()low_min=klines['low'].rolling(window).min()# 价格位置(0-1之间)price_position=(klines['close']-low_min)/(high_max-low_min)sentiment=pd.DataFrame(index=klines.index)sentiment['price_position']=price_position# 超买情绪(价格在高位)sentiment['overbought']=(price_position>0.8).astype(int)# 超卖情绪(价格在低位)sentiment['oversold']=(price_position<0.2).astype(int)# 中性情绪sentiment['neutral']=((price_position>=0.3)&(price_position<=0.7)).astype(int)returnsentiment# 使用示例position_sentiment=analyze_price_position_sentiment(klines)print(f"超买情绪:{position_sentiment['overbought'].iloc[-1]}")print(f"超卖情绪:{position_sentiment['oversold'].iloc[-1]}")

六、成交量情绪分析

6.1 成交量情绪

defanalyze_volume_sentiment(klines):"""分析成交量情绪"""volume=klines['volume']volume_ma=volume.rolling(20).mean()sentiment=pd.DataFrame(index=klines.index)# 成交量比率volume_ratio=volume/volume_ma sentiment['volume_ratio']=volume_ratio# 放量情绪sentiment['high_volume']=(volume_ratio>1.5).astype(int)# 缩量情绪sentiment['low_volume']=(volume_ratio<0.5).astype(int)# 价量关系price_change=klines['close'].pct_change()price_volume_corr=price_change.rolling(20).corr(volume.pct_change())sentiment['price_volume_corr']=price_volume_corr# 价量配合(价格上涨且放量)sentiment['bullish_volume']=((price_change>0)&(volume_ratio>1.2)).astype(int)# 价量背离(价格上涨但缩量)sentiment['divergence']=((price_change>0)&(volume_ratio<0.8)).astype(int)returnsentiment# 使用示例volume_sentiment=analyze_volume_sentiment(klines)print(f"放量情绪:{volume_sentiment['high_volume'].iloc[-1]}")print(f"价量配合:{volume_sentiment['bullish_volume'].iloc[-1]}")

七、综合情绪指标

7.1 情绪综合评分

defcalculate_sentiment_score(klines):"""计算综合情绪评分"""# 获取各项情绪指标oi_sentiment=analyze_open_interest_sentiment(klines)price_sentiment=analyze_price_sentiment(klines)position_sentiment=analyze_price_position_sentiment(klines)volume_sentiment=analyze_volume_sentiment(klines)# 综合评分(-100到100)sentiment_score=pd.Series(0.0,index=klines.index)# 持仓情绪(权重0.2)sentiment_score+=(oi_sentiment['bullish']-oi_sentiment['bearish'])*20# 价格情绪(权重0.3)momentum=price_sentiment['momentum']sentiment_score+=np.sign(momentum)*abs(momentum)*30# 位置情绪(权重0.2)position=position_sentiment['price_position']sentiment_score+=(position-0.5)*40# 成交量情绪(权重0.3)volume_ratio=volume_sentiment['volume_ratio']price_change=klines['close'].pct_change()sentiment_score+=np.sign(price_change)*(volume_ratio-1)*30# 归一化到-100到100sentiment_score=np.clip(sentiment_score,-100,100)returnsentiment_score# 使用示例sentiment_score=calculate_sentiment_score(klines)print(f"当前情绪评分:{sentiment_score.iloc[-1]:.2f}")ifsentiment_score.iloc[-1]>50:print("市场情绪:极度看涨")elifsentiment_score.iloc[-1]>20:print("市场情绪:看涨")elifsentiment_score.iloc[-1]<-50:print("市场情绪:极度看跌")elifsentiment_score.iloc[-1]<-20:print("市场情绪:看跌")else:print("市场情绪:中性")

7.2 情绪趋势

defanalyze_sentiment_trend(sentiment_score,window=20):"""分析情绪趋势"""sentiment_ma=sentiment_score.rolling(window).mean()sentiment_std=sentiment_score.rolling(window).std()# 情绪趋势trend=pd.DataFrame(index=sentiment_score.index)trend['score']=sentiment_score trend['ma']=sentiment_ma trend['std']=sentiment_std# 情绪变化trend['change']=sentiment_score.diff()# 情绪强度trend['strength']=abs(sentiment_score)/100# 情绪方向trend['direction']=np.sign(sentiment_score)returntrend# 使用示例sentiment_trend=analyze_sentiment_trend(sentiment_score)print(f"情绪趋势:{sentiment_trend['ma'].iloc[-1]:.2f}")print(f"情绪强度:{sentiment_trend['strength'].iloc[-1]:.2%}")

八、情绪交易策略

8.1 情绪反转策略

defsentiment_reversal_strategy(api,symbol):"""情绪反转策略"""klines=api.get_kline_serial(symbol,3600,500)api.wait_update()sentiment_score=calculate_sentiment_score(klines)current_sentiment=sentiment_score.iloc[-1]prev_sentiment=sentiment_score.iloc[-2]# 极度看涨后反转ifprev_sentiment>80andcurrent_sentiment<60:return-1# 卖出# 极度看跌后反转elifprev_sentiment<-80andcurrent_sentiment>-60:return1# 买入return0# 使用示例api=TqApi(auth=TqAuth("快期账户","快期密码"))signal=sentiment_reversal_strategy(api,"SHFE.rb2510")print(f"交易信号:{signal}")api.close()

8.2 情绪趋势策略

defsentiment_trend_strategy(api,symbol):"""情绪趋势策略"""klines=api.get_kline_serial(symbol,3600,500)api.wait_update()sentiment_score=calculate_sentiment_score(klines)sentiment_ma=sentiment_score.rolling(20).mean()current_sentiment=sentiment_score.iloc[-1]current_ma=sentiment_ma.iloc[-1]prev_ma=sentiment_ma.iloc[-2]# 情绪向上突破ifcurrent_sentiment>current_maandprev_sentiment<=prev_ma:return1# 买入# 情绪向下突破elifcurrent_sentiment<current_maandprev_sentiment>=prev_ma:return-1# 卖出return0

九、情绪监控系统

9.1 实时情绪监控

classSentimentMonitor:"""情绪监控系统"""def__init__(self,api,symbol):self.api=api self.symbol=symbol self.klines=Noneself.sentiment_history=[]defupdate_sentiment(self):"""更新情绪"""ifself.klinesisNone:self.klines=self.api.get_kline_serial(self.symbol,3600,500)else:self.api.wait_update()sentiment_score=calculate_sentiment_score(self.klines)current_sentiment=sentiment_score.iloc[-1]self.sentiment_history.append({'time':self.klines.index[-1],'sentiment':current_sentiment})returncurrent_sentimentdefget_sentiment_alert(self,threshold=80):"""获取情绪预警"""current_sentiment=self.update_sentiment()ifabs(current_sentiment)>threshold:ifcurrent_sentiment>threshold:return"极度看涨预警"else:return"极度看跌预警"returnNone# 使用示例api=TqApi(auth=TqAuth("快期账户","快期密码"))monitor=SentimentMonitor(api,"SHFE.rb2510")whileTrue:alert=monitor.get_sentiment_alert()ifalert:print(f"情绪预警:{alert}")time.sleep(60)

十、总结

10.1 情绪分析要点

要点说明
多维度分析从多个维度分析情绪
综合评分使用综合评分系统
趋势识别识别情绪趋势
策略应用将情绪分析应用于策略

10.2 注意事项

  1. 数据质量- 确保数据准确
  2. 指标选择- 选择有效指标
  3. 避免过拟合- 避免过度优化
  4. 持续监控- 持续监控情绪变化

免责声明:本文仅供学习交流使用,不构成任何投资建议。期货交易有风险,入市需谨慎。

更多资源

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/19 11:35:20

本地化部署哪个AI大模型运行结果最靠谱?

一.为什么要进行AI大模型的本地化部署&#xff1f; 日常工作中&#xff0c;需要紧急处理的公司事务&#xff0c;需要 AI 帮忙分析提高处理速度和效率&#xff0c;但是由于文件涉密...不能把内容传到AI平台&#xff1b;出差乘机&#xff0c;正好想到好点子要优化方案&#xff0…

作者头像 李华
网站建设 2026/5/21 14:10:50

【硬件】片选 低电平

“片选 低电平有效”的意思是&#xff1a;这根 CS/SS/片选 信号线在 电平为 0&#xff08;低电平&#xff09; 的时候&#xff0c;设备才会被选中、才会响应总线&#xff1b;当它是 1&#xff08;高电平&#xff09; 时&#xff0c;设备不响应&#xff0c;相当于“没被选中”。…

作者头像 李华
网站建设 2026/5/21 9:46:28

对比全职与兼职成本,灵活性,给出纯兼职,更省钱安案。

1️⃣ 实际应用场景描述 & 痛点引入在智能制造与数字化工厂领域&#xff0c;企业常面临用人模式的选择&#xff1a;- 全职员工&#xff1a;稳定性高&#xff0c;响应快&#xff0c;但人力成本高&#xff08;社保、福利、办公空间等&#xff09;。- 兼职/自由职业者&#xf…

作者头像 李华