PandasTA 源码解析(八)

.\pandas-ta\pandas_ta\momentum\__init__.py

# 设置文件编码为 UTF-8
# 导入 ao 指标
from .ao import ao
# 导入 apo 指标
from .apo import apo
# 导入 bias 指标
from .bias import bias
# 导入 bop 指标
from .bop import bop
# 导入 brar 指标
from .brar import brar
# 导入 cci 指标
from .cci import cci
# 导入 cfo 指标
from .cfo import cfo
# 导入 cg 指标
from .cg import cg
# 导入 cmo 指标
from .cmo import cmo
# 导入 coppock 指标
from .coppock import coppock
# 导入 cti 指标
from .cti import cti
# 导入 dm 指标
from .dm import dm
# 导入 er 指标
from .er import er
# 导入 eri 指标
from .eri import eri
# 导入 fisher 指标
from .fisher import fisher
# 导入 inertia 指标
from .inertia import inertia
# 导入 kdj 指标
from .kdj import kdj
# 导入 kst 指标
from .kst import kst
# 导入 macd 指标
from .macd import macd
# 导入 mom 指标
from .mom import mom
# 导入 pgo 指标
from .pgo import pgo
# 导入 ppo 指标
from .ppo import ppo
# 导入 psl 指标
from .psl import psl
# 导入 pvo 指标
from .pvo import pvo
# 导入 qqe 指标
from .qqe import qqe
# 导入 roc 指标
from .roc import roc
# 导入 rsi 指标
from .rsi import rsi
# 导入 rsx 指标
from .rsx import rsx
# 导入 rvgi 指标
from .rvgi import rvgi
# 导入 slope 指标
from .slope import slope
# 导入 smi 指标
from .smi import smi
# 导入 squeeze 指标
from .squeeze import squeeze
# 导入 squeeze_pro 指标
from .squeeze_pro import squeeze_pro
# 导入 stc 指标
from .stc import stc
# 导入 stoch 指标
from .stoch import stoch
# 导入 stochrsi 指标
from .stochrsi import stochrsi
# 导入 td_seq 指标
from .td_seq import td_seq
# 导入 trix 指标
from .trix import trix
# 导入 tsi 指标
from .tsi import tsi
# 导入 uo 指标
from .uo import uo
# 导入 willr 指标
from .willr import willr

.\pandas-ta\pandas_ta\overlap\alma.py

# -*- coding: utf-8 -*-
# 从 numpy 库中导入 exp 函数并重命名为 npExp
from numpy import exp as npExp
# 从 numpy 库中导入 nan 常量并重命名为 npNaN
from numpy import nan as npNaN
# 从 pandas 库中导入 Series 类
from pandas import Series
# 从 pandas_ta.utils 模块中导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_seriesdef alma(close, length=None, sigma=None, distribution_offset=None, offset=None, **kwargs):"""Indicator: Arnaud Legoux Moving Average (ALMA)"""# 验证参数# 将长度转换为整数,如果长度存在且大于 0;否则默认为 10length = int(length) if length and length > 0 else 10# 将 sigma 转换为浮点数,如果 sigma 存在且大于 0;否则默认为 6.0sigma = float(sigma) if sigma and sigma > 0 else 6.0# 将 distribution_offset 转换为浮点数,如果 distribution_offset 存在且大于 0;否则默认为 0.85distribution_offset = float(distribution_offset) if distribution_offset and distribution_offset > 0 else 0.85# 验证 close 序列,长度为 lengthclose = verify_series(close, length)# 获取偏移量offset = get_offset(offset)# 如果 close 为空,返回空if close is None: return# 预先计算m = distribution_offset * (length - 1)s = length / sigmawtd = list(range(length))for i in range(0, length):# 计算权重(窗口)wtd[i] = npExp(-1 * ((i - m) * (i - m)) / (2 * s * s))# 计算结果# 初始化结果为长度-1个 NaN 和 1 个 0 组成的列表result = [npNaN for _ in range(0, length - 1)] + [0]for i in range(length, close.size):window_sum = 0cum_sum = 0for j in range(0, length):# 计算窗口和window_sum = window_sum + wtd[j] * close.iloc[i - j]# 计算累积和cum_sum = cum_sum + wtd[j]# 计算 ALMAalmean = window_sum / cum_sum# 如果 i 等于长度,则将结果列表追加 NaN,否则追加 almeanresult.append(npNaN) if i == length else result.append(almean)# 创建 ALMA Series 对象alma = Series(result, index=close.index)# 处理偏移if offset != 0:alma = alma.shift(offset)# 处理填充if "fillna" in kwargs:alma.fillna(kwargs["fillna"], inplace=True)if "fill_method" in kwargs:alma.fillna(method=kwargs["fill_method"], inplace=True)# 名称和分类alma.name = f"ALMA_{length}_{sigma}_{distribution_offset}"alma.category = "overlap"return alma# 为 alma 函数添加文档字符串
alma.__doc__ = \
"""Arnaud Legoux Moving Average (ALMA)The ALMA moving average uses the curve of the Normal (Gauss) distribution, which
can be shifted from 0 to 1. This allows regulating the smoothness and high
sensitivity of the indicator. Sigma is another parameter that is responsible for
the shape of the curve coefficients. This moving average reduces lag of the data
in conjunction with smoothing to reduce noise.Implemented for Pandas TA by rengel8 based on the source provided below.Sources:https://www.prorealcode.com/prorealtime-indicators/alma-arnaud-legoux-moving-average/Calculation:refer to provided sourceArgs:close (pd.Series): Series of 'close'slength (int): It's period, window size. Default: 10sigma (float): Smoothing value. Default 6.0distribution_offset (float): Value to offset the distribution min 0(smoother), max 1 (more responsive). Default 0.85offset (int): How many periods to offset the result. Default: 0Kwargs:fillna (value, optional): pd.DataFrame.fillna(value)fill_method (value, optional): Type of fill methodReturns:"""# 创建一个 Pandas Series 对象,表示生成了一个新的特征
# 这是一个空的字符串,通常用作多行注释的起始

