PandasTA 源码解析(十一)(2)

简介: PandasTA 源码解析(十一)

PandasTA 源码解析(十一)(1)https://developer.aliyun.com/article/1506211

.\pandas-ta\pandas_ta\performance\log_return.py

# -*- coding: utf-8 -*-
# 从 numpy 中导入 log 函数并重命名为 nplog
from numpy import log as nplog
# 从 pandas_ta.utils 中导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_series
def log_return(close, length=None, cumulative=None, offset=None, **kwargs):
    """Indicator: Log Return"""
    # 验证参数
    # 如果 length 存在且大于 0,则将其转换为整数,否则设为 1
    length = int(length) if length and length > 0 else 1
    # 如果 cumulative 存在且为真,则设为 True,否则设为 False
    cumulative = bool(cumulative) if cumulative is not None and cumulative else False
    # 验证 close 是否为有效的 Series,并设置长度
    close = verify_series(close, length)
    # 获取偏移量
    offset = get_offset(offset)
    # 如果 close 为空,则返回 None
    if close is None: return
    # 计算结果
    if cumulative:
        # 计算累积对数收益率
        log_return = nplog(close / close.iloc[0])
    else:
        # 计算对数收益率
        log_return = nplog(close / close.shift(length))
    # 偏移结果
    if offset != 0:
        log_return = log_return.shift(offset)
    # 处理填充值
    if "fillna" in kwargs:
        log_return.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        log_return.fillna(method=kwargs["fill_method"], inplace=True)
    # 设置名称和类别
    log_return.name = f"{'CUM' if cumulative else ''}LOGRET_{length}"
    log_return.category = "performance"
    return log_return
# 设置 log_return 函数的文档字符串
log_return.__doc__ = \
"""Log Return
Calculates the logarithmic return of a Series.
See also: help(df.ta.log_return) for additional **kwargs a valid 'df'.
Sources:
    https://stackoverflow.com/questions/31287552/logarithmic-returns-in-pandas-dataframe
Calculation:
    Default Inputs:
        length=1, cumulative=False
    LOGRET = log( close.diff(periods=length) )
    CUMLOGRET = LOGRET.cumsum() if cumulative
Args:
    close (pd.Series): Series of 'close's
    length (int): It's period. Default: 20
    cumulative (bool): If True, returns the cumulative returns. Default: False
    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\performance\percent_return.py

# -*- coding: utf-8 -*-
# 从 pandas_ta.utils 模块中导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_series
# 定义一个名为 percent_return 的函数,用于计算百分比收益率
def percent_return(close, length=None, cumulative=None, offset=None, **kwargs):
    """Indicator: Percent Return"""
    
    # 验证参数
    length = int(length) if length and length > 0 else 1
    cumulative = bool(cumulative) if cumulative is not None and cumulative else False
    close = verify_series(close, length)
    offset = get_offset(offset)
    if close is None: return
    # 计算结果
    if cumulative:
        pct_return = (close / close.iloc[0]) - 1
    else:
        pct_return = close.pct_change(length) # (close / close.shift(length)) - 1
    # 偏移
    if offset != 0:
        pct_return = pct_return.shift(offset)
    # 处理填充
    if "fillna" in kwargs:
        pct_return.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        pct_return.fillna(method=kwargs["fill_method"], inplace=True)
    # 设置名称和类别
    pct_return.name = f"{'CUM' if cumulative else ''}PCTRET_{length}"
    pct_return.category = "performance"
    return pct_return
# 设置 percent_return 函数的文档字符串
percent_return.__doc__ = \
"""Percent Return
Calculates the percent return of a Series.
See also: help(df.ta.percent_return) for additional **kwargs a valid 'df'.
Sources:
    https://stackoverflow.com/questions/31287552/logarithmic-returns-in-pandas-dataframe
Calculation:
    Default Inputs:
        length=1, cumulative=False
    PCTRET = close.pct_change(length)
    CUMPCTRET = PCTRET.cumsum() if cumulative
Args:
    close (pd.Series): Series of 'close's
    length (int): It's period. Default: 20
    cumulative (bool): If True, returns the cumulative returns. Default: False
    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\performance\__init__.py

# 设置文件编码为 UTF-8
# 导入 drawdown 模块中的 drawdown 函数
# 导入 log_return 模块中的 log_return 函数
# 导入 percent_return 模块中的 percent_return 函数

.\pandas-ta\pandas_ta\statistics\entropy.py

