如何实施兴登堡预兆指标?

Sky*_*ker 5 python finance numpy pandas technical-indicator

此处定义的兴登堡预兆指标为:

股市指数每日新高 52 周高点和新低 52 周低点的数量超过阈值(通常为 2.2%)。

对我来说,这意味着,我们每天滚动并回顾 52 周或 252 个业务/交易日,然后计算高点(或低点)的数量,最后计算该回报或 pct_change,即新高(或低点)的比率)他们想要监控,例如高于 2.2%

import pandas as pd
import numpy as np
import yfinance as yf

# download the S&P500 
df = yf.download('^GSPC')
# compute the "highs" and "lows"
df['Highs'] = df['Close'].rolling(252).apply(lambda x: x.cummax().diff().
    apply(lambda x: np.where(x > 0, 1, 0)).sum()).pct_change()
df['Lows'] = df['Close'].rolling(252).apply(lambda x: x.cummin().diff().
    apply(lambda x: np.where(x < 0, 1, 0)).sum()).pct_change()
Run Code Online (Sandbox Code Playgroud)

我们的理解是一样的吗?有更好的方法吗?

Dav*_*veB 1

有趣的问题!我可以建议以下代码吗?它的运行速度比解决方案快得多apply,因为它是矢量化的,并且还更清楚地列出了步骤,以便您可以检查临时结果。

我得到了与您的代码不同的结果 - 您可以通过在底部的时间序列上绘制结果来进行比较。

import pandas as pd
import numpy as np
import yfinance as yf

# download the S&P500 
df = yf.download('^GSPC')

# Constants
n_trading_day_window = 252

# Simplify the input dataframe to only the relevant column
df_hin_omen = df[['Close']]
# Calculate rolling highs and lows
df_hin_omen.insert(1, 'rolling_high', df_hin_omen['Close'].rolling(n_trading_day_window).max())
df_hin_omen.insert(2, 'rolling_low', df_hin_omen['Close'].rolling(n_trading_day_window).min())
# High and low are simply when the given row matches the 252 day high or low
df_hin_omen.insert(3, 'is_high', df_hin_omen.Close == df_hin_omen.rolling_high)
df_hin_omen.insert(4, 'is_low', df_hin_omen.Close == df_hin_omen.rolling_low)
# Calculate rolling percentages
df_hin_omen.insert(5, 'percent_highs', df_hin_omen.is_high.rolling(n_trading_day_window).sum() / n_trading_day_window)
df_hin_omen.insert(6, 'percent_lows', df_hin_omen.is_low.rolling(n_trading_day_window).sum() / n_trading_day_window)
Run Code Online (Sandbox Code Playgroud)

运行后,您可以按如下方式检查结果:

import matplotlib, matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(16, 6))
df_hin_omen.resample('w').mean().percent_highs.plot(ax=ax)
df_hin_omen.resample('w').mean().percent_lows.plot(ax=ax)
Run Code Online (Sandbox Code Playgroud)

根据兴登堡预兆的定义,“兴登堡预兆寻找与以下前提的统计偏差:在正常情况下,某些股票要么创出 52 周新高,要么创出 52 周新低。如果两者都发生在同时。”

因此,从我们的图表来看,我的解释是,股市目前收盘于许多 52 周高点,但并未出现许多 52 周低点。另请注意,引用的文章指出,“据报道,它仅在 25% 的情况下正确预测了股市大幅下跌。” 所以我不确定我们是否可以对此进行过多的解读......

在此输入图像描述

编辑

我查看了您的代码,我认为该函数的使用不pct_change正确 - 这将计算滚动差异的变化,因此从 0.10% 到 0.11% 的移动实际上相当于 10 % 改变。相反,您需要过去一年的滚动总和,并将其除以一年中的天数,根据我上面的代码。