.\pandas-ta\pandas_ta\overlap\dema.py

# -*- coding: utf-8 -*-
# 导入 ema 函数
from .ema import ema
# 导入 Imports 模块
from pandas_ta import Imports
# 导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_series# 定义 dema 函数,计算 Double Exponential Moving Average (DEMA)
def dema(close, length=None, talib=None, offset=None, **kwargs):"""Indicator: Double Exponential Moving Average (DEMA)"""# 验证参数# 如果 length 存在且大于 0,则将其转换为整数,否则设为默认值 10length = int(length) if length and length > 0 else 10# 验证 close 数据类型为 Series,并且长度符合要求close = verify_series(close, length)# 获取 offset 值offset = get_offset(offset)# 判断是否使用 talib 模式mode_tal = bool(talib) if isinstance(talib, bool) else True# 如果 close 为空,则返回空值if close is None: return# 计算结果if Imports["talib"] and mode_tal:# 如果导入了 talib 并且使用 talib 模式,则调用 talib 中的 DEMA 函数from talib import DEMAdema = DEMA(close, length)else:# 否则,分别计算两个 EMA 值ema1 = ema(close=close, length=length)ema2 = ema(close=ema1, length=length)# 计算 DEMA 值dema = 2 * ema1 - ema2# 对结果进行偏移if offset != 0:dema = dema.shift(offset)# 处理填充值if "fillna" in kwargs:dema.fillna(kwargs["fillna"], inplace=True)if "fill_method" in kwargs:dema.fillna(method=kwargs["fill_method"], inplace=True)# 设置指标名称和类别dema.name = f"DEMA_{length}"dema.category = "overlap"return dema# 设置 dema 函数的文档字符串
dema.__doc__ = \
"""Double Exponential Moving Average (DEMA)The Double Exponential Moving Average attempts to a smoother average with less
lag than the normal Exponential Moving Average (EMA).Sources:https://www.tradingtechnologies.com/help/x-study/technical-indicator-definitions/double-exponential-moving-average-dema/Calculation:Default Inputs:length=10EMA = Exponential Moving Averageema1 = EMA(close, length)ema2 = EMA(ema1, length)DEMA = 2 * ema1 - ema2Args:close (pd.Series): Series of 'close'slength (int): It's period. Default: 10talib (bool): If TA Lib is installed and talib is True, Returns the TA Libversion. Default: Trueoffset (int): How many periods to offset the result. Default: 0Kwargs:fillna (value, optional): pd.DataFrame.fillna(value)fill_method (value, optional): Type of fill methodReturns:pd.Series: New feature generated.
"""

.\pandas-ta\pandas_ta\overlap\ema.py

# -*- coding: utf-8 -*-
# 从 numpy 导入 nan 并重命名为 npNaN
from numpy import nan as npNaN
# 从 pandas_ta 导入 Imports 模块
from pandas_ta import Imports
# 从 pandas_ta.utils 导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_seriesdef ema(close, length=None, talib=None, offset=None, **kwargs):"""Indicator: Exponential Moving Average (EMA)"""# 验证参数# 将 length 转换为整数,如果 length 存在且大于 0,否则默认为 10length = int(length) if length and length > 0 else 10# 从 kwargs 中弹出 "adjust" 键的值,默认为 Falseadjust = kwargs.pop("adjust", False)# 从 kwargs 中弹出 "sma" 键的值,默认为 Truesma = kwargs.pop("sma", True)# 验证 close 数据,并使用 length 进行验证close = verify_series(close, length)# 获取偏移量offset = get_offset(offset)# 如果 talib 存在且为布尔类型,则将 mode_tal 设置为 talib,否则设置为 Truemode_tal = bool(talib) if isinstance(talib, bool) else True# 如果 close 为 None,则返回if close is None: return# 计算结果if Imports["talib"] and mode_tal:# 如果 Imports 中的 "talib" 为 True 且 mode_tal 为 True,则使用 talib 库中的 EMA 函数from talib import EMAema = EMA(close, length)else:# 否则执行以下操作if sma:# 如果 sma 为 True,则执行以下操作close = close.copy()# 计算前 length 个 close 的均值作为初始值sma_nth = close[0:length].mean()# 将 close 的前 length-1 个值设为 NaNclose[:length - 1] = npNaN# 将 close 的第 length-1 个值设为初始均值close.iloc[length - 1] = sma_nth# 使用指数加权移动平均计算 EMAema = close.ewm(span=length, adjust=adjust).mean()# 偏移结果if offset != 0:ema = ema.shift(offset)# 处理填充if "fillna" in kwargs:ema.fillna(kwargs["fillna"], inplace=True)if "fill_method" in kwargs:ema.fillna(method=kwargs["fill_method"], inplace=True)# 名称和类别# 设置 ema 的名称为 "EMA_length",类别为 "overlap"ema.name = f"EMA_{length}"ema.category = "overlap"return ema# 重新定义 ema 函数的文档字符串
ema.__doc__ = \
"""Exponential Moving Average (EMA)指数移动平均是对比简单移动平均(SMA)更具响应性的移动平均。其权重由 alpha 决定,与其长度成正比。有几种不同的计算 EMA 的方法。一种方法仅使用标准的 EMA 定义,另一种方法使用 SMA 生成其余计算的初始值。来源:https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averageshttps://www.investopedia.com/ask/answers/122314/what-exponential-moving-average-ema-formula-and-how-ema-calculated.asp计算:默认参数:length=10, adjust=False, sma=True如果 sma 为 True:sma_nth = close[0:length].sum() / lengthclose[:length - 1] = np.NaNclose.iloc[length - 1] = sma_nthEMA = close.ewm(span=length, adjust=adjust).mean()参数:close (pd.Series): 'close' 数据的序列length (int): 周期。默认为 10talib (bool): 如果安装了 TA Lib 并且 talib 为 True,则返回 TA Lib 版本。默认为 Trueoffset (int): 结果的偏移周期数。默认为 0可选参数:adjust (bool, optional): 默认为 Falsesma (bool, optional): 如果为 True,则使用 SMA 作为初始值。默认为 Truefillna (value, optional): pd.DataFrame.fillna(value)fill_method (value, optional): 填充方法的类型返回:pd.Series: 生成的新特征。
"""

