backtest-portfolio-yuntuosixsex

A general simulated position backtesting system. It records buy orders, daily valuation snapshots, and automatic liquidations, and supports historical backtests for arbitrary exit strategies without replaying historical data. Compatible with any market that has daily data such as stocks, cryptocurrencies, and forex.

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "backtest-portfolio-yuntuosixsex" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-8cfd2bc1fd0b8b7bf3d118d587bb2807138bc991334cdafdac2e95ae9ab6118c. Verify the upstream source and version against https://skillhub.cn/skills/user_1b4883f8/backtest-portfolio-yuntuosixsex before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

skillhub.cn

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

A general simulated position backtesting system. It records buy orders, daily valuation snapshots, and automatic liquidations, and supports historical backtests for arbitrary exit strategies without replaying historical data. Compatible with any market that has daily data such as stocks, cryptocurrencies, and forex.

0 Downloads

Introduction source: third_party · user_1b4883f8 · 1.0.1 Reference

SkillPi interpretation

Tasks
Translation pending; see source documentation.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: backtest-portfolio
description: 通用模拟持仓回测系统。记录买入订单、每日估值快照、自动平仓,支持任意退出策略的历史回测,无需重放历史数据。兼容股票、加密货币、外汇等任何有日线数据的市场。
slug: backtest-portfolio-yuntuosixsex
displayName: Backtest Portfolio 模拟回测仓
version: 1.0.1
summary: 通用模拟持仓回测系统。记录买入订单、每日估值快照、自动平仓,支持任意退出策略的历史回测,无需重放历史数据。兼容股票、加密货币、外汇等任何有日线数据的市场。
license: MIT
emoji: 📊
tags:
- 回测
- 持仓管理
- 模拟交易
- 策略分析

📊 Backtest Portfolio — 模拟回测仓

一个市场无关的模拟持仓回测系统,核心设计原则只有一条:
存原材料,不存成品。

它不硬编码"买入 → 持有5天 → 卖出"这种固定流程,而是记录三条不可变的事实:

  1. 买了什么、什么时候、什么价格买(orders 表)
  2. 买入之后每一天发生了什么(daily_snapshots 表)
  3. 最终什么时候、为什么卖出、赚了多少(trades 表)

因为完整的每日价格都存成了快照,你可以在不重放历史数据的情况下,对同一批历史持仓测试任意退出策略。


为什么要做这个设计?

大多数回测工具把退出规则写死在代码里("5天后卖出")。测一次还行,但想换规则就得重头跑一遍。

这个 skill 把 数据收集 和 规则评估 拆成两个阶段:

阶段 做的事 执行时机
收集 记录买入 + 每日快照 每天(向前)
评估 用已有快照跑任意退出规则 任意时间(向后)

想试"3%移动止盈 vs 5天硬持有哪个更好"?直接查已有快照,一行代码出结果。


数据库结构

三个表,都有 UNIQUE 约束,每天重复执行不会产生重复数据:

orders — 买入记录(不可变)

字段 类型 说明
instrument TEXT 标的代码(股票代码/合约地址等)
name TEXT 名称
strategy TEXT 策略标签(如"动量突破"、"价值回归")
category TEXT 分级(如"A级"、"B级"、"核心"、"卫星")
entry_date TEXT 买入日期 (YYYY-MM-DD)
entry_price REAL 买入价
score REAL 买入评分
meta TEXT 额外字段(JSON格式)
rules_version TEXT 策略版本号

daily_snapshots — 每日估值快照(每天追加)

字段 类型 说明
instrument TEXT
date TEXT 日期
close_price REAL 当日收盘价
days_held INTEGER 持有天数(买入日=1)
high_since_entry REAL 建仓以来最高收盘价
low_since_entry REAL 建仓以来最低收盘价

trades — 已平仓记录

字段 类型 说明
instrument TEXT
entry_date, exit_date TEXT 买入/卖出日期
entry_price, exit_price REAL
days_held INTEGER 持有天数
profit_pct REAL 盈亏百分比
exit_reason TEXT timeout(超时) / stop_loss(止损) / take_profit(止盈) / trailing_stop(移动止盈) / manual(手动)

快速上手

1. 实现一个数据源(PriceProvider)

接入任何市场的行情数据,只需写一个类:

from scripts.backtest_portfolio import PriceProvider

class A股数据源(PriceProvider):
    def get_daily_prices(self, instrument: str):
        """返回按日期升序的每日行情。每条格式:{date, close, high?, low?}"""
        import baostock as bs
        bs.login()
        rs = bs.query_history_k_data_plus(
            f"sh.{instrument}" if instrument.startswith("6") else f"sz.{instrument}",
            "date,close,high,low",
            start_date="2025-01-01",
            frequency="d",
        )
        bs.logout()
        return [{"date": r[0], "close": float(r[1]),
                 "high": float(r[2]), "low": float(r[3])}
                for r in rs.get_data() if r[0]]
