PandasTA 源码解析(八)(2)

简介: PandasTA 源码解析(八)

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

相关文章
|
10月前
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
1019 29
|
10月前
|
前端开发 数据安全/隐私保护 CDN
二次元聚合短视频解析去水印系统源码
二次元聚合短视频解析去水印系统源码
438 4
|
10月前
|
JavaScript 算法 前端开发
JS数组操作方法全景图,全网最全构建完整知识网络!js数组操作方法全集(实现筛选转换、随机排序洗牌算法、复杂数据处理统计等情景详解,附大量源码和易错点解析)
这些方法提供了对数组的全面操作,包括搜索、遍历、转换和聚合等。通过分为原地操作方法、非原地操作方法和其他方法便于您理解和记忆,并熟悉他们各自的使用方法与使用范围。详细的案例与进阶使用,方便您理解数组操作的底层原理。链式调用的几个案例,让您玩转数组操作。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
10月前
|
移动开发 前端开发 JavaScript
从入门到精通:H5游戏源码开发技术全解析与未来趋势洞察
H5游戏凭借其跨平台、易传播和开发成本低的优势,近年来发展迅猛。接下来,让我们深入了解 H5 游戏源码开发的技术教程以及未来的发展趋势。
|
10月前
|
存储 前端开发 JavaScript
在线教育网课系统源码开发指南:功能设计与技术实现深度解析
在线教育网课系统是近年来发展迅猛的教育形式的核心载体,具备用户管理、课程管理、教学互动、学习评估等功能。本文从功能和技术两方面解析其源码开发,涵盖前端(HTML5、CSS3、JavaScript等)、后端(Java、Python等)、流媒体及云计算技术,并强调安全性、稳定性和用户体验的重要性。
|
11月前
|
机器学习/深度学习 自然语言处理 算法
生成式 AI 大语言模型(LLMs)核心算法及源码解析:预训练篇
生成式 AI 大语言模型(LLMs)核心算法及源码解析:预训练篇
3079 1
|
存储 设计模式 算法
【23种设计模式·全精解析 | 行为型模式篇】11种行为型模式的结构概述、案例实现、优缺点、扩展对比、使用场景、源码解析
行为型模式用于描述程序在运行时复杂的流程控制,即描述多个类或对象之间怎样相互协作共同完成单个对象都无法单独完成的任务,它涉及算法与对象间职责的分配。行为型模式分为类行为模式和对象行为模式,前者采用继承机制来在类间分派行为,后者采用组合或聚合在对象间分配行为。由于组合关系或聚合关系比继承关系耦合度低,满足“合成复用原则”,所以对象行为模式比类行为模式具有更大的灵活性。 行为型模式分为: • 模板方法模式 • 策略模式 • 命令模式 • 职责链模式 • 状态模式 • 观察者模式 • 中介者模式 • 迭代器模式 • 访问者模式 • 备忘录模式 • 解释器模式
1086 1
【23种设计模式·全精解析 | 行为型模式篇】11种行为型模式的结构概述、案例实现、优缺点、扩展对比、使用场景、源码解析
|
设计模式 存储 安全
【23种设计模式·全精解析 | 创建型模式篇】5种创建型模式的结构概述、实现、优缺点、扩展、使用场景、源码解析
结构型模式描述如何将类或对象按某种布局组成更大的结构。它分为类结构型模式和对象结构型模式,前者采用继承机制来组织接口和类,后者釆用组合或聚合来组合对象。由于组合关系或聚合关系比继承关系耦合度低,满足“合成复用原则”,所以对象结构型模式比类结构型模式具有更大的灵活性。 结构型模式分为以下 7 种: • 代理模式 • 适配器模式 • 装饰者模式 • 桥接模式 • 外观模式 • 组合模式 • 享元模式
【23种设计模式·全精解析 | 创建型模式篇】5种创建型模式的结构概述、实现、优缺点、扩展、使用场景、源码解析
|
10月前
|
负载均衡 JavaScript 前端开发
分片上传技术全解析:原理、优势与应用(含简单实现源码)
分片上传通过将大文件分割成多个小的片段或块,然后并行或顺序地上传这些片段,从而提高上传效率和可靠性,特别适用于大文件的上传场景,尤其是在网络环境不佳时,分片上传能有效提高上传体验。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
自然语言处理 数据处理 索引
mindspeed-llm源码解析(一)preprocess_data
mindspeed-llm是昇腾模型套件代码仓,原来叫"modelLink"。这篇文章带大家阅读一下数据处理脚本preprocess_data.py(基于1.0.0分支),数据处理是模型训练的第一步,经常会用到。
399 0

推荐镜像

更多
  • DNS