.\pandas-ta\pandas_ta\overlap\fwma.py

# -*- coding: utf-8 -*-
# 从 pandas_ta.utils 模块导入 fibonacci、get_offset、verify_series、weights 函数
from pandas_ta.utils import fibonacci, get_offset, verify_series, weights# 定义 Fibonacci's Weighted Moving Average (FWMA) 函数
def fwma(close, length=None, asc=None, offset=None, **kwargs):"""Indicator: Fibonacci's Weighted Moving Average (FWMA)"""# 验证参数# 如果 length 参数存在且大于 0,则将其转换为整数,否则设为默认值 10length = int(length) if length and length > 0 else 10# 如果 asc 参数存在且为真,则保持其值,否则设为默认值 Trueasc = asc if asc else True# 验证 close 参数,并设定长度为 lengthclose = verify_series(close, length)# 获取偏移量offset = get_offset(offset)# 如果 close 为空,则返回空值if close is None: return# 计算结果# 根据长度生成 Fibonacci 数列,使用加权方法fibs = fibonacci(n=length, weighted=True)# 计算 FWMAfwma = close.rolling(length, min_periods=length).apply(weights(fibs), raw=True)# 偏移# 如果偏移量不为零,则对 FWMA 进行偏移if offset != 0:fwma = fwma.shift(offset)# 处理填充# 如果 kwargs 中包含 fillna 键,则使用指定值进行填充if "fillna" in kwargs:fwma.fillna(kwargs["fillna"], inplace=True)# 如果 kwargs 中包含 fill_method 键,则使用指定的填充方法if "fill_method" in kwargs:fwma.fillna(method=kwargs["fill_method"], inplace=True)# 名称与类别# 设置 FWMA 的名称为 FWMA_length,类别为 overlapfwma.name = f"FWMA_{length}"fwma.category = "overlap"# 返回 FWMA 结果return fwma# 设置 FWMA 函数的文档字符串
fwma.__doc__ = \
"""Fibonacci's Weighted Moving Average (FWMA)Fibonacci's Weighted Moving Average is similar to a Weighted Moving Average
(WMA) where the weights are based on the Fibonacci Sequence.Source: Kevin JohnsonCalculation:Default Inputs:length=10,def weights(w):def _compute(x):return np.dot(w * x)return _computefibs = utils.fibonacci(length - 1)FWMA = close.rolling(length)_.apply(weights(fibs), raw=True)Args:close (pd.Series): Series of 'close'slength (int): It's period. Default: 10asc (bool): Recent values weigh more. Default: Trueoffset (int): How many periods to offset the result. Default: 0Kwargs:fillna (value, optional): pd.DataFrame.fillna(value)fill_method (value, optional): Type of fill methodReturns:pd.Series: New feature generated.
"""

.\pandas-ta\pandas_ta\overlap\hilo.py