class 美股数据源(PriceProvider):
    def get_daily_prices(self, instrument: str):
        import yfinance as yf
        df = yf.download(instrument, period="6mo")
        return df.reset_index().rename(
            columns={"Date": "date", "Close": "close",
                     "High": "high", "Low": "low"}
        ).to_dict("records")

2. 初始化数据库

from scripts.backtest_portfolio import init_db
conn, cur = init_db("data/模拟仓.db")

3. 每天收盘后更新

from scripts.backtest_portfolio import daily_update, init_db

conn, _ = init_db("data/模拟仓.db")

# 今日评分>=88的候选建模拟仓
新买入 = [
    {"instrument": "000001", "name": "平安银行", "entry_price": 12.35,
     "strategy": "B1少妇回踩", "category": "A级", "score": 92},
    {"instrument": "600519", "name": "贵州茅台", "entry_price": 1680.00,
     "strategy": "白马趋势", "category": "A级", "score": 90},
]

报告 = daily_update(
    conn,
    price_provider=A股数据源(),
    new_orders=新买入,
    max_hold_days=10,     # 超过10天自动平仓
)
print(json.dumps(报告, indent=2, ensure_ascii=False))

4. 回测任意退出规则

from scripts.backtest_portfolio import backtest_exit_rule

# 场景A:固定持有5天
r1 = backtest_exit_rule(conn, "timeout", max_hold_days=5, min_score=80)
print(f"持有5天:{r1['total_trades']}笔交易,{r1['win_rate']}%胜率,平均{r1['avg_return']}%")

# 场景B:5天持有 + -5%止损
r2 = backtest_exit_rule(conn, "combination", max_hold_days=5, stop_loss_pct=-5.0, min_score=88)
print(f"加止损后胜率:{r2['win_rate']}% vs 裸持有{r1['win_rate']}%")

# 场景C:移动止盈(从最高点回撤8%卖出)
r3 = backtest_exit_rule(conn, "trailing_stop", trailing_stop_pct=-8.0, min_score=80)

CLI 命令行用法

# 每日更新(需要在你的脚本中提供数据源)
python scripts/backtest_portfolio.py daily --db data/模拟仓.db

# 回测(仅需数据库,无需数据源)
python scripts/backtest_portfolio.py backtest --exit combination \
    --max-hold 5 --stop-loss -5.0 --min-score 80

# 查看统计
python scripts/backtest_portfolio.py stats --by strategy

策略优化建议

  1. 让数据积累起来。快照数据越多,能测的退出规则变种就越多。
  2. 按策略分别测试。不同评分段的候选往往有最优退出方案。
  3. 对比场景。同一批持仓,同时跑多个退出规则,直接对比结果。
  4. 原始数据是永久的。想在 meta 里加新字段?JSON格式随便加,不用改表结构。

实战:比较不同退出规则

# 对比不同持有天数
for 天数 in [3, 5, 7, 10]:
    r = backtest_exit_rule(conn, "timeout", max_hold_days=天数)
    print(f"持有{天数}天:{r['total_trades']}笔,{r['win_rate']}%胜率,{r['avg_return']}%")

# 对比不同止损线
for 止损 in [-3, -5, -8, -10]:
    r = backtest_exit_rule(conn, "combination", max_hold_days=5, stop_loss_pct=止损)
    print(f"-{abs(止损)}%止损:{r['win_rate']}%胜率,{r['avg_return']}%平均收益")

几秒钟出一张胜率对比表,帮你在不同退出策略之间选出最优解——完全不需要重跑历史数据。


这个技能不是什么

  • ❌ 不是自动交易机器人 — 只记录和分析
  • ❌ 不是实盘接口 — 不连接任何券商API
  • ❌ 不绑定任何市场 — A股/港股/美股/加密货币/外汇都用同一个代码

关于

从A股实盘生产环境提取并抽象而来。原始系统运行了72个交易日,累计追踪7500+笔候选记录。三表设计 + backtest_exit_rule() 是反复迭代后的产物。

开源协议:MIT

Current listing version

1.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value92/100

Highlights

  • 提供通用模拟持仓回测系统,支持股票、加密货币、外汇等多市场
  • 创新性地将数据收集与规则评估分离,避免重复回测历史数据
  • 解决量化交易用户的核心痛点,具备高实用价值
Trigger Precision95/100

Highlights

  • description 明确描述功能边界和核心特性
  • 触发词精准完整,覆盖多种使用场景
Structure and Standards90/100

Highlights

  • 文档结构完整,包含快速上手、数据库结构、CLI 用法等
  • 提供端到端示例和实战代码,便于用户理解执行
Execution Reliability88/100

Highlights

  • 提供完整 Python 实现和数据库初始化脚本
  • 通过 UNIQUE 约束防止重复数据,覆盖主要异常场景
  • CLI 工具完善,参数设计合理
Evidence Verifiability (mean of the first four)91/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.