蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行初始化、交叉、波幅与指标库对比

PYTHON隔离 CPython 3.12.14、Pandas 3.1.0、Matplotlib 3.11.2;库对比固定 pandas-ta 0.4.71b0indicators.py
indicators.py197 行
"""Compute explicitly initialized indicators and compare a pinned library."""
import json
import sys
from pathlib import Path
from platform import python_version
from importlib.metadata import version
from math import isfinite, isclose, sqrt

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd


def ema(values, span):
    alpha = 2 / (span+1)
    current = values.iloc[0]
    result = [current]
    for value in values.iloc[1:]:
        current = (1-alpha)*current + alpha*value
        result.append(current)
    return pd.Series(result,index=values.index,dtype="float64")


def wilder(values, periods):
    """SMA seed from the first complete contiguous window."""
    result = pd.Series(float("nan"),index=values.index,dtype="float64")
    first = values.first_valid_index()
    if first is None:
        return result
    start = values.index.get_loc(first)
    valid = values.iloc[start:]
    if valid.isna().any():
        raise ValueError("Missing value after seed input starts")
    if len(valid)<periods:
        return result
    current = float(valid.iloc[:periods].mean())
    result.iloc[start+periods-1] = current
    for position, value in enumerate(valid.iloc[periods:],start+periods):
        current = (current*(periods-1)+value)/periods
        result.iloc[position] = current
    return result


def macd(close):
    difference = ema(close,12)-ema(close,26)
    signal = ema(difference,9)
    gap = difference-signal
    return difference, signal, gap


def cross_counts(gap):
    previous = gap.shift()
    return [int(((gap>0)&(previous<=0)).sum()),int(((gap<0)&(previous>=0)).sum())]


def rsi(close,periods=14):
    changes = close.diff()
    gain = wilder(changes.clip(lower=0),periods)
    loss = wilder(-changes.clip(upper=0),periods)
    # The flat, gain-free and loss-free cases are an explicit local convention.
    value = (100*gain/(gain+loss)).mask((gain==0)&(loss==0),50)
    return value


def bollinger(close,periods=20,ddof=0):
    window = close.rolling(periods,min_periods=periods)
    mean, spread = window.mean(),2*window.std(ddof=ddof)
    return pd.DataFrame({"lower":mean-spread,"middle":mean,"upper":mean+spread})


def atr(bars,periods=14):
    if bars.isna().any().any() or not bars.index.is_monotonic_increasing or not bars.index.is_unique:
        raise ValueError("OHLC must be complete, ordered and unique")
    if ((bars.low>bars.close)|(bars.close>bars.high)|(bars.low<=0)).any():
        raise ValueError("Closing price outside OHLC range")
    previous = bars.close.shift()
    candidates = pd.DataFrame({"range":bars.high-bars.low,"up_gap":(bars.high-previous).abs(),
                               "down_gap":(bars.low-previous).abs()})
    tr = candidates.max(axis=1)
    return tr,wilder(tr,periods),candidates.idxmax(axis=1)


def last(values):
    return round(float(values.iloc[-1]),8)


def show_chart(close, difference, signal, gap, bands, target):
    fig, axes = plt.subplots(2,1,figsize=(8,6.2),sharex=True,layout="constrained")
    price, indicator = axes
    price.plot(close,label="Close",color="#23384d")
    price.plot(bands["middle"],label="20-point mean",color="#245a92")
    price.fill_between(close.index,bands["lower"],bands["upper"],alpha=.25,color="#39a689",label="±2 σ (ddof=0)")
    indicator.plot(difference,label="DIF",color="#245a92")
    indicator.plot(signal,label="DEA",color="#8a4d15")
    indicator.bar(close.index,2*gap,color=["#16826c" if value>=0 else "#ac4e35" for value in gap],
                  label="2 × (DIF − DEA)",alpha=.55)
    indicator.axhline(0,color="#4f5c69",linewidth=.8)
    price.set(title="Synthetic close and Bollinger bands",ylabel="Price")
    indicator.set(title="MACD with an explicitly doubled histogram",xlabel="Observation",ylabel="Price difference")
    for axis in axes:
        axis.grid(alpha=.2)
        axis.legend(loc="upper left",ncols=2,fontsize=8)
    fig.savefig(target,dpi=120)
    plt.close(fig)


