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

运行本章核心实例

PYTHONOwned synthetic CSV, offline charts and simulated arithmetic. No provider calls or orders.python-qt.py
python-qt.py180 行
"""蓝色天空网 mbsky.com · 使用合成行情的离线均线演算。"""
from math import isclose
from pathlib import Path
import platform
import sys

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

sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks


def close_series(frame, symbol="LAB", field="Close"):
    """Validate either a local flat schema or an explicit field/ticker pair."""
    if frame.empty:
        raise ValueError("empty price data")
    if frame.index.hasnans or frame.index.has_duplicates or not frame.index.is_monotonic_increasing:
        raise ValueError("dates must be unique and ascending")
    if frame.columns.has_duplicates:
        raise ValueError("duplicate price columns")
    if isinstance(frame.columns, pd.MultiIndex):
        candidates = [column for column in ((field, symbol), (symbol, field)) if column in frame.columns]
        if len(candidates) != 1:
            raise ValueError("expected one price column for the specified ticker")
        selected = frame[candidates[0]]
    else:
        if field not in frame.columns:
            raise ValueError("missing price column")
        selected = frame[field]
    close = pd.to_numeric(selected, errors="raise").astype(float)
    if close.isna().any() or not close.map(lambda value: 0 < value < float("inf")).all():
        raise ValueError("prices must be positive and finite")
    return close.rename("Close")


def backtest(close, fast, slow, allow_short=False):
    if not 0 < fast < slow < len(close):
        raise ValueError("need two ordered windows and a return after warm-up")
    fast_mean = close.rolling(fast, min_periods=fast).mean()
    slow_mean = close.rolling(slow, min_periods=slow).mean()
    spread = fast_mean - slow_mean
    prior = spread.shift(1)
    events = pd.Series(0, index=close.index, dtype="int64")
    events.loc[prior.le(0) & spread.gt(0)] = 1
    events.loc[prior.ge(0) & spread.lt(0)] = -1

    targets = events.where(events.ne(0)).ffill().fillna(0).astype("int64")
    if not allow_short:
        targets = targets.clip(lower=0)
    positions = targets.shift(1, fill_value=0)
    market_returns = close.pct_change(fill_method=None).fillna(0)
    strategy_returns = positions * market_returns
    equity = (1 + strategy_returns).cumprod()
    if (equity <= 0).any():
        raise ValueError("model lost all capital; simple annualization is undefined")
    baseline = close / close.iloc[0]
    drawdown = equity / equity.cummax() - 1
    intervals = len(close) - 1
    metrics = dict(total=float(equity.iloc[-1] - 1),
                   annualized=float(equity.iloc[-1] ** (252 / intervals) - 1),
                   drawdown=float(drawdown.min()), intervals=intervals)
    return pd.DataFrame(dict(close=close, fast=fast_mean, slow=slow_mean, event=events,
                             target=targets, position=positions, strategy_return=strategy_returns,
                             equity=equity, baseline=baseline, drawdown=drawdown)), metrics


def save_plot(data, columns, labels, path, y_axis):
    fig, axis = plt.subplots(figsize=(7.6, 3.5), layout="constrained")
    for column, label in zip(columns, labels, strict=True):
        axis.plot(data.index, data[column], label=label, linewidth=2)
    locator = mdates.AutoDateLocator(minticks=4, maxticks=7)
    axis.xaxis.set_major_locator(locator)
    axis.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator))
    axis.set(xlabel="Synthetic observation date", ylabel=y_axis, title="MBSKY | Synthetic price lab")
    axis.grid(alpha=0.25)
    axis.legend()
    fig.savefig(path, dpi=120, metadata={"Software": "MBSKY reproducible synthetic price lab"})
    plt.close(fig)


def near(check, label, result, expected):
    result = float(result)
    if not isclose(result, expected, rel_tol=1e-12, abs_tol=1e-12):
        raise AssertionError((label, result, expected))
    check.records.append(dict(name=label, actual=result, expected=expected, passed=True))


def check_columns(check, frame, close):
    for names in [[("Close", "LAB"), ("Volume", "LAB")], [("LAB", "Close"), ("LAB", "Volume")]]:
        layered = frame[["Close", "Volume"]].copy()
        layered.columns = pd.MultiIndex.from_tuples(names)
        check.eq("select close with " + "/".join(names[0]), close_series(layered).tolist(), close.tolist())
        check.raises("reject missing symbol with " + "/".join(names[0]), ValueError,
                     lambda: close_series(layered, symbol="MISSING"))
    check.eq("adjusted choice is explicit", close_series(frame, field="Adj Close").iloc[0].item(), 9.0)
    check.raises("reject empty frame", ValueError, lambda: close_series(frame.iloc[:0]))
    check.raises("reject missing price column", ValueError, lambda: close_series(frame[["Volume"]]))
    check.raises("reject unsorted dates", ValueError, lambda: close_series(frame.iloc[::-1]))
    check.raises("reject repeated dates", ValueError, lambda: close_series(pd.concat([frame.iloc[:1], frame])))
    for label, invalid in (("missing", float("nan")), ("zero", 0), ("infinite", float("inf"))):
        altered = frame.astype({"Close": float})
        altered.loc[altered.index[0], "Close"] = invalid
        check.raises("reject " + label + " prices", ValueError, lambda: close_series(altered))