# -*- coding: utf-8 -*-
# 导入 numpy 中的 nan 作为 npNaN
from numpy import nan as npNaN
# 从 pandas 中导入 DataFrame 和 Series
from pandas import DataFrame, Series
# 从当前包中导入 ma 模块
from .ma import ma
# 从 pandas_ta.utils 中导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_seriesdef hilo(high, low, close, high_length=None, low_length=None, mamode=None, offset=None, **kwargs):"""Indicator: Gann HiLo (HiLo)"""# 验证参数# 如果 high_length 存在且大于 0,则转换为整数;否则设为默认值 13high_length = int(high_length) if high_length and high_length > 0 else 13# 如果 low_length 存在且大于 0,则转换为整数;否则设为默认值 21low_length = int(low_length) if low_length and low_length > 0 else 21# 如果 mamode 是字符串,则转换为小写;否则设为默认值 "sma"mamode = mamode.lower() if isinstance(mamode, str) else "sma"# 计算 high 和 low 的最大长度_length = max(high_length, low_length)# 验证 high、low 和 close 的数据,并取长度为 _length 的数据high = verify_series(high, _length)low = verify_series(low, _length)close = verify_series(close, _length)# 获取偏移量offset = get_offset(offset)# 如果 high、low 或 close 为空,则返回空值if high is None or low is None or close is None: return# 计算结果m = close.size# 初始化 hilo、long 和 short 为全 NaN 的 Serieshilo = Series(npNaN, index=close.index)long = Series(npNaN, index=close.index)short = Series(npNaN, index=close.index)# 计算 high 和 low 的移动平均值high_ma = ma(mamode, high, length=high_length)low_ma = ma(mamode, low, length=low_length)# 循环计算 hilo、long 和 shortfor i in range(1, m):if close.iloc[i] > high_ma.iloc[i - 1]:hilo.iloc[i] = long.iloc[i] = low_ma.iloc[i]elif close.iloc[i] < low_ma.iloc[i - 1]:hilo.iloc[i] = short.iloc[i] = high_ma.iloc[i]else:hilo.iloc[i] = hilo.iloc[i - 1]long.iloc[i] = short.iloc[i] = hilo.iloc[i - 1]# 偏移结果if offset != 0:hilo = hilo.shift(offset)long = long.shift(offset)short = short.shift(offset)# 处理填充值if "fillna" in kwargs:hilo.fillna(kwargs["fillna"], inplace=True)long.fillna(kwargs["fillna"], inplace=True)short.fillna(kwargs["fillna"], inplace=True)if "fill_method" in kwargs:hilo.fillna(method=kwargs["fill_method"], inplace=True)long.fillna(method=kwargs["fill_method"], inplace=True)short.fillna(method=kwargs["fill_method"], inplace=True)# 名称和类别_props = f"_{high_length}_{low_length}"# 创建包含 hilo、long 和 short 数据的 DataFramedata = {f"HILO{_props}": hilo, f"HILOl{_props}": long, f"HILOs{_props}": short}df = DataFrame(data, index=close.index)# 设置 DataFrame 的名称和类别df.name = f"HILO{_props}"df.category = "overlap"# 返回 DataFramereturn df# 设置 hilo 函数的文档字符串
hilo.__doc__ = \
"""Gann HiLo Activator(HiLo)The Gann High Low Activator Indicator was created by Robert Krausz in a 1998
issue of Stocks & Commodities Magazine. It is a moving average based trend
indicator consisting of two different simple moving averages.The indicator tracks both curves (of the highs and the lows). The close of the
bar defines which of the two gets plotted.Increasing high_length and decreasing low_length better for short trades,
vice versa for long positions.Sources:https://www.sierrachart.com/index.php?page=doc/StudiesReference.php&ID=447&Name=Gann_HiLo_Activatorhttps://www.tradingtechnologies.com/help/x-study/technical-indicator-definitions/simple-moving-average-sma/
"""# 通过指定的 URL 访问 Gann High Low 脚本https://www.tradingview.com/script/XNQSLIYb-Gann-High-Low/
# 计算函数,根据所选的移动平均模式计算高低移动平均线
Calculation:# 默认输入参数:高期限、低期限、移动平均模式(默认为简单移动平均)Default Inputs:high_length=13, low_length=21, mamode="sma"# EMA = 指数移动平均EMA = Exponential Moving Average# HMA = 哈尔移动平均HMA = Hull Moving Average# SMA = 简单移动平均 # 默认# 根据所选的移动平均模式计算高期限和低期限移动平均值if "ema":high_ma = EMA(high, high_length)low_ma = EMA(low, low_length)elif "hma":high_ma = HMA(high, high_length)low_ma = HMA(low, low_length)else: # "sma"high_ma = SMA(high, high_length)low_ma = SMA(low, low_length)# 类似于Supertrend MA选择# 创建一个Series对象,用于存储高低移动平均线hilo = Series(npNaN, index=close.index)# 循环计算for i in range(1, m):# 如果当前收盘价大于上一个周期的高期限移动平均值,则将当前位置的低期限移动平均值存入hiloif close.iloc[i] > high_ma.iloc[i - 1]:hilo.iloc[i] = low_ma.iloc[i]# 如果当前收盘价小于上一个周期的低期限移动平均值,则将当前位置的高期限移动平均值存入hiloelif close.iloc[i] < low_ma.iloc[i - 1]:hilo.iloc[i] = high_ma.iloc[i]# 否则,维持前一个周期的值else:hilo.iloc[i] = hilo.iloc[i - 1]Args:# 高价的Serieshigh (pd.Series): Series of 'high's# 低价的Serieslow (pd.Series): Series of 'low's# 收盘价的Seriesclose (pd.Series): Series of 'close's# 高期限的长度,即移动平均线的周期。默认值为13high_length (int): It's period. Default: 13# 低期限的长度,即移动平均线的周期。默认值为21low_length (int): It's period. Default: 21# 移动平均模式,参见```help(ta.ma)```py。默认为'sma'mamode (str): See ```help(ta.ma)```py. Default: 'sma'# 结果的偏移量,即将结果向前或向后移动的周期数。默认为0offset (int): How many periods to offset the result. Default: 0Kwargs:# 是否调整结果adjust (bool): Default: True# 是否使用SMA作为初始值presma (bool, optional): If True, uses SMA for initial value.# 对DataFrame进行fillna填充fillna (value, optional): pd.DataFrame.fillna(value)# 填充方法的类型fill_method (value, optional): Type of fill methodReturns:# 返回一个DataFrame,包含HILO(线)、HILOl(长)、HILOs(短)列。pd.DataFrame: HILO (line), HILOl (long), HILOs (short) columns.

.\pandas-ta\pandas_ta\overlap\hl2.py

# -*- coding: utf-8 -*-
# 从 pandas_ta.utils 模块中导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_series# 定义函数 hl2,计算 HL2 指标
def hl2(high, low, offset=None, **kwargs):"""Indicator: HL2 """# 验证参数# 确保 high 和 low 是有效的序列数据high = verify_series(high)low = verify_series(low)# 获取偏移量offset = get_offset(offset)# 计算结果# HL2 指标的计算公式为 (high + low) / 2hl2 = 0.5 * (high + low)# 偏移# 如果偏移量不为 0,则对 hl2 进行偏移if offset != 0:hl2 = hl2.shift(offset)# 名称和类别# 设置 hl2 的名称为 "HL2",类别为 "overlap"hl2.name = "HL2"hl2.category = "overlap"return hl2

