PandasTA 源码解析(二)(2)

本文涉及的产品
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
云解析 DNS,旗舰版 1个月
全局流量管理 GTM,标准版 1个月
简介: PandasTA 源码解析(二)

PandasTA 源码解析(二)(1)https://developer.aliyun.com/article/1506016

.\pandas-ta\pandas_ta\candles\cdl_z.py

# -*- coding: utf-8 -*-
# 从 pandas 库中导入 DataFrame 类
from pandas import DataFrame
# 从 pandas_ta.statistics 模块中导入 zscore 函数
from pandas_ta.statistics import zscore
# 从 pandas_ta.utils 模块中导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_series
# 定义一个名为 cdl_z 的函数,用于计算 Candle Type: Z Score
def cdl_z(open_, high, low, close, length=None, full=None, ddof=None, offset=None, **kwargs):
    """Candle Type: Z Score"""
    # 验证参数
    length = int(length) if length and length > 0 else 30
    ddof = int(ddof) if ddof and ddof >= 0 and ddof < length else 1
    open_ = verify_series(open_, length)
    high = verify_series(high, length)
    low = verify_series(low, length)
    close = verify_series(close, length)
    offset = get_offset(offset)
    full = bool(full) if full is not None and full else False
    # 如果输入的数据有缺失,则返回空
    if open_ is None or high is None or low is None or close is None: return
    # 计算结果
    if full:
        length = close.size
    z_open = zscore(open_, length=length, ddof=ddof)
    z_high = zscore(high, length=length, ddof=ddof)
    z_low = zscore(low, length=length, ddof=ddof)
    z_close = zscore(close, length=length, ddof=ddof)
    _full = "a" if full else ""
    _props = _full if full else f"_{length}_{ddof}"
    # 创建一个 DataFrame 对象,包含计算得到的 Z Score 结果
    df = DataFrame({
        f"open_Z{_props}": z_open,
        f"high_Z{_props}": z_high,
        f"low_Z{_props}": z_low,
        f"close_Z{_props}": z_close,
    })
    # 如果 full 为 True,则使用 backfill 方法填充缺失值
    if full:
        df.fillna(method="backfill", axis=0, inplace=True)
    # 如果 offset 不为 0,则对 DataFrame 进行偏移
    if offset != 0:
        df = df.shift(offset)
    # 处理填充值
    if "fillna" in kwargs:
        df.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        df.fillna(method=kwargs["fill_method"], inplace=True)
    # 设置 DataFrame 的名称和类别
    df.name = f"CDL_Z{_props}"
    df.category = "candles"
    return df
# 设置 cdl_z 函数的文档字符串
cdl_z.__doc__ = \
"""Candle Type: Z
Normalizes OHLC Candles with a rolling Z Score.
Source: Kevin Johnson
Calculation:
    Default values:
        length=30, full=False, ddof=1
    Z = ZSCORE
    open  = Z( open, length, ddof)
    high  = Z( high, length, ddof)
    low   = Z(  low, length, ddof)
    close = Z(close, length, ddof)
Args:
    open_ (pd.Series): Series of 'open's
    high (pd.Series): Series of 'high's
    low (pd.Series): Series of 'low's
    close (pd.Series): Series of 'close's
    length (int): The period. Default: 10
Kwargs:
    naive (bool, optional): If True, prefills potential Doji less than
        the length if less than a percentage of it's high-low range.
        Default: False
    fillna (value, optional): pd.DataFrame.fillna(value)
    fill_method (value, optional): Type of fill method
Returns:
    pd.Series: CDL_DOJI column.
"""

.\pandas-ta\pandas_ta\candles\ha.py