# -*- coding: utf-8 -*-
# 导入 log 函数并将其命名为 npLog
from numpy import log as npLog
# 导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_series
# 定义熵指标函数,接受收盘价、周期、对数的基数、偏移量和其他参数
def entropy(close, length=None, base=None, offset=None, **kwargs):
    """Indicator: Entropy (ENTP)"""
    # 验证参数
    # 如果 length 存在且大于 0,则将其转换为整数,否则设为默认值 10
    length = int(length) if length and length > 0 else 10
    # 如果 base 存在且大于 0,则将其转换为浮点数,否则设为默认值 2.0
    base = float(base) if base and base > 0 else 2.0
    # 验证收盘价是否是一个有效的 Series,如果不是则返回 None
    close = verify_series(close, length)
    # 获取偏移量
    offset = get_offset(offset)
    # 如果收盘价为 None,则返回 None
    if close is None: return
    # 计算结果
    # 计算每个价格占总和的比例
    p = close / close.rolling(length).sum()
    # 计算熵
    entropy = (-p * npLog(p) / npLog(base)).rolling(length).sum()
    # 偏移结果
    if offset != 0:
        entropy = entropy.shift(offset)
    # 处理填充
    # 如果参数中包含 "fillna",则使用指定值填充空值
    if "fillna" in kwargs:
        entropy.fillna(kwargs["fillna"], inplace=True)
    # 如果参数中包含 "fill_method",则使用指定的填充方法填充空值
    if "fill_method" in kwargs:
        entropy.fillna(method=kwargs["fill_method"], inplace=True)
    # 设置名称和类别
    entropy.name = f"ENTP_{length}"
    entropy.category = "statistics"
    return entropy
# 设置熵指标函数的文档字符串
entropy.__doc__ = \
"""Entropy (ENTP)
Introduced by Claude Shannon in 1948, entropy measures the unpredictability
of the data, or equivalently, of its average information. A die has higher
entropy (p=1/6) versus a coin (p=1/2).
Sources:
    https://en.wikipedia.org/wiki/Entropy_(information_theory)
Calculation:
    Default Inputs:
        length=10, base=2
    P = close / SUM(close, length)
    E = SUM(-P * npLog(P) / npLog(base), length)
Args:
    close (pd.Series): Series of 'close's
    length (int): It's period. Default: 10
    base (float): Logarithmic Base. Default: 2
    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\statistics\kurtosis.py

# -*- coding: utf-8 -*-
# 从 pandas_ta.utils 模块中导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_series
# 定义函数 kurtosis,计算某个时间段内的峰度
def kurtosis(close, length=None, offset=None, **kwargs):
    """Indicator: Kurtosis"""
    # 验证参数
    # 如果 length 存在且大于 0,则将其转换为整数;否则将 length 设为默认值 30
    length = int(length) if length and length > 0 else 30
    # 如果 kwargs 中有 "min_periods" 参数且不为 None,则将其转换为整数;否则将 min_periods 设为 length 的值
    min_periods = int(kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length
    # 验证 close 参数,并确保其长度不小于 length 和 min_periods 的最大值
    close = verify_series(close, max(length, min_periods))
    # 获取偏移量
    offset = get_offset(offset)
    # 如果 close 为 None,则返回空值
    if close is None: return
    # 计算结果
    # 计算 close 的滚动窗口长度为 length 的峰度,并使用 min_periods 参数指定最小期数
    kurtosis = close.rolling(length, min_periods=min_periods).kurt()
    # 处理偏移
    if offset != 0:
        # 对计算的峰度结果进行偏移
        kurtosis = kurtosis.shift(offset)
    # 处理填充
    if "fillna" in kwargs:
        # 使用指定的值填充缺失值
        kurtosis.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        # 使用指定的填充方法填充缺失值
        kurtosis.fillna(method=kwargs["fill_method"], inplace=True)
    # 设定指标的名称和类别
    kurtosis.name = f"KURT_{length}"
    kurtosis.category = "statistics"
    # 返回计算结果
    return kurtosis
# 为函数 kurtosis 添加文档字符串
kurtosis.__doc__ = \
"""Rolling Kurtosis
Sources:
Calculation:
    Default Inputs:
        length=30
    KURTOSIS = close.rolling(length).kurt()
Args:
    close (pd.Series): Series of 'close's
    length (int): It's period. Default: 30
    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.
"""

PandasTA 源码解析(十一)(3)https://developer.aliyun.com/article/1506214

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

热门文章

最新文章

推荐镜像

更多
  • DNS