PandasTA 源码解析(八)(1)https://developer.aliyun.com/article/1506129
.\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,则将其转换为整数,否则设为默认值 10 length = int(length) if length and length > 0 else 10 # 如果 asc 参数存在且为真,则保持其值,否则设为默认值 True asc = asc if asc else True # 验证 close 参数,并设定长度为 length close = verify_series(close, length) # 获取偏移量 offset = get_offset(offset) # 如果 close 为空,则返回空值 if close is None: return # 计算结果 # 根据长度生成 Fibonacci 数列,使用加权方法 fibs = fibonacci(n=length, weighted=True) # 计算 FWMA fwma = 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,类别为 overlap fwma.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 Johnson Calculation: Default Inputs: length=10, def weights(w): def _compute(x): return np.dot(w * x) return _compute fibs = utils.fibonacci(length - 1) FWMA = close.rolling(length)_.apply(weights(fibs), raw=True) Args: close (pd.Series): Series of 'close's length (int): It's period. Default: 10 asc (bool): Recent values weigh more. Default: True offset (int): How many periods to offset the result. Default: 0 Kwargs: fillna (value, optional): pd.DataFrame.fillna(value) fill_method (value, optional): Type of fill method Returns: 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_series def hilo(high, low, close, high_length=None, low_length=None, mamode=None, offset=None, **kwargs): """Indicator: Gann HiLo (HiLo)""" # 验证参数 # 如果 high_length 存在且大于 0,则转换为整数;否则设为默认值 13 high_length = int(high_length) if high_length and high_length > 0 else 13 # 如果 low_length 存在且大于 0,则转换为整数;否则设为默认值 21 low_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 的 Series hilo = 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 和 short for 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 数据的 DataFrame data = {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" # 返回 DataFrame return 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_Activator https://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): # 如果当前收盘价大于上一个周期的高期限移动平均值,则将当前位置的低期限移动平均值存入hilo if close.iloc[i] > high_ma.iloc[i - 1]: hilo.iloc[i] = low_ma.iloc[i] # 如果当前收盘价小于上一个周期的低期限移动平均值,则将当前位置的高期限移动平均值存入hilo elif close.iloc[i] < low_ma.iloc[i - 1]: hilo.iloc[i] = high_ma.iloc[i] # 否则,维持前一个周期的值 else: hilo.iloc[i] = hilo.iloc[i - 1] Args: # 高价的Series high (pd.Series): Series of 'high's # 低价的Series low (pd.Series): Series of 'low's # 收盘价的Series close (pd.Series): Series of 'close's # 高期限的长度,即移动平均线的周期。默认值为13 high_length (int): It's period. Default: 13 # 低期限的长度,即移动平均线的周期。默认值为21 low_length (int): It's period. Default: 21 # 移动平均模式,参见```help(ta.ma)```py。默认为'sma' mamode (str): See ```help(ta.ma)```py. Default: 'sma' # 结果的偏移量,即将结果向前或向后移动的周期数。默认为0 offset (int): How many periods to offset the result. Default: 0 Kwargs: # 是否调整结果 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 method Returns: # 返回一个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) / 2 hl2 = 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 库,默认为 True mode_tal = bool(talib) if isinstance(talib, bool) else True # 计算结果 # 如果导入了 talib 库并且 mode_tal 为 True if Imports["talib"] and mode_tal: # 从 talib 库中导入 TYPPRICE 函数,计算 HLC3 from talib import TYPPRICE hlc3 = TYPPRICE(high, low, close) else: # 否则,使用普通方法计算 HLC3 hlc3 = (high + low + close) / 3.0 # 偏移 # 如果偏移量不为 0,则对结果进行偏移 if offset != 0: hlc3 = hlc3.shift(offset) # 名称和类别 # 设置结果的名称为 "HLC3",类别为 "overlap" hlc3.name = "HLC3" hlc3.category = "overlap" # 返回计算结果 return hlc3
PandasTA 源码解析(八)(3)https://developer.aliyun.com/article/1506132