# 设置文件编码为 UTF-8
# 导入 DataFrame 类
from pandas import DataFrame
# 导入 get_offset 和 verify_series 函数
from pandas_ta.utils import get_offset, verify_series
# 定义 Heikin Ashi 函数
def ha(open_, high, low, close, offset=None, **kwargs):
    """Candle Type: Heikin Ashi"""
    # 验证参数,确保它们都是 pd.Series 类型
    open_ = verify_series(open_)
    high = verify_series(high)
    low = verify_series(low)
    close = verify_series(close)
    # 获取偏移量
    offset = get_offset(offset)
    # 计算结果
    m = close.size
    # 创建 DataFrame 对象,包含 HA_open、HA_high、HA_low 和 HA_close 列
    df = DataFrame({
        "HA_open": 0.5 * (open_.iloc[0] + close.iloc[0]),
        "HA_high": high,
        "HA_low": low,
        "HA_close": 0.25 * (open_ + high + low + close),
    })
    # 计算 HA_open 列
    for i in range(1, m):
        df["HA_open"][i] = 0.5 * (df["HA_open"][i - 1] + df["HA_close"][i - 1])
    # 计算 HA_high 和 HA_low 列
    df["HA_high"] = df[["HA_open", "HA_high", "HA_close"]].max(axis=1)
    df["HA_low"] = df[["HA_open", "HA_low", "HA_close"]].min(axis=1)
    # 处理偏移
    if offset != 0:
        df = df.shift(offset)
    # 处理填充
    if "fillna" in kwargs:
        df.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        df.fillna(method=kwargs["fill_method"], inplace=True)
    # 命名和分类
    df.name = "Heikin-Ashi"
    df.category = "candles"
    return df
# 设置 Heikin Ashi 函数的文档字符串
ha.__doc__ = \
"""Heikin Ashi Candles (HA)
The Heikin-Ashi technique averages price data to create a Japanese
candlestick chart that filters out market noise. Heikin-Ashi charts,
developed by Munehisa Homma in the 1700s, share some characteristics
with standard candlestick charts but differ based on the values used
to create each candle. Instead of using the open, high, low, and close
like standard candlestick charts, the Heikin-Ashi technique uses a
modified formula based on two-period averages. This gives the chart a
smoother appearance, making it easier to spots trends and reversals,
but also obscures gaps and some price data.
Sources:
    https://www.investopedia.com/terms/h/heikinashi.asp
Calculation:
    HA_OPEN[0] = (open[0] + close[0]) / 2
    HA_CLOSE = (open[0] + high[0] + low[0] + close[0]) / 4
    for i > 1 in df.index:
        HA_OPEN = (HA_OPEN[i−1] + HA_CLOSE[i−1]) / 2
    HA_HIGH = MAX(HA_OPEN, HA_HIGH, HA_CLOSE)
    HA_LOW = MIN(HA_OPEN, HA_LOW, HA_CLOSE)
    How to Calculate Heikin-Ashi
    Use one period to create the first Heikin-Ashi (HA) candle, using
    the formulas. For example use the high, low, open, and close to
    create the first HA close price. Use the open and close to create
    the first HA open. The high of the period will be the first HA high,
    and the low will be the first HA low. With the first HA calculated,
    it is now possible to continue computing the HA candles per the formulas.
Args:
    open_ (pd.Series): Series of 'open's
    high (pd.Series): Series of 'high's
    low (pd.Series): Series of 'low's
    close (pd.Series): Series of 'close's
Kwargs:
    fillna (value, optional): pd.DataFrame.fillna(value)
    fill_method (value, optional): Type of fill method
Returns:
"""
    # 创建一个 Pandas 数据帧,该数据帧包含 ha_open、ha_high、ha_low、ha_close 四列。
# 导入所需模块
import requests
import json
# 定义函数 `get_weather`,接收城市名作为参数,返回该城市的天气信息
def get_weather(city):
    # 构建 API 请求 URL,使用城市名作为查询参数
    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid=YOUR_API_KEY"
    # 发送 GET 请求获取天气数据
    response = requests.get(url)
    # 解析 JSON 格式的响应数据
    data = response.json()
    # 返回解析后的天气数据
    return data
# 定义函数 `main`,程序的入口点
def main():
    # 输入要查询的城市
    city = input("Enter city name: ")
    # 调用 `get_weather` 函数获取城市天气信息
    weather_data = get_weather(city)
    # 打印城市天气信息
    print(json.dumps(weather_data, indent=4))
# 如果该脚本直接运行,则执行 `main` 函数
if __name__ == "__main__":
    main()

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

