一、前言
市场情绪是影响价格波动的重要因素。通过分析市场情绪,可以更好地理解市场行为,提高策略的准确性。本文将介绍如何量化分析市场情绪并应用于交易策略。
本文将介绍:
- 市场情绪指标
- 情绪数据获取
- 情绪分析方法
- 情绪交易策略
- 情绪监控系统
二、为什么选择天勤量化(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 注意事项
- 数据质量- 确保数据准确
- 指标选择- 选择有效指标
- 避免过拟合- 避免过度优化
- 持续监控- 持续监控情绪变化
免责声明:本文仅供学习交流使用,不构成任何投资建议。期货交易有风险,入市需谨慎。
更多资源:
- 天勤量化官网:https://www.shinnytech.com
- GitHub开源地址:https://github.com/shinnytech/tqsdk-python
- 官方文档:https://doc.shinnytech.com/tqsdk/latest