首页  

zscore因子计算及策略回测     所属分类 quant 浏览量 212
Techical Analysis of Stock & Commodities
Z-score: How to use it in Trading

Z-score 计算公式
Z = (X - μ) / σ
μ 均值
σ 标准差,也称波动率

假设 X 服从正态分布 
3个标准差(σ)原则,或者68-95-99.7原则

pandas 滚动计算  Z-score

def rolling_zscore(s, win=20):
    ma = s.rolling(window=win).mean()
    std = s.rolling(window=win).std()
    return (s - ma)/std

rolling_mean = close_prices.rolling(window=period).mean()
rolling_std = close_prices.rolling(window=period).std()
z_scores = (close_prices - rolling_mean) / rolling_std


计算最近 250 天的 zscore, 买点 zscore 小于-2  ,卖点 zscore 大于 2 
布林通道 上下轨  均值 ± 2个标准差

z-score 因子的有效性来源于正态分布的假设
然而,股价的波动并不符合正态分布



import pandas as pd import matplotlib.pyplot as plt # 常量 Z_THRESH = 2 PERIODS = [30, 60, 90] TICKER_SYMBOL = "hs300" START_DATE = '2020-1-1' # END_DATE 暂不使用 END_DATE = '2023-12-25' def fetch_data(ticker_symbol, start_date, end_date): """Fetches historical data for a given ticker symbol.""" # ticker_data = yf.Ticker(ticker_symbol) # 不使用 yfinance ,读取本地文件 # /demo/myweb2020/docs/Q/data/hs300 ticker_data = pd.read_csv('/Users/dugang/tmp/hs300.txt') # return ticker_data.history(period='1d', start=start_date, end=end_date) ticker_data = ticker_data[ticker_data['date']>=start_date] return ticker_data def calculate_z_scores(close_prices, periods): """Calculates Z-scores for given periods.""" z_scores_dict = {} for period in periods: # 计算给定周期的滚动平均值 rolling_mean = close_prices.rolling(window=period).mean() # 计算给定周期的滚动标准差 rolling_std = close_prices.rolling(window=period).std() # 计算收盘价的Z值 z_scores = (close_prices - rolling_mean) / rolling_std # 将Z值存储在以周期为关键字的字典中 z_scores_dict[period] = z_scores return z_scores_dict def plot_data(close_prices, z_scores_data): """Plots close prices and z-scores.""" # 为收盘价和Z值创建子图 fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(20, 8)) # 在第一个子图上绘制收盘价 ax1.plot(close_prices.index, close_prices, label='Close Prices') for period, z_scores in z_scores_data.items(): # 在第二个子图上绘制每个时期的Z值 ax2.plot(z_scores.index, z_scores, label=f'Z-Scores {period} days', alpha=0.7) # 如果周期是列表中的第一个,则在第一个子图上绘制买入/卖出信号 if period == PERIODS[0]: buy_signals = (z_scores < -Z_THRESH) sell_signals = (z_scores > Z_THRESH) ax1.plot(close_prices[buy_signals].index, close_prices[buy_signals], 'o', color='g', label='Buy Signal') ax1.plot(close_prices[sell_signals].index, close_prices[sell_signals], 'o', color='r', label='Sell Signal') # 为收盘价子图设置y标签和图例 ax1.set_ylabel('Close Prices') ax1.legend(loc="upper left") ax1.grid(True) # 在Z值子图上绘制表示Z值阈值的水平线 ax2.axhline(-Z_THRESH, color='red', linestyle='--') ax2.axhline(Z_THRESH, color='red', linestyle='--') # 设置Z值子图的Y标签和图例 ax2.set_ylabel('Z-Scores') ax2.legend(loc="upper left") ax2.grid(True) # 为整个绘图设置主标题 plt.suptitle(f'{TICKER_SYMBOL} Close Prices and Z-Scores {Z_THRESH} Treshold') # 显示图表 plt.show() # 获取股票代码的历史数据 ticker_data = fetch_data(TICKER_SYMBOL, START_DATE, END_DATE) # 计算指定时期的Z值 z_scores_data = calculate_z_scores(ticker_data['close'], PERIODS) # 绘制收盘价和Z值 plot_data(ticker_data['close'], z_scores_data)
日线数据接口 由歪枣网提供 http://waizaowang.com/api/detail/1007 date,open,close,high,low,a,v 2005-01-04,994.77,982.79,994.77,980.66,7412870.0,4431980032 2005-01-05,981.58,992.56,997.32,979.88,7119110.0,4529209856 2005-01-06,993.33,983.17,993.79,980.33,6288030.0,3921019904 沪深300 http://api.waizaowang.com/doc/getIndexDayKLine?code=000300&ktype=101&startDate=1990-01-01&endDate=2100-01-01&fields=tdate,open,close,high,low,cjl,cje&export=0&token=xxx token 注册账号 登录后获取

上一篇     下一篇
Python数据分析中的统计学基础概念

数学公式中的希腊字母

温和世界 和 疯狂世界

Python统计学极简入门笔记 01 统计学简介

Python统计学极简入门笔记 02 描述性统计

Python统计学极简入门笔记 03 数据分布