本文主要是介绍JQData | 利用区间极值法对牛熊市进行简单划分,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
利用JQdata获取市场(股票)历史时间段处于牛市状态还是熊市状态
转自 https://www.joinquant.com/post/15536?tag=algorithm
如题,牛市和熊市的交易者心理预期与交易习惯可能是不相同的,为了方便统计不同市场情绪下市场,可以使用历史数据进行简单划分,也可以大致判断目前市场走势处于一个什么状态之中
import numpy as np import pandas as pd from scipy.signal import argrelextrema from jqdatasdk import * auth('账号','密码')
data = get_price('000001.XSHG',start_date='2007-01-01',end_date='2018-11-18') # data.to_csv('000001.csv') # data = pd.read_csv('000001.csv') #为防止意外可以先将数据储存下来
def get_bull_or_bear(series,order=100):'''获取时间区间所处的牛熊市状态传入: series如close, order代表划分前后追朔的数据量,数据量越大,精度越小返回: 交易日的牛熊市的分类,series'''# 利用scipy在前后order个交易日内寻找极值点x=series.valueshigh = argrelextrema(x,np.greater,order=order)[0]low = argrelextrema(x,np.less,order=order)[0]high_s = pd.Series('high',series.iloc[high].index)low_s = pd.Series('low',series.iloc[low].index)data1 = pd.concat([high_s,low_s]).sort_index()other = []for i in range(len(data1)-1): #去除重复值划分if data1.iloc[i]==data1.iloc[i+1]:other.append(data1.index[i])data1.drop(other,inplace=True)data1[series.index[-1]] = data1.iloc[-2] #加上开头与结束的归类data1[series.index[0]] = data1.iloc[1]data1.sort_index(inplace=True) # 获得牛熊分界点bull_data = pd.Series(False,series.index,name='is_bull') #获得每一交易日属于牛市期还是熊市期if data1[0]=='high': is_bull =False else:is_bull=Truefor i in range(len(data1)-1):if is_bull:bull_data[data1.index[i]:data1.index[i+1]] = Trueis_bull=Falseelse:is_bull=Truereturn bull_data
bull_data = get_bull_or_bear(data.close,100) bull_data.value_counts()
False 1761 True 1128 Name: is_bull, dtype: int64
ax = bull_data.plot(style='-',figsize=(17,5)) data.close.plot(secondary_y=True,ax=ax)
<matplotlib.axes._subplots.AxesSubplot at 0x7fe302f34790>
bull_data = get_bull_or_bear(data.close,50) ax = bull_data.plot(style='-',figsize=(17,5)) data.close.plot(secondary_y=True,ax=ax)
<matplotlib.axes._subplots.AxesSubplot at 0x7fe309a63650>
# 很长时间我们可能会沉浸在牛市或者熊市的状态中,实际上早已脱离牛市(熊市),所以使用ema指标简单模拟何时我们发现离开了牛市(熊市) series = pd.ewma(data.close,span=50) bull_data = get_bull_or_bear(series,100) ax = bull_data.plot(style='-',figsize=(17,5)) data.close.plot(secondary_y=True,ax=ax) series.plot(secondary_y=True,ax=ax)
/opt/conda/envs/python2new/lib/python2.7/site-packages/ipykernel_launcher.py:2: FutureWarning: pd.ewm_mean is deprecated for Series and will be removed in a future version, replace with Series.ewm(ignore_na=False,span=50,min_periods=0,adjust=True).mean()
<matplotlib.axes._subplots.AxesSubplot at 0x7fe309d16350>
这篇关于JQData | 利用区间极值法对牛熊市进行简单划分的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!