def independent_cases(close, target):
    dif, dea, gap = macd(close)
    pd.testing.assert_series_equal(dif,close.ewm(span=12,adjust=False).mean()-close.ewm(span=26,adjust=False).mean())
    pd.testing.assert_series_equal(dea,dif.ewm(span=9,adjust=False).mean())
    assert cross_counts(pd.Series([0.,2.,3.,0.,-1.,-2.,0.,1.])) == [2,1]
    assert cross_counts(pd.Series([1.,2.])) == [0,0]
    crosses = cross_counts(gap)
    assert all(value>0 for value in crosses)

    seed = pd.Series([10.,12.,11.,13.,12.])
    seeded = rsi(seed,3)
    simple_ewm = seed.diff().clip(lower=0).ewm(alpha=1/3,adjust=False).mean()
    assert seeded.iloc[:3].isna().all() and isclose(seeded.iloc[3],80)
    assert isclose(last(seeded),100*8/13) and not isclose(simple_ewm.iloc[3],4/3)
    edges = [last(rsi(pd.Series(seq,dtype="float64"),3)) for seq in
             ([1,2,3,4],[4,3,2,1],[4,4,4,4])]
    assert edges == [100.,0.,50.]

    sample = pd.Series([2.,4.,6.])
    wide,narrow = bollinger(sample,3,ddof=1),bollinger(sample,3,ddof=0)
    assert wide.iloc[:2].isna().all().all()
    assert isclose(last(wide["upper"]),8) and isclose(last(narrow["upper"]),4+2*sqrt(8/3))
    bands = bollinger(close)
    assert bands.iloc[:19].isna().all().all()
    show_chart(close,dif,dea,gap,bands,target)

    bars = pd.DataFrame({"high":[11.,15.,13.,13.],"low":[9.,14.,11.,10.],"close":[10.,14.5,11.5,12.]})
    tr, average, winner = atr(bars,3)
    assert tr.tolist()==[2.,5.,3.5,3.] and winner.tolist()==["range","up_gap","down_gap","range"]
    assert average.iloc[:2].isna().all() and isclose(average.iloc[2],3.5) and isclose(average.iloc[3],10/3)
    invalid = bars.copy()
    invalid.loc[1,"close"] = 20
    try:
        atr(invalid,3)
    except ValueError:
        invalid_rejected = True
    else:
        raise AssertionError("Bad OHLC was accepted")
    return (
        dict(macd=dict(dif=last(dif),dea=last(dea),histogram=last(2*gap),crossings=crosses,manual_crossings=[2,1]),
             rsi=dict(first_valid=3,first=seeded.iloc[3],next=last(seeded),flat_up_down=edges,
                      plain_ewm_seed=float(simple_ewm.iloc[3])),
             bollinger=dict(population_upper=last(narrow["upper"]),sample_upper=last(wide["upper"]),
                            plotted_last=last(bands["upper"])),
             atr=dict(tr=tr.tolist(),winners=winner.tolist(),first=average.iloc[2],next=last(average),
                      invalid_ohlc_rejected=invalid_rejected)),
        (dif,dea,gap,bands),
    )


def comparison_case(close, owned):
    import pandas_ta as ta
    dif, dea, gap, bands = owned
    lib_macd = ta.macd(close,fast=12,slow=26,signal=9,talib=False)
    lib_rsi = ta.rsi(close,length=14,talib=False)
    lib_bands = ta.bbands(close,length=20,std=2,ddof=0,talib=False)
    lib_sample_bands = ta.bbands(close,length=20,std=2,ddof=1,talib=False)
    assert list(lib_macd) == ["MACD_12_26_9","MACDh_12_26_9","MACDs_12_26_9"]
    line, hist, signal = (lib_macd[name] for name in lib_macd)
    pd.testing.assert_series_equal(hist,line-signal,check_names=False)
    upper = next(column for column in lib_bands if column.startswith("BBU_"))
    sample_upper = next(column for column in lib_sample_bands if column.startswith("BBU_"))
    pd.testing.assert_series_equal(lib_bands[upper],bands["upper"],check_names=False,check_exact=False)
    pd.testing.assert_series_equal(lib_sample_bands[sample_upper],bollinger(close,ddof=1)["upper"],
                                   check_names=False,check_exact=False)
    named = {"dif":(line,dif),"dea":(signal,dea),"unscaled_histogram":(hist,gap),
             "rsi":(lib_rsi,rsi(close)),"upper_band":(lib_bands[upper],bands["upper"])}
    actual = {}
    for key,(third_party, authored) in named.items():
        common = pd.concat([third_party,authored],axis=1).dropna()
        assert len(common)>0 and isfinite(last(third_party))
        actual[key] = dict(first_library=third_party.first_valid_index(),first_owned=authored.first_valid_index(),
            library_last=last(third_party),owned_last=last(authored),
            max_abs_common_difference=float((common.iloc[:,0]-common.iloc[:,1]).abs().max()))
    assert actual["dif"]["first_library"] > actual["dif"]["first_owned"]
    assert actual["upper_band"]["max_abs_common_difference"] < 1e-8
    return actual


if __name__ == "__main__":
    oscillation = (0,1,4,7,6,4,1,-3,-6,-5,-2,0)
    close = pd.Series([100+step*.18+oscillation[step%12] for step in range(60)],dtype="float64")
    report, owned = independent_cases(close,Path("indicator-panels.png"))
    if "--compare-library" in sys.argv:
        report["library_comparison"] = comparison_case(close,owned)
        report["library_versions"] = {name:version(name) for name in ("pandas-ta","numba","llvmlite","numpy","pandas")}
    report["versions"] = dict(python=python_version(),pandas=pd.__version__,matplotlib=matplotlib.__version__,
                              numpy=version("numpy"))
    print(json.dumps(report,indent=2,allow_nan=False))
本例需在 隔离 CPython 3.12.14、Pandas 3.1.0、Matplotlib 3.11.2;库对比固定 pandas-ta 0.4.71b0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:隔离 CPython 3.12.14、Pandas 3.1.0、Matplotlib 3.11.2;库对比固定 pandas-ta 0.4.71b0

入口文件:projects/quant-indicators/indicators.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 indicators.py,或下载右侧课程工程包。
  2. 确认本地已准备 隔离 CPython 3.12.14、Pandas 3.1.0、Matplotlib 3.11.2;库对比固定 pandas-ta 0.4.71b0。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:量化交易

课程关联工程包(登记关联20章) · 含当前章节或实例 · mbskycom202612a303.zip

下载课程关联工程包:量化交易

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a308.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习