# 声明文件编码格式为 UTF-8
# 导入 cdl_doji 模块中的 cdl_doji 函数
from .cdl_doji import cdl_doji
# 导入 cdl_inside 模块中的 cdl_inside 函数
from .cdl_inside import cdl_inside
# 导入 cdl_pattern 模块中的 cdl_pattern、cdl 和 ALL_PATTERNS as CDL_PATTERN_NAMES
from .cdl_pattern import cdl_pattern, cdl, ALL_PATTERNS as CDL_PATTERN_NAMES
# 导入 cdl_z 模块中的 cdl_z 函数
from .cdl_z import cdl_z
# 导入 ha 模块中的 ha 函数
from .ha import ha


PandasTA 源码解析(二)(3)https://developer.aliyun.com/article/1506021

相关文章
|
2月前
|
监控 网络协议 Java
Tomcat源码解析】整体架构组成及核心组件
Tomcat,原名Catalina,是一款优雅轻盈的Web服务器,自4.x版本起扩展了JSP、EL等功能,超越了单纯的Servlet容器范畴。Servlet是Sun公司为Java编程Web应用制定的规范,Tomcat作为Servlet容器,负责构建Request与Response对象,并执行业务逻辑。
Tomcat源码解析】整体架构组成及核心组件
|
21天前
|
存储 缓存 Java
什么是线程池?从底层源码入手,深度解析线程池的工作原理
本文从底层源码入手,深度解析ThreadPoolExecutor底层源码,包括其核心字段、内部类和重要方法,另外对Executors工具类下的四种自带线程池源码进行解释。 阅读本文后,可以对线程池的工作原理、七大参数、生命周期、拒绝策略等内容拥有更深入的认识。
什么是线程池?从底层源码入手,深度解析线程池的工作原理
|
25天前
|
开发工具
Flutter-AnimatedWidget组件源码解析
Flutter-AnimatedWidget组件源码解析
|
21天前
|
设计模式 Java 关系型数据库
【Java笔记+踩坑汇总】Java基础+JavaWeb+SSM+SpringBoot+SpringCloud+瑞吉外卖/谷粒商城/学成在线+设计模式+面试题汇总+性能调优/架构设计+源码解析
本文是“Java学习路线”专栏的导航文章,目标是为Java初学者和初中高级工程师提供一套完整的Java学习路线。
174 37
|
13天前
|
编解码 开发工具 UED
QT Widgets模块源码解析与实践
【9月更文挑战第20天】Qt Widgets 模块是 Qt 开发中至关重要的部分,提供了丰富的 GUI 组件,如按钮、文本框等,并支持布局管理、事件处理和窗口管理。这些组件基于信号与槽机制,实现灵活交互。通过对源码的解析及实践应用,可深入了解其类结构、布局管理和事件处理机制,掌握创建复杂 UI 界面的方法,提升开发效率和用户体验。
63 12
|
2月前
|
测试技术 Python
python自动化测试中装饰器@ddt与@data源码深入解析
综上所述,使用 `@ddt`和 `@data`可以大大简化写作测试用例的过程,让我们能专注于测试逻辑的本身,而无需编写重复的测试方法。通过讲解了 `@ddt`和 `@data`源码的关键部分,我们可以更深入地理解其背后的工作原理。
30 1
|
2月前
|
开发者 Python
深入解析Python `httpx`源码,探索现代HTTP客户端的秘密!
深入解析Python `httpx`源码,探索现代HTTP客户端的秘密!
72 1
|
2月前
|
开发者 Python
深入解析Python `requests`库源码,揭开HTTP请求的神秘面纱!
深入解析Python `requests`库源码,揭开HTTP请求的神秘面纱!
132 1
|
2月前
|
NoSQL Redis
redis 6源码解析之 ziplist
redis 6源码解析之 ziplist
25 5
|
2月前
|
算法 安全 Java
深入解析Java多线程:源码级别的分析与实践
深入解析Java多线程:源码级别的分析与实践

热门文章

最新文章

推荐镜像

更多
下一篇
无影云桌面