.\pandas-ta\pandas_ta\overlap\hlc3.py

# -*- coding: utf-8 -*-
# 从 pandas_ta 库中导入 Imports 模块
from pandas_ta import Imports
# 从 pandas_ta.utils 中导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_series# 定义函数 hlc3,计算 HLC3 指标
def hlc3(high, low, close, talib=None, offset=None, **kwargs):"""Indicator: HLC3"""# 验证参数# 验证 high、low、close 是否为 Series 类型high = verify_series(high)low = verify_series(low)close = verify_series(close)# 获取偏移量offset = get_offset(offset)# 判断是否使用 talib 库,默认为 Truemode_tal = bool(talib) if isinstance(talib, bool) else True# 计算结果# 如果导入了 talib 库并且 mode_tal 为 Trueif Imports["talib"] and mode_tal:# 从 talib 库中导入 TYPPRICE 函数,计算 HLC3from talib import TYPPRICEhlc3 = TYPPRICE(high, low, close)else:# 否则,使用普通方法计算 HLC3hlc3 = (high + low + close) / 3.0# 偏移# 如果偏移量不为 0,则对结果进行偏移if offset != 0:hlc3 = hlc3.shift(offset)# 名称和类别# 设置结果的名称为 "HLC3",类别为 "overlap"hlc3.name = "HLC3"hlc3.category = "overlap"# 返回计算结果return hlc3

.\pandas-ta\pandas_ta\overlap\hma.py

# -*- coding: utf-8 -*-# 从 numpy 库中导入 sqrt 函数并重命名为 npSqrt
from numpy import sqrt as npSqrt
# 从当前目录下的 wma 模块中导入 wma 函数
from .wma import wma
# 从 pandas_ta.utils 模块中导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_series# 定义 Hull Moving Average (HMA) 指标函数
def hma(close, length=None, offset=None, **kwargs):"""Indicator: Hull Moving Average (HMA)"""# 验证参数# 如果 length 存在且大于 0,则将其转换为整数,否则设为默认值 10length = int(length) if length and length > 0 else 10# 验证 close 数据为 pd.Series 类型,并且长度符合要求close = verify_series(close, length)# 获取 offset 值offset = get_offset(offset)# 如果 close 为空,则返回空值if close is None: return# 计算结果half_length = int(length / 2)sqrt_length = int(npSqrt(length))# 计算 wmaf 和 wmaswmaf = wma(close=close, length=half_length)wmas = wma(close=close, length=length)# 计算 HMAhma = wma(close=2 * wmaf - wmas, length=sqrt_length)# 调整偏移量if offset != 0:hma = hma.shift(offset)# 处理填充值if "fillna" in kwargs:hma.fillna(kwargs["fillna"], inplace=True)if "fill_method" in kwargs:hma.fillna(method=kwargs["fill_method"], inplace=True)# 设置指标名称和类别hma.name = f"HMA_{length}"hma.category = "overlap"return hma# 设置 HMA 函数的文档字符串
hma.__doc__ = \
"""Hull Moving Average (HMA)The Hull Exponential Moving Average attempts to reduce or remove lag in moving
averages.Sources:https://alanhull.com/hull-moving-averageCalculation:Default Inputs:length=10WMA = Weighted Moving Averagehalf_length = int(0.5 * length)sqrt_length = int(sqrt(length))wmaf = WMA(close, half_length)wmas = WMA(close, length)HMA = WMA(2 * wmaf - wmas, sqrt_length)Args:close (pd.Series): Series of 'close'slength (int): It's period. Default: 10offset (int): How many periods to offset the result. Default: 0Kwargs:fillna (value, optional): pd.DataFrame.fillna(value)fill_method (value, optional): Type of fill methodReturns:pd.Series: New feature generated.
"""

.\pandas-ta\pandas_ta\overlap\hwma.py

