首页  

沪深300指数 bias250 z20 z250 分析     所属分类 quant 浏览量 200
z20  20日 zscore 
z250  250日 zscore 


import pandas as pd
import matplotlib.pyplot as plt  
from datetime import datetime

    
df = pd.read_csv('/data/hs300.txt')
df['ma250'] = df['close'].rolling(window=250).mean()
df['std250'] = df['close'].rolling(window=250).std()

df['ma20'] = df['close'].rolling(window=20).mean()
df['std20'] = df['close'].rolling(window=20).std()

df['bias250'] = (df['close'] - df['ma250']) * 100 / df['ma250'] 

df['z250'] = (df['close'] - df['ma250']) / df['std250']
df['z20'] = (df['close'] - df['ma20']) / df['std20']

# 根据日期过滤
# df = df[df['date'] >='2020-01-01']
# 转成日期
df['dt']= pd.to_datetime(df['date'])
# 设置索引
df.set_index('dt')

# df[['bias250']].plot()
plt.plot(df['dt'],df['close'],color='k',label='close')

# 买入信号
buymask = df[df['bias250']< -15 ]
print(buymask.shape)
buymask = buymask[buymask['z20'] < -2]
print(buymask.shape)
plt.plot(buymask['dt'],buymask['close'],color='red',linestyle='',marker='o')


# 卖出信号
sellmask = df[df['bias250'] > 20 ]
sellmask = sellmask[sellmask['z20'] > 2]

plt.plot(sellmask['dt'],sellmask['close'],color='g',linestyle='',marker='o')

# plt.xticks(rotation=45)
# x轴日期自适应 避免重叠
plt.gcf().autofmt_xdate()
plt.legend()
plt.show()

# bias250
plt.plot(df['dt'],df['bias250'],label='bias250')
# plt.gca() 获当前 Axes 对象
ax = plt.gca()
    
# 添加 bias250 上下阈值线 
ax.axhline(-15, color='red', linestyle='--')
ax.axhline(20, color='red', linestyle='--') 

# plt.xticks(rotation=45)
# x轴日期自适应 避免重叠
plt.gcf().autofmt_xdate()
plt.legend()
plt.show()


# z250

plt.plot(df['dt'],df['z250'],label='z250')
ax = plt.gca()
# plt.gca() 获当前 Axes 对象
ax = plt.gca()
    
# 添加 z250 上下阈值线 
ax.axhline(-2, color='red', linestyle='--')
ax.axhline(2, color='red', linestyle='--')
plt.gcf().autofmt_xdate()
plt.legend()
plt.show()



# z20
plt.plot(df['dt'],df['z20'],label='z20')
ax = plt.gca()
# plt.gca() 获当前 Axes 对象
ax = plt.gca()
    
# 添加 z20 上下阈值线 
ax.axhline(-2, color='red', linestyle='--')
ax.axhline(2, color='red', linestyle='--')
plt.gcf().autofmt_xdate()
plt.legend()
plt.show()



# close  z250 双轴图



fig, ax1 = plt.subplots ()
ax2 = ax1.twinx ()
ax1.plot(df.index,df['close'], 'b-') 
ax2.plot(df.index,df['z250'], 'r-') 

ax1.set_ylabel('close', color='b')
ax2.set_ylabel('z250', color='r')

plt.show()

上一篇     下一篇
matplot 基本用法

pandas matplot 读取日线数据,滚动计算bias250 添加阈值线

pandas matplot 画图 超出阈值 变颜色

聚宽 沪深300指数 数据读取分析

油车 电车 使用成本

pandas read_csv 和 to_csv 索引问题