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

运行交易日历、现金分红和成本实验

PYTHON隔离 CPython 3.12 与 Matplotlib 3.11,离线合成输入market.py
market.py150 行
"""Offline market-rule and corporate-action exercise with synthetic inputs."""
from datetime import date, time
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path
import json
import platform

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

D = Decimal
CENT = D("0.01")


def next_session(trade_day, calendar, days=1):
    """Advance within the supplied exchange calendar, not calendar days."""
    return calendar[calendar.index(trade_day) + days]


def shanghai_phase(clock, is_session):
    if not is_session:
        return "closed"
    for start, end, phase in (
        (time(9, 15), time(9, 25), "opening_auction"),
        (time(9, 30), time(11, 30), "continuous"),
        (time(13), time(14, 57), "continuous"),
        (time(14, 57), time(15), "closing_auction"),
    ):
        if start <= clock < end:
            return phase
    return "outside_matching_window"


def shanghai_buy_size(board, quantity):
    if board == "main":
        return 100 <= quantity <= 1_000_000 and quantity % 100 == 0
    if board == "star_limit":
        return 200 <= quantity <= 100_000
    raise ValueError("Unknown board or order type")


def mainland_tick(price):
    return price > 0 and price % CENT == 0


def sellable_quantity(lots, session, calendar):
    """Ordinary sample stock. Each lot is (purchase date, shares)."""
    return sum(quantity for bought, quantity in lots
               if calendar.index(bought) < calendar.index(session))


def fillable_at_band(against_limit, opposite_available):
    # The caller supplies a conservative executable opposing quantity.
    return not against_limit or opposite_available > 0


def event_prices(previous, current, dividend):
    """Single cash action, with no split, tax, or assumed reinvestment."""
    reference = previous - dividend
    if not D(0) < reference <= previous or current <= 0:
        raise ValueError("Unsupported cash event or price")
    factor = reference / previous
    return {
        "raw_return": current / previous - 1,
        "adjusted_return": current / reference - 1,
        "cash_holding_return": (current + dividend) / previous - 1,
        "back_adjusted_previous": reference,
        "forward_adjusted_current": current / factor,
    }


def fees(amount, side, *, commission, minimum, stamp, transfer):
    if side not in ("buy", "sell") or amount <= 0:
        raise ValueError("Invalid fill")
    return {
        "commission": max(amount * commission, minimum).quantize(CENT, ROUND_HALF_UP),
        "stamp": (amount * stamp if side == "sell" else D(0)).quantize(CENT, ROUND_HALF_UP),
        "transfer": (amount * transfer).quantize(CENT, ROUND_HALF_UP),
    }


def run(output):
    calendar = tuple(date(2026, 11, day) for day in (6, 10, 11, 12))
    friday, tuesday, wednesday, _ = calendar
    phases = [
        shanghai_phase(time(9, 20), True), shanghai_phase(time(9, 31), True),
        shanghai_phase(time(12), True), shanghai_phase(time(14, 59), True),
        shanghai_phase(time(10), False),
    ]
    assert phases == ["opening_auction", "continuous", "outside_matching_window", "closing_auction", "closed"]
    lots = [(friday, 200)]
    assert [sellable_quantity(lots, day, calendar) for day in (friday, tuesday)] == [0, 200]
    assert [next_session(friday, calendar, d) for d in (1, 2)] == [tuesday, wednesday]
    sizes = [shanghai_buy_size(board, quantity) for board, quantity in
             (("main", 150), ("main", 200), ("star_limit", 199), ("star_limit", 201))]
    ticks = [mainland_tick(D(price)) for price in ("10.01", "10.005")]
    band = [fillable_at_band(True, n) for n in (0, 100)]
    assert sizes == [False, True, False, True] and ticks == [True, False] and band == [False, True]

    action = event_prices(D("100"), D("97"), D("4"))
    assert action["raw_return"] == D("-.03") and action["cash_holding_return"] == D(".01")
    assert action["back_adjusted_previous"] == D("96")
    assert abs(action["adjusted_return"] - (action["forward_adjusted_current"] / 100 - 1)) < D("1e-25")
    assert event_prices(D("100"), D("100"), D("0"))["adjusted_return"] == 0
    try:
        event_prices(D("100"), D("97"), D("100"))
    except ValueError:
        rejected_invalid = True
    else:
        rejected_invalid = False
    assert rejected_invalid

    prices = (D("99"), D("100"), D("97"), D("98"))
    adjusted = (prices[0] * D(".96"), D("96"), prices[2], prices[3])
    fig, ax = plt.subplots(figsize=(8, 3.7), layout="constrained")
    labels = ("Before -1", "Before", "Ex-date", "After")
    ax.plot(labels, [float(p) for p in prices], "o-", label="Raw close", color="#23364b")
    ax.plot(labels, [float(p) for p in adjusted], "o-", label="Latest-anchored", color="#008171")
    ax.axvline(2, color="#ac5727", linestyle="--", alpha=.65)
    ax.set(ylabel="Synthetic price", title="A cash dividend changes the price basis")
    ax.grid(alpha=.2)
    ax.legend()
    fig.savefig(output, dpi=120)
    plt.close(fig)

    rates = dict(commission=D(".00025"), minimum=D("5"), stamp=D(".0005"), transfer=D(".00001"))
    small = [fees(D("10000"), side, **rates) for side in ("buy", "sell")]
    large = fees(D("100000"), "buy", **rates)
    assert list(small[0].values()) == [D("5.00"), D("0.00"), D("0.10")]
    assert list(small[1].values()) == [D("5.00"), D("5.00"), D("0.10")]
    assert large["commission"] == D("25.00")
    explicit_cost = sum(value for side in small for value in side.values())
    slippage = (D("100.02") - D("100")) * 100
    assert explicit_cost == D("15.20") and slippage == D("2.00")
    return {
        "versions": {"python": platform.python_version(), "matplotlib": matplotlib.__version__},
        "sessions": {"phases": phases, "sellable": [0, 200], "settlement": [str(tuesday), str(wednesday)]},
        "orders": {"sizes_accepted": sizes, "ticks_accepted": ticks, "executable_at_limit": band},
        "corporate_action": {**{key: str(value) for key, value in action.items()}, "rejected_invalid": rejected_invalid},
        "price_plot": {"labels": labels, "raw": list(map(str, prices)), "adjusted": list(map(str, adjusted))},
        "costs": {"small_buy": list(map(str, small[0].values())), "small_sell": list(map(str, small[1].values())),
                  "large_buy_commission": str(large["commission"]), "explicit_round_trip": str(explicit_cost),
                  "buy_slippage_only": str(slippage)},
    }


if __name__ == "__main__":
    print(json.dumps(run(Path("cash-action.png")), indent=2))
本例需在 隔离 CPython 3.12 与 Matplotlib 3.11,离线合成输入 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:隔离 CPython 3.12 与 Matplotlib 3.11,离线合成输入

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

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 market.py,或下载右侧课程工程包。
  2. 确认本地已准备 隔离 CPython 3.12 与 Matplotlib 3.11,离线合成输入。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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