# -*- coding: utf-8 -*-
# 从 pandas 库中导入 Series 类
from pandas import Series
# 从 pandas_ta.utils 模块中导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_series# 定义函数 hwma,计算 Holt-Winter 移动平均值
def hwma(close, na=None, nb=None, nc=None, offset=None, **kwargs):"""Indicator: Holt-Winter Moving Average"""# 验证参数有效性并设置默认值na = float(na) if na and na > 0 and na < 1 else 0.2nb = float(nb) if nb and nb > 0 and nb < 1 else 0.1nc = float(nc) if nc and nc > 0 and nc < 1 else 0.1# 验证 close 参数并转换为 pd.Series 类型close = verify_series(close)# 获取偏移量offset = get_offset(offset)# 计算结果last_a = last_v = 0last_f = close.iloc[0]result = []m = close.sizefor i in range(m):# 计算 FF = (1.0 - na) * (last_f + last_v + 0.5 * last_a) + na * close.iloc[i]# 计算 VV = (1.0 - nb) * (last_v + last_a) + nb * (F - last_f)# 计算 AA = (1.0 - nc) * last_a + nc * (V - last_v)result.append((F + V + 0.5 * A))# 更新变量值last_a, last_f, last_v = A, F, V# 创建 Series 对象hwma = Series(result, index=close.index)# 处理偏移if offset != 0:hwma = hwma.shift(offset)# 处理填充值if "fillna" in kwargs:hwma.fillna(kwargs["fillna"], inplace=True)if "fill_method" in kwargs:hwma.fillna(method=kwargs["fill_method"], inplace=True)# 设置名称和分类suffix = f"{na}_{nb}_{nc}"hwma.name = f"HWMA_{suffix}"hwma.category = "overlap"return hwma# 为 hwma 函数添加文档字符串
hwma.__doc__ = \
"""HWMA (Holt-Winter Moving Average)Indicator HWMA (Holt-Winter Moving Average) is a three-parameter moving average
by the Holt-Winter method; the three parameters should be selected to obtain a
forecast.This version has been implemented for Pandas TA by rengel8 based
on a publication for MetaTrader 5.Sources:https://www.mql5.com/en/code/20856Calculation:HWMA[i] = F[i] + V[i] + 0.5 * A[i]where..F[i] = (1-na) * (F[i-1] + V[i-1] + 0.5 * A[i-1]) + na * Price[i]V[i] = (1-nb) * (V[i-1] + A[i-1]) + nb * (F[i] - F[i-1])A[i] = (1-nc) * A[i-1] + nc * (V[i] - V[i-1])Args:close (pd.Series): Series of 'close'sna (float): Smoothed series parameter (from 0 to 1). Default: 0.2nb (float): Trend parameter (from 0 to 1). Default: 0.1nc (float): Seasonality parameter (from 0 to 1). Default: 0.1close (pd.Series): Series of 'close'sKwargs:fillna (value, optional): pd.DataFrame.fillna(value)fill_method (value, optional): Type of fill methodReturns:pd.Series: hwma
"""

.\pandas-ta\pandas_ta\overlap\ichimoku.py

# -*- coding: utf-8 -*-
# 导入所需的库
from pandas import date_range, DataFrame, RangeIndex, Timedelta
from .midprice import midprice
from pandas_ta.utils import get_offset, verify_series# 定义 Ichimoku 函数,计算 Ichimoku Kinkō Hyō 指标
def ichimoku(high, low, close, tenkan=None, kijun=None, senkou=None, include_chikou=True, offset=None, **kwargs):"""Indicator: Ichimoku Kinkō Hyō (Ichimoku)"""# 设置默认的参数值tenkan = int(tenkan) if tenkan and tenkan > 0 else 9kijun = int(kijun) if kijun and kijun > 0 else 26senkou = int(senkou) if senkou and senkou > 0 else 52_length = max(tenkan, kijun, senkou)# 验证输入的数据high = verify_series(high, _length)low = verify_series(low, _length)close = verify_series(close, _length)offset = get_offset(offset)# 根据参数设置是否包含未来数据if not kwargs.get("lookahead", True):include_chikou = False# 如果输入数据有缺失,则返回空值if high is None or low is None or close is None: return None, None# 计算 Ichimoku 指标的各个线tenkan_sen = midprice(high=high, low=low, length=tenkan)kijun_sen = midprice(high=high, low=low, length=kijun)span_a = 0.5 * (tenkan_sen + kijun_sen)span_b = midprice(high=high, low=low, length=senkou)# 复制 Span A 和 Span B 在移动之前的值_span_a = span_a[-kijun:].copy()_span_b = span_b[-kijun:].copy()# 移动 Span A 和 Span B 的值span_a = span_a.shift(kijun)span_b = span_b.shift(kijun)chikou_span = close.shift(-kijun)# 根据偏移量对数据进行偏移if offset != 0:tenkan_sen = tenkan_sen.shift(offset)kijun_sen = kijun_sen.shift(offset)span_a = span_a.shift(offset)span_b = span_b.shift(offset)chikou_span = chikou_span.shift(offset)# 处理缺失值if "fillna" in kwargs:span_a.fillna(kwargs["fillna"], inplace=True)span_b.fillna(kwargs["fillna"], inplace=True)chikou_span.fillna(kwargs["fillna"], inplace=True)if "fill_method" in kwargs:span_a.fillna(method=kwargs["fill_method"], inplace=True)span_b.fillna(method=kwargs["fill_method"], inplace=True)chikou_span.fillna(method=kwargs["fill_method"], inplace=True)# 设置各个线的名称和类别span_a.name = f"ISA_{tenkan}"span_b.name = f"ISB_{kijun}"tenkan_sen.name = f"ITS_{tenkan}"kijun_sen.name = f"IKS_{kijun}"chikou_span.name = f"ICS_{kijun}"chikou_span.category = kijun_sen.category = tenkan_sen.category = "trend"span_b.category = span_a.category = chikou_span# 准备 Ichimoku DataFramedata = {span_a.name: span_a,span_b.name: span_b,tenkan_sen.name: tenkan_sen,kijun_sen.name: kijun_sen,}if include_chikou:data[chikou_span.name] = chikou_spanichimokudf = DataFrame(data)ichimokudf.name = f"ICHIMOKU_{tenkan}_{kijun}_{senkou}"ichimokudf.category = "overlap"# 准备 Span DataFramelast = close.index[-1]# 如果收盘价索引的数据类型为 "int64",执行以下操作if close.index.dtype == "int64":# 创建一个新的范围索引,起始于 last + 1,结束于 last + kijun + 1ext_index = RangeIndex(start=last + 1, stop=last + kijun + 1)# 创建一个空的 DataFrame,索引为 ext_index,列为 span_a.name 和 span_b.namespandf = DataFrame(index=ext_index, columns=[span_a.name, span_b.name])# 将 _span_a 和 _span_b 的索引设置为 ext_index_span_a.index = _span_b.index = ext_index# 如果收盘价索引的数据类型不为 "int64",执行以下操作else:# 统计收盘价索引中各值的频次,并取出出现频次最多的值df_freq = close.index.value_counts().mode()[0]# 创建一个时间增量对象,时间间隔为 df_freq 天tdelta = Timedelta(df_freq, unit="d")# 创建一个新的日期范围,起始日期为 last + tdelta,包含 kijun 个工作日new_dt = date_range(start=last + tdelta, periods=kijun, freq="B")# 创建一个空的 DataFrame,索引为 new_dt,列为 span_a.name 和 span_b.namespandf = DataFrame(index=new_dt, columns=[span_a.name, span_b.name])# 将 _span_a 和 _span_b 的索引设置为 new_dtspandf[span_a.name] = _span_aspandf[span_b.name] = _span_b# 设置 spandf 的名称为特定字符串,包含 tenkan 和 kijun 的值spandf.name = f"ICHISPAN_{tenkan}_{kijun}"# 设置 spandf 的类别为 "overlap"spandf.category = "overlap"# 返回 ichimokudf 和 spandfreturn ichimokudf, spandf
# 将 ichimoku.__doc__ 的值设为字符串,用于描述 Ichimoku Kinkō Hyō(一种用于金融市场预测的模型)的计算方法和参数
ichimoku.__doc__ = \
"""Ichimoku Kinkō Hyō (ichimoku)Developed Pre WWII as a forecasting model for financial markets.Sources:https://www.tradingtechnologies.com/help/x-study/technical-indicator-definitions/ichimoku-ich/Calculation:Default Inputs:tenkan=9, kijun=26, senkou=52MIDPRICE = MidpriceTENKAN_SEN = MIDPRICE(high, low, close, length=tenkan)KIJUN_SEN = MIDPRICE(high, low, close, length=kijun)CHIKOU_SPAN = close.shift(-kijun)SPAN_A = 0.5 * (TENKAN_SEN + KIJUN_SEN)SPAN_A = SPAN_A.shift(kijun)SPAN_B = MIDPRICE(high, low, close, length=senkou)SPAN_B = SPAN_B.shift(kijun)Args:high (pd.Series): Series of 'high's  # high 数据序列low (pd.Series): Series of 'low's  # low 数据序列close (pd.Series): Series of 'close's  # close 数据序列tenkan (int): Tenkan period. Default: 9  # Tenkan 周期,默认为 9kijun (int): Kijun period. Default: 26  # Kijun 周期,默认为 26senkou (int): Senkou period. Default: 52  # Senkou 周期,默认为 52include_chikou (bool): Whether to include chikou component. Default: True  # 是否包含 chikou 组件,默认为 Trueoffset (int): How many periods to offset the result. Default: 0  # 结果偏移的周期数,默认为 0Kwargs:fillna (value, optional): pd.DataFrame.fillna(value)  # fillna 方法的参数,用于填充缺失值fill_method (value, optional): Type of fill method  # 填充方法的类型Returns:pd.DataFrame: Two DataFrames.  # 返回两个 DataFrameFor the visible period: spanA, spanB, tenkan_sen, kijun_sen,  # 可见期间的 DataFrame,包含 spanA、spanB、tenkan_sen、kijun_senand chikou_span columns  # 以及 chikou_span 列For the forward looking period: spanA and spanB columns  # 未来观察期间的 DataFrame,包含 spanA 和 spanB 列
"""

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/821134.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