def main():
    check = Checks()
    folder = Path(__file__).resolve().parent
    output = Path(sys.argv[1]) if len(sys.argv) > 1 else folder / "quant-lab-output"
    output.mkdir(parents=True, exist_ok=True)
    frame = pd.read_csv(folder / "quant-lab-prices.csv", parse_dates=["Date"], index_col="Date")
    close = close_series(frame)
    check.eq("CSV columns", frame.columns.tolist(), ["Open", "High", "Low", "Close", "Adj Close", "Volume"])
    check.eq("CSV first five", close.head().tolist(), [10.0, 10.0, 10.0, 12.0, 14.0])
    check.eq("CSV first and last dates",
             (close.index[0].date().isoformat(), close.index[-1].date().isoformat()), ('2024-01-02', '2024-01-15'))
    stats = close.describe()
    check.eq("describe count and range", tuple(stats.loc[["count", "min", "max"]]), (10.0, 8.0, 14.0))
    near(check, "describe mean", stats["mean"], 10.8)
    near(check, "describe median", stats["50%"], 10)
    check_columns(check, frame, close)

    data, metrics = backtest(close, 2, 3)
    check.eq("slow mean warm-up", data["slow"].isna().tolist()[:3], [True, True, False])
    check.eq("first comparable equal means", (data["fast"].iloc[2].item(), data["slow"].iloc[2].item()), (10.0, 10.0))
    check.eq("up down equality and reentry events", data["event"].tolist(), [0, 0, 0, 1, 0, 0, -1, 0, 1, 0])
    check.eq("target exposure persists", data["target"].tolist(), [0, 0, 0, 1, 1, 1, 0, 0, 1, 1])
    check.eq("execution uses prior target", data["position"].tolist(), [0, 0, 0, 0, 1, 1, 1, 0, 0, 1])
    check.eq("prior exposure still applies on exit signal", data["position"].iloc[6].item(), 1)
    near(check, "no strategy return on first upward event", data["strategy_return"].iloc[3], 0)
    near(check, "fractional return when long", data["strategy_return"].iloc[4], 1/6)
    near(check, "final strategy equity", data["equity"].iloc[-1], 7/9)
    near(check, "final buy and hold equity", data["baseline"].iloc[-1], 1.4)
    near(check, "total return", metrics["total"], -2/9)
    check.eq("return intervals exclude initial row", metrics["intervals"], 9)
    near(check, "geometric annualization", metrics["annualized"], (7/9)**28 - 1)
    near(check, "peak to trough drawdown", metrics["drawdown"], -3/7)

    short_data, _ = backtest(close, 2, 3, allow_short=True)
    check.eq("short exposure differs from flat exit", short_data["position"].iloc[8].item(), -1)
    near(check, "short exposure final equity", short_data["equity"].iloc[-1], 7/18)

    daily_spread = data["fast"] - data["slow"]
    old_state = daily_spread.gt(0).astype("int64") - daily_spread.lt(0).astype("int64")
    old_position = old_state.shift(1, fill_value=0)
    old_equity = (1 + old_position * close.pct_change(fill_method=None).fillna(0)).cumprod()
    check.eq("historical daily state is not a crossover",
             old_state.tolist(), [0, 0, 0, 1, 1, 0, -1, -1, 1, 1])
    check.eq("historical position becomes flat after an equal day", old_position.iloc[6].item(), 0)
    near(check, "historical signed daily-state equity", old_equity.iloc[-1], 35/72)

    full = pd.Series([100.0]*200+[110.0]*60+[70.0]*60, name="Close")
    normal, _ = backtest(full, 50, 200)
    check.eq("200 observation warm-up", normal["slow"].first_valid_index(), 199)
    check.eq("50 and 200 crossing indices", normal.index[normal["event"].ne(0)].tolist(), [200, 270])
    check.eq("normal windows wait one interval", normal["position"].iloc[[200, 201, 270, 271]].tolist(), [0, 1, 1, 0])
    check.raises("reject insufficient history", ValueError, lambda: backtest(close, 50, 200))

    close_path = output / "quant-close.png"
    equity_path = output / "quant-equity.png"
    save_plot(data, ["close"], ["Close"], close_path, "Price units")
    save_plot(data, ["equity", "baseline"], ["Strategy equity", "Buy and hold"], equity_path, "Equity (starts at 1)")
    for path in (close_path, equity_path):
        pixels = plt.imread(path)
        check.eq(path.name + " dimensions", tuple(pixels.shape), (420, 912, 4))
        check.eq(path.name + " contains plotted pixels", bool(pixels[:, :, :3].min() < 0.3), True)

    check.finish("python-qt", python=platform.python_version(), platform=platform.platform(),
                 pandas=pd.__version__, matplotlib=matplotlib.__version__, backend=matplotlib.get_backend(),
                 scope="Owned synthetic CSV, offline charts and simulated arithmetic. No provider calls or orders.",
                 describe={name: float(value) for name,value in stats.items()}, metrics=metrics)


if __name__ == "__main__":
    main()
本例需在 Owned synthetic CSV, offline charts and simulated arithmetic. No provider calls or orders. 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Owned synthetic CSV, offline charts and simulated arithmetic. No provider calls or orders.

入口文件:projects/python-lab/python-qt.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python-qt.py,或下载右侧课程工程包。
  2. 确认本地已准备 Owned synthetic CSV, offline charts and simulated arithmetic. No provider calls or orders.。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

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

下载课程关联工程包:Python

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

下载课程关联工程包:Python

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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