快速排序题目SelectK问题

力扣75.颜色分类 给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums &#xff0c;原地对它们进行排序&#xff0c;使得相同颜色的元素相邻&#xff0c;并按照红色、白色、蓝色顺序排列。 我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 必须在不使用库内置的 sor…

普发Pfeiffer TPG252 TPG256A SingleGaugeTPG261-262使用说明手侧

普发Pfeiffer TPG252 TPG256A SingleGaugeTPG261-262使用说明手侧

卷积神经网络的结构组成与解释(详细介绍)

文章目录 前言 1、卷积层 2、激活层 3、BN层 4、池化层 5、FC层&#xff08;全连接层&#xff09; 6、损失层 7、Dropout层 8、优化器 9、学习率 10、卷积神经网络的常见结构 前言 卷积神经网络是以卷积层为主的深层网络结构&#xff0c;网络结构包括有卷积层、激活层、BN层、…

模板初阶的学习

目录&#xff1a; 一&#xff1a;泛型模板 二&#xff1a;函数模板 三&#xff1a;类模板 1&#xff1a;泛型模板 泛型编程&#xff1a;编写与类型无关的通用代码&#xff0c;是代码复用的一种手段。模板是泛型编程的基础。 以交换函数为列进行讲解&#xff1a; void Swap(…

微服务中的重要模块

为什么要有微服务&#xff1f; 微服务提高开发效能&#xff0c;避免业务的重复理解&#xff0c;代码重复开发&#xff0c;增加开发效能和代码复用性。 在实际的工作中许多不同的业务有着共同的功能需求&#xff0c;如果我们每遇到一次这种需求就重新去理解构建一次的话会花费大…

【深度学习】【机器学习】用神经网络进行入侵检测,NSL-KDD数据集,基于机器学习(深度学习)判断网络入侵,网络攻击,流量异常【3】

之前用NSL-KDD数据集做入侵检测的项目是&#xff1a; 【1】https://qq742971636.blog.csdn.net/article/details/137082925 【2】https://qq742971636.blog.csdn.net/article/details/137170933 有人问我是不是可以改代码&#xff0c;我说可以。 训练 我将NSL_KDD_Final_1.i…

Day42:动态规划 LeedCode 01背包 416. 分割等和子集

01背包 1.确定dp数组以及下标的含义 dp[i][j]的含义&#xff1a;从下标为[0-i]的物品里任意取&#xff0c;放进容量为j的背包&#xff0c;价值总和最大是多少。 那么可以有两个方向推出来dp[i][j] 2.确定递推公式 不放物品i&#xff1a;由dp[i - 1][j]推出&#xff0c;即背…

十大排序——9.桶排序

这篇文章我们来介绍一下桶排序 目录 1.介绍 2.代码实现 3.总结与思考 1.介绍 桶排序和计数排序一样&#xff0c;都不是基于比较进行排序的。 下面通过一个例子来理解一下桶排序吧。 首先&#xff0c;给你一个无序数组[ 20,18,28,66,25,31,67,30 ]&#xff0c;然后&#…

Maven POM元素解析(二)

一、parent <parent>元素包含定位此项目将从中继承的父项目所需的信息。注意&#xff1a;此元素的子元素不是插值的&#xff0c;必须作为文字值给定。 ElementTypeDescriptiongroupIdString要从中继承的父项目的组id。artifactIdString要从中继承的父项目的项目id。ver…

【Entity Framework】你知道如何处理无键实体吗

【Entity Framework】你知道如何处理无键实体吗 文章目录 【Entity Framework】你知道如何处理无键实体吗一、概述二、定义无键实体类型数据注释 三、无键实体类型特征四、无键实体使用场景五、无键实体使用场景六、无键使用示例6.1 定义一个简单的Blog和Post模型&#xff1a;6…

高分二号卫星(GF-2):中国遥感科技的新高度

​高分二号卫星&#xff08;GF-2&#xff09;是中国在高分辨率地球观测领域的重要成就&#xff0c;其引入了先进的成像技术和灵活的数据获取模式&#xff0c;为地球资源监测、环境保护、城市规划等领域提供了强大的数据支持。本文将深入介绍高分二号卫星的技术特点、成像能力以…

Day 27 39. 组合总和 40.组合总和II 131.分割回文串

组合总和 给定一个无重复元素的数组 candidates 和一个目标数 target &#xff0c;找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明&#xff1a; 所有数字&#xff08;包括 target&#xff09;都是正整数。解集不能…

自定义类型: 结构体 (详解)

本文索引 一. 结构体类型的声明1. 结构体的声明和初始化2. 结构体的特殊声明3. 结构体的自引用 二. 结构体内存对齐1. 对齐规则2. 为啥存在对齐?3. 修改默认对齐值 三. 结构体传参四. 结构体实现位段1. 什么是位段?2. 位段的内存分配3. 位段的应用4. 位段的注意事项 ​ 前言:…

什么是上位机?入门指南

什么是上位机&#xff1f; 上位机&#xff08;SCADA&#xff0c;Supervisory Control and Data Acquisition&#xff09;是一种软件系统&#xff0c;用于监控和控制工业过程中的设备。它通常与传感器、执行器和其他自动化设备一起工作&#xff0c;以实时地监视过程状态、收集数…

【精读文献】Scientific data|2017-2021年中国10米玉米农田变化制图

论文名称&#xff1a;Mapping annual 10-m maize cropland changes in China during 2017–2021 第一作者及通讯作者&#xff1a;Xingang Li, Ying Qu 第一作者单位及通讯作者单位&#xff1a;北京师范大学地理学部 文章发表期刊&#xff1a;《Scientific data》&#xff08…

Token2049主办方遭遇假门票风波,韩国罗马基金会Charles Lee损失50万美元

加密货币——遍地黄金&#xff1f;还是遍地陷阱&#xff1f; 尽管伊朗空袭以色列导致中东局势愈发紧张&#xff0c;但加密社区对当地市场的热情丝毫没有受到影响&#xff0c;不出意外的话&#xff0c;Token 2049这场全球最受瞩目的加密货币盛会将于4月18至19日在迪拜如期举行&…

Buck变换电路

Buck变换电路 Buck变换电路是最基本的DC/DC拓扑电路&#xff0c;属于非隔离型直流变换器&#xff0c;其输出电压小于输入电压。Buck变换电路具有效率高、输出稳定、控制简单和成本低的优点&#xff0c;广泛应用于稳压电源、光伏发电、LED驱动和能量回收系统。 电路原理 Buck变…

PyCharm 2024.1 发布:全面升级,助力高效编程!

PyCharm 2024.1 发布&#xff1a;全面升级&#xff0c;助力高效编程&#xff01; 文章目录 PyCharm 2024.1 发布&#xff1a;全面升级&#xff0c;助力高效编程&#xff01;摘要引言 Hugging Face&#xff1a;模型和数据集的快速文档预览针对 JavaScript 和 TypeScript 的全行代…

力扣101. 对称二叉树(java)

思路&#xff1a; 一、验证 左右子树是否可翻转对称的&#xff1f; 二、分析左右子树情况&#xff1a; 1&#xff09;左右都也空 对称 2&#xff09;左右有一个为空 不对称 3&#xff09;左右都不为空&#xff0c;但数字不同 不对称 4&#xff09;左右都不为空&#xff0c;且数…

C++从入门到精通——类和对象(下篇)

1. 再谈构造函数 1.1 构造函数体赋值 在创建对象时&#xff0c;编译器通过调用构造函数&#xff0c;给对象中各个成员变量一个合适的初始值。 class Date { public:Date(int year, int month, int day){_year year;_month month;_day day;} private:int _year;int _mont…