### Verify PyPI Installation and Version Source: https://github.com/waditu/czsc/blob/master/docs/release_checklist.md After installing a specific version of the czsc package, this snippet verifies that the installed version matches the expected version. ```bash pip install czsc== python -c "import czsc; print(czsc.__version__)" ``` -------------------------------- ### Sync Dependencies with UV Source: https://github.com/waditu/czsc/blob/master/CLAUDE.md Use 'uv sync' to manage project dependencies. Run with '--extra dev' to install development tools, or '--extra all' to install all dependency combinations. This command is typically run when pyproject.toml or uv.lock changes. ```bash uv sync --extra dev ``` ```bash uv sync --extra all ``` -------------------------------- ### Run auto-czsc-quant with Example Configuration Source: https://github.com/waditu/czsc/blob/master/scripts/auto-czsc-quant/README.md Execute the main command to run the auto-czsc-quant script with a specified configuration file. This is the primary command for initiating an experiment. ```bash PYTHONPATH=scripts/auto-czsc-quant uv run python -m auto_quant.cli run \ --config scripts/auto-czsc-quant/configs/example.json ``` -------------------------------- ### Run auto-czsc-quant with Tushare and LLM Source: https://github.com/waditu/czsc/blob/master/scripts/auto-czsc-quant/README.md Example command to run the script using Tushare for real market data and an LLM for generating position candidates. Ensure TUSHARE_TOKEN and LLM environment variables are configured. ```bash PYTHONPATH=scripts/auto-czsc-quant uv run python -m auto_quant.cli run \ --config scripts/auto-czsc-quant/configs/example.tushare-llm.json ``` -------------------------------- ### Get Signal Name Template Source: https://github.com/waditu/czsc/blob/master/docs/examples.md Obtain the key template for a specific signal name. This helps in understanding the expected format for signal keys. ```python czsc._native.signals.bar.get_signal_template(name) ``` -------------------------------- ### Import Streamlit ACE Editor Source: https://github.com/waditu/czsc/blob/master/tests/compat/baselines/streamlit_imports.txt Imports the Streamlit ACE editor component for integrating a code editor within Streamlit apps. Ensure streamlit_ace is installed. ```python from streamlit_ace import st_ace ``` -------------------------------- ### Get Package Version Source: https://github.com/waditu/czsc/blob/master/docs/public_api.md Retrieves the current version of the CZSC package. ```python from czsc import __version__ print(__version__) ``` -------------------------------- ### Add Typer Dependency to pyproject.toml Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md Append the Typer dependency to the [project].dependencies list in pyproject.toml. This ensures Typer is installed with the project. ```toml "typer>=0.12.0", ``` -------------------------------- ### K-line Synthesis and Multi-level Analysis with BarGenerator Source: https://github.com/waditu/czsc/blob/master/README.md Utilizes the BarGenerator to synthesize K-lines across different frequencies, starting from a base frequency. This is useful for creating higher-frequency bars from lower-frequency data or vice-versa. ```python from czsc import BarGenerator, Freq # 使用 BarGenerator 进行 K 线合成 bg = BarGenerator(base_freq='1分钟', freqs=['5分钟', '30分钟', '日线']) for bar in raw_bars: bg.update(bar) # 获取各周期 K 线 bars_5m = bg.bars['5分钟'] bars_30m = bg.bars['30分钟'] ``` -------------------------------- ### Welcome Message Source: https://github.com/waditu/czsc/blob/master/docs/public_api.md Prints a welcome message that includes the package version, a random quote, and caching information. ```python from czsc import welcome welcome() ``` -------------------------------- ### Package Metadata Source: https://github.com/waditu/czsc/blob/master/docs/public_api.md Access essential package metadata such as version, author, email, and release date. The `welcome` function provides a convenient way to display this information along with other startup details. ```APIDOC ## Package Metadata | API | Purpose | Implementation Location | |--------------|----------------------------------------------------------------------|-------------------------| | `__version__`| Package version number (unique source: `Cargo.toml [workspace.package].version`) | `czsc/__init__.py:140` | | `__author__` | Author | `czsc/__init__.py:144` | | `__email__` | Email | `czsc/__init__.py:145` | | `__date__` | Release date | `czsc/__init__.py:146` | | `welcome` | Print version number, random motto, and cache information | `czsc/__init__.py:258` | ``` -------------------------------- ### Get CZSC Cache Directory Size Source: https://github.com/waditu/czsc/blob/master/docs/examples.md Check the current disk space usage of the default CZSC cache directory. ```python czsc.get_dir_size(czsc.home_path) ``` -------------------------------- ### Define CZSC CLI Entry Point in pyproject.toml Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md Configure the entry point for the CZSC CLI in pyproject.toml under the [project.scripts] section. This allows the CLI to be executed directly using the 'czsc' command. ```toml [project.scripts] czsc = "czsc.cli:app" ``` -------------------------------- ### Import Streamlit Lightweight Charts Source: https://github.com/waditu/czsc/blob/master/tests/compat/baselines/streamlit_imports.txt Imports the renderLightweightCharts function for displaying lightweight charts in Streamlit. Requires the streamlit-lightweight-charts library. ```python from streamlit_lightweight_charts import renderLightweightCharts # noqa: PLC0415 ``` -------------------------------- ### Registering Custom Signals with Macros Source: https://github.com/waditu/czsc/blob/master/crates/czsc-signal-macros/README.md Demonstrates how to use `#[signal_module]` to group signals and `#[signal]` to mark individual signal functions for automatic registration. Ensure necessary imports are present. ```rust use czsc_signal_macros::{signal, signal_module}; #[signal_module(category = "kline")] pub mod my_signals { use super::*; #[signal(template = "{freq}_我的信号_V250101")] pub fn sig_v250101(/* ... */) -> /* ... */ { /* ... */ } } ``` -------------------------------- ### Get List of Signal Names Source: https://github.com/waditu/czsc/blob/master/docs/examples.md Retrieve all available signal names registered in the native Rust backend. This function returns a comprehensive list across all submodules. ```python czsc._native.signals.bar.list_signal_names() ``` -------------------------------- ### Run Pre-Release Checks Source: https://github.com/waditu/czsc/blob/master/docs/release_checklist.md Execute a comprehensive script to verify code formatting, linting, build, tests, Python bindings generation, and package compatibility before pushing a tag. This script combines multiple checks to ensure the release is ready. ```bash set -e cargo fmt --all -- --check cargo clippy --workspace --all-targets -- -D warnings cargo build --workspace --release cargo test -p czsc-derive -p czsc-core -p czsc-utils -p czsc-ta -p czsc-signal-macros PYO3_PYTHON=$(uv run python -c 'import sys; print(sys.executable)') \ cargo run --bin stub_gen -p czsc-python --no-default-features --features stub-gen git diff --exit-code czsc/_native/__init__.pyi uv run maturin develop --release uv run --no-sync ruff format --check czsc/ tests/ uv run --no-sync ruff check czsc/ tests/ uv run --no-sync pytest --run-slow uv run python -c "import czsc; print('version:', czsc.__version__)" # §7 cargo check ratchet(rc.8 教训)—— 模拟下游纯 Rust 用户拉发布产物 # 注意:本地 cargo check --workspace 会因 path = "..." 短路,看不到 # crates.io 上的版本解析问题;必须在干净项目里 cargo add 才能复现。 # 这一段建议在 PR push tag **之后**、cargo publish dispatch **之前** # 跑一次(用 dry-run 产物或 TestPyPI/crates.io-staging 镜像)。 echo "✅ 本地预检全部通过" ``` -------------------------------- ### CZSC CLI Entry Point Implementation Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md The main entry point for the CZSC CLI, using Typer to assemble and register various subcommands. It supports a '--json' output option for LLM friendliness. ```python """CZSC 命令行工具入口。 通过 `czsc <子命令>` 调用;所有命令支持 `--json` 输出(LLM 友好)。 """ from __future__ import annotations import typer from czsc.cli import analyze, backtest, bench, data, plot, research, schema, signals app = typer.Typer( help="CZSC 缠论技术分析命令行工具", no_args_is_help=True, add_completion=False, ) app.add_typer(signals.app, name="signals", help="信号目录与文档") app.add_typer(research.app, name="research", help="策略研究 / 回放 / 配置解析") app.add_typer(data.app, name="data", help="造数与质量校验") app.add_typer(plot.app, name="plot", help="缠论 / 信号 HTML 可视化") app.command("analyze", help="对一段 K 线跑缠论,输出分型 + 笔")(analyze.analyze) app.command("backtest", help="传入 Position 对象 + 数据源,产出回测结果")(backtest.backtest) app.command("bench", help="CZSC / CzscTrader 吞吐量基准")(bench.bench) app.command("schema", help="吐出全部命令/参数 schema 供 LLM 自发现")(schema.schema) if __name__ == "__main__": app() ``` -------------------------------- ### Importing Data Connectors Source: https://github.com/waditu/czsc/blob/master/docs/public_api.md Demonstrates how to import data connectors from the czsc.connectors module. You can import the entire module or specific functions. ```python from czsc.connectors import ts_connector # 或 from czsc.connectors.ts_connector import get_raw_bars ``` -------------------------------- ### CLI Commands for auto-czsc-quant Source: https://github.com/waditu/czsc/blob/master/scripts/auto-czsc-quant/README.md Primary command-line interface commands for running experiments and generating prompts for LLM optimization. ```bash PYTHONPATH=scripts/auto-czsc-quant uv run python -m auto_quant.cli run --config PYTHONPATH=scripts/auto-czsc-quant uv run python -m auto_quant.cli prompt --run-dir ``` -------------------------------- ### Chants Visualization and Backtest Report Generation Source: https://github.com/waditu/czsc/blob/master/README.md Provides functions for visualizing Chants K-lines across multiple periods and generating HTML backtest reports. 'plot_czsc' and 'plot_czsc_trader' create interactive HTML visualizations, while 'generate_backtest_report' produces a comprehensive report from backtest data. ```python # 缠论 K 线(多周期联立,自包含 HTML,离线即可打开) from czsc.utils.plotting.lightweight import plot_czsc, plot_czsc_trader html = plot_czsc(c, output="html") # 单周期 plot_czsc_trader(ct, output="html", path="trader.html") # 多周期 # 回测 HTML 报告:用 wbt.generate_backtest_report 一键产出 from wbt import generate_backtest_report generate_backtest_report(df=dfw, output_path="report.html", weight_type="ts") ``` -------------------------------- ### Generate Mock K-line Data and Analyze Core Chants Source: https://github.com/waditu/czsc/blob/master/README.md Generates simulated 30-minute K-line data for a given symbol and date range. It then converts this data into RawBar objects and initializes a CZSC analysis object to automatically identify 'fenxing', 'bi', and 'zhongshu'. ```python import czsc from czsc import CZSC, Freq, format_standard_kline from czsc.mock import generate_symbol_kines # 生成模拟 K 线数据 df = generate_symbol_kines('000001', '30分钟', '20240101', '20240601') # 转换为 RawBar 对象列表 bars = format_standard_kline(df, freq=Freq.F30) # 创建 CZSC 分析对象(自动识别分型、笔、中枢) czsc_obj = CZSC(bars) print(f"笔数量:{len(czsc_obj.bi_list)}") print(f"中枢数量:{len(czsc_obj.zs_list)}") ``` -------------------------------- ### Initial CLI Skeleton Test Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md A basic test for the CZSC CLI skeleton using Typer's CliRunner. It verifies that the help message lists all registered subcommands. ```python from typer.testing import CliRunner from czsc.cli import app runner = CliRunner() def test_app_help_lists_subcommands(): result = runner.invoke(app, ["--help"]) assert result.exit_code == 0 for name in ["signals", "analyze", "backtest", "research", "data", "plot", "bench", "schema"]: assert name in result.output ``` -------------------------------- ### Weighted Backtesting with CZSC Source: https://github.com/waditu/czsc/blob/master/README.md Performs weighted backtesting using simulated K-line data that includes weights. It initializes the WeightBacktest object with the data and a fee rate, then prints the summary statistics of the backtest. ```python from czsc import WeightBacktest from czsc.mock import generate_klines_with_weights # 生成带权重的模拟数据 dfw = generate_klines_with_weights(seed=42) # 运行权重回测 wb = WeightBacktest(dfw, fee_rate=0.0002) print(wb.stats) # 回测统计汇总 ``` -------------------------------- ### Commit Bench Command Implementation Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md This bash command stages and commits the changes for the `bench` command implementation and its corresponding test file. ```bash git add czsc/cli/bench.py tests/cli/test_bench.py git commit -m "feat(cli): bench(CZSC 吞吐量基准,案例 4)" ``` -------------------------------- ### Implement CZSC Bench Command Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md This Python code implements the `bench` command for the CZSC CLI. It generates mock kline data, measures the time taken for CZSC object construction and incremental updates, and outputs the results. ```python """bench 命令:CZSC 吞吐量基准(沿用 examples/17 逻辑)。""" from __future__ import annotations import time import typer from czsc.cli import _io app = typer.Typer() def bench( years: int = typer.Option(20, "--years", help="模拟数据年数"), freq: str = typer.Option("5分钟", "--freq", help="频率"), symbol: str = typer.Option("000001", "--symbol", help="标的"), json_out: bool = typer.Option(False, "--json", help="JSON 输出"), ) -> None: """本地复现 CZSC 单周期吞吐量(bars/s)。""" with _io.error_boundary(json_out): from czsc import CZSC, format_standard_kline from czsc.mock import generate_symbol_kines end_year = 2024 sdt = f"{end_year - years:04d}0101" edt = f"{end_year:04d}0101" df = generate_symbol_kines(symbol, _io.freq_to_cn(freq), sdt, edt) bars = format_standard_kline(df, _io.freq_to_cn(freq)) n = len(bars) t0 = time.perf_counter() c = CZSC(bars) construct_sec = time.perf_counter() - t0 t1 = time.perf_counter() c2 = CZSC(bars[:1]) for bar in bars[1:]: c2.update(bar) update_sec = time.perf_counter() - t1 out = { "symbol": symbol, "freq": _io.freq_to_cn(freq), "bars": n, "czsc_construct": {"sec": round(construct_sec, 4), "bars_per_sec": round(n / construct_sec)}, "czsc_update": {"sec": round(update_sec, 4), "bars_per_sec": round(n / update_sec)}, } def human(d): typer.echo(f"{d['symbol']} {d['freq']} bars={d['bars']}") typer.echo(f" 构造: {d['czsc_construct']['bars_per_sec']:>10,} bars/s") typer.echo(f" 增量推进:{d['czsc_update']['bars_per_sec']:>10,} bars/s") _io.emit(out, json_out=json_out, human=human) ``` -------------------------------- ### 数据格式转换:生成CZSC对象 Source: https://github.com/waditu/czsc/blob/master/CLAUDE.md 演示如何从mock数据生成CZSC分析对象。需要从czsc顶层命名空间导入CZSC, Freq, format_standard_kline和generate_symbol_kines。 ```python from czsc import CZSC, Freq, format_standard_kline from czsc.mock import generate_symbol_kines # 生成K线数据 df = generate_symbol_kines('000001', '30分钟', '20240101', '20240105') # 转换为RawBar对象列表 bars = format_standard_kline(df, freq=Freq.F30) # 创建CZSC分析对象 czsc_obj = CZSC(bars) ``` -------------------------------- ### Format and Check Code with Ruff Source: https://github.com/waditu/czsc/blob/master/CLAUDE.md Utilize 'uv run' with Ruff for code formatting and checking. This command ensures code adheres to project standards. It's recommended to use Ruff for formatting and checking instead of Black, isort, or Flake8. ```bash uv run --no-sync ruff format czsc/ tests/ ``` ```bash uv run --no-sync ruff check czsc/ tests/ ``` -------------------------------- ### Rust Core Components Source: https://github.com/waditu/czsc/blob/master/CLAUDE.md The project utilizes Rust for its core components, compiled via PyO3 into Python extensions. This includes core types like CZSC, FX, BI, and utility functions for market analysis. ```rust crates/czsc-python (PyO3 binding total entry point, the only crate enabling "pyo3/extension-module") ``` -------------------------------- ### Environment Variables for Tushare and LLM Source: https://github.com/waditu/czsc/blob/master/scripts/auto-czsc-quant/README.md Default environment variables read from .env for Tushare data access and Anthropic-compatible LLM configuration. ```text TUSHARE_TOKEN=... ANTHROPIC_BASE_URL=... ANTHROPIC_API_KEY=... ANTHROPIC_MODEL=... ``` -------------------------------- ### Backtesting and Strategies Source: https://github.com/waditu/czsc/blob/master/README.md Tools for backtesting trading strategies. ```APIDOC ### Backtesting and Strategies - **`WeightBacktest`**: Weight-based backtesting (from wbt). - **`CzscStrategyBase`**: Base class for CZSC strategies (Python). - **`CzscJsonStrategy`**: Strategy defined in JSON format (Python). ``` -------------------------------- ### Logging and Alerting Tools Source: https://github.com/waditu/czsc/blob/master/docs/public_api.md Utilities for logging strategy information and capturing warning messages. ```APIDOC ## log_strategy_info ### Description Prints detailed information about strategy data, including symbols, time range, and weight statistics. ### Implementation Location `czsc/utils/log.py:5` ``` ```APIDOC ## capture_warnings ### Description A context manager for capturing warning messages. ### Implementation Location `czsc/utils/warning_capture.py:14` ``` ```APIDOC ## execute_with_warning_capture ### Description Executes a function and captures any warning messages generated during its execution. ### Implementation Location `czsc/utils/warning_capture.py:66` ``` -------------------------------- ### Mock Data Generation Source: https://github.com/waditu/czsc/blob/master/docs/public_api.md The `czsc.mock` module allows for the generation of synthetic K-line data for backtesting and development purposes. It includes functions to create data for single symbols or multiple symbols with weights. ```APIDOC ## Mock Data (mock) Defined in `czsc/mock.py`, forwarded to `wbt.mock`. | API | Purpose | Implementation Location | Internal Dependencies | |-----------------------------|----------------------------------------------------------------------|--------------------------------|-----------------------| | `generate_symbol_kines` | Generate random K-line DataFrame for a single symbol and period | `czsc/mock.py:33` → forwards `wbt.mock.mock_symbol_kline` | `wbt.mock` | | `generate_klines_with_weights` | Generate K-lines with weight columns for multi-symbol backtesting | `czsc/mock.py:61` → forwards `wbt.mock.mock_weights` | `wbt.mock` | **Usage**: ```python from czsc.mock import generate_symbol_kines df = generate_symbol_kines("000001", "30分钟", "20240101", "20240601") ``` ``` -------------------------------- ### Multi-level Analysis with CzscTrader Source: https://github.com/waditu/czsc/blob/master/CLAUDE.md The 'CzscTrader' class enables multi-level analysis across different timeframes (e.g., 1-minute, 5-minute, 30-minute, daily) for comprehensive market decision-making. ```python from czsc.traders import CzscTrader ``` -------------------------------- ### Verify Rust Crate Addition and Compilation Source: https://github.com/waditu/czsc/blob/master/docs/release_checklist.md This snippet demonstrates how to add the czsc crate to a new Rust project and ensure it compiles successfully. It includes checks for potential versioning conflicts and unwanted Python toolchain dependencies. ```bash TMPD=$(mktemp -d); cd "$TMPD" cargo init --name release_smoke --quiet cargo add 'czsc@=' --quiet cargo check 2>&1 | tail -20 # 必须 0 错误 cargo tree -i polars-core 2>&1 | head -10 # 必须单一版本,无 0.42/0.52 双版本冲突 cd - && rm -rf "$TMPD" ``` -------------------------------- ### Placeholder for Bench Function Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md A placeholder function for the 'bench' command. This will be replaced with the actual implementation in a later task. ```python from __future__ import annotations def bench(): ... # 占位,Task 4 替换 ``` -------------------------------- ### Basic CZSC Analysis Usage in Rust Source: https://github.com/waditu/czsc/blob/master/crates/czsc/README.md Initialize the CZSC analyzer with raw bar data and a lookback period. This snippet demonstrates how to access the direction of the latest bi-list entry. ```rust use czsc::{CZSC, RawBar, Freq, BarGenerator, is_trading_time}; use czsc::analyze::CZSC as Analyzer; let bars: Vec = /* ... */; let analyzer = Analyzer::new(bars, 50); println!("最新一笔方向: {:?}", analyzer.bi_list.last().map(|b| b.direction)); ``` -------------------------------- ### Placeholder for Backtest Function Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md A placeholder function for the 'backtest' command. This will be replaced with the actual implementation in a later task. ```python from __future__ import annotations def backtest(): ... # 占位,Task 4 替换 ``` -------------------------------- ### Import Streamlit Library Source: https://github.com/waditu/czsc/blob/master/tests/compat/baselines/streamlit_imports.txt Standard import for using Streamlit functionalities. This is a common pattern across many Streamlit applications. ```python import streamlit as st ``` -------------------------------- ### General Utility Functions Source: https://github.com/waditu/czsc/blob/master/docs/public_api.md A collection of utility functions for common tasks such as importing modules by name, sorting frequencies, printing DataFrame samples, converting DataFrames to Arrow format, and extracting Python namespaces. ```APIDOC ## import_by_name ### Description Imports a module, class, or function dynamically through a string. ### Implementation Location `czsc/utils/__init__.py:175` ``` ```APIDOC ## freqs_sorted ### Description Sorts and removes duplicates from a list of K-line frequencies. ### Implementation Location `czsc/utils/__init__.py:198` ``` ```APIDOC ## print_df_sample ### Description Prints the first N rows of a DataFrame in reST table format. ### Implementation Location `czsc/utils/__init__.py:211` ``` ```APIDOC ## to_arrow ### Description Converts a DataFrame into Arrow IPC byte string format. ### Implementation Location `czsc/utils/__init__.py:222` ``` ```APIDOC ## get_py_namespace ### Description Retrieves the namespace from a Python script file. ### Implementation Location `czsc/utils/__init__.py:128` ``` ```APIDOC ## code_namespace ### Description Retrieves the namespace from a Python code string. ### Implementation Location `czsc/utils/__init__.py:156` ``` ```APIDOC ## cross_sectional_ic ### Description Calculates cross-sectional correlation (IC / ICIR). ### Implementation Location `czsc/utils/analysis/corr.py:20` ``` ```APIDOC ## index_composition ### Description Synthesizes index K-lines with yield rate weighting. ### Implementation Location `czsc/utils/index_composition.py:11` ``` -------------------------------- ### Signals CLI Plot Command Implementation Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md Python implementation for the `plot signals` CLI command, which visualizes trading signals overlaid on K-line charts in an HTML file. It loads market data, signal configurations, and generates the plot. ```python def signals_cmd( input: str = typer.Argument(..., help="标准行情文件"), signals_config: str = typer.Option(..., "--signals-config", help="signals_config JSON 文件"), freq: str = typer.Option("30分钟", "--freq", help="频率"), output: str = typer.Option("signals.html", "-o", "--output", help="HTML 输出路径"), sdt: str = typer.Option("20170101", "--sdt", help="信号起始日期"), tail_bars: int = typer.Option(None, "--tail-bars", help="只画最后 N 根"), json_out: bool = typer.Option(False, "--json", help="JSON 输出"), ) -> None: """信号叠加到 K 线主图 HTML(plot_czsc_signals)。""" with _io.error_boundary(json_out): from czsc import format_standard_kline from czsc.utils.plotting.lightweight import plot_czsc_signals df = _io.load_bars_df(input) bars = format_standard_kline(df, _io.freq_to_cn(freq)) cfg = json.loads(open(signals_config, encoding="utf-8").read()) plot_czsc_signals(bars, signals_config=cfg, output="html", path=output, sdt=sdt, tail_bars=tail_bars) _io.emit({"output": output}, json_out=json_out, human=lambda d: typer.echo(f"已写入 {d['output']}")) ``` -------------------------------- ### Environment Variables Source: https://github.com/waditu/czsc/blob/master/docs/public_api.md The `czsc.envs` module provides functions to access and manage environment-specific configurations, such as logging verbosity and parameters for technical analysis calculations. ```APIDOC ## Environment Variables (envs) Defined in `czsc/envs.py`, exposed via the `czsc.envs` sub-module. | API | Purpose | Implementation Location | Internal Dependencies | |-------------------|------------------------------------------------------------|-------------------------|-----------------------| | `get_verbose` | Get whether detailed logging is enabled (`CZSC_VERBOSE`) | `czsc/envs.py:35` | None | | `get_min_bi_len` | Get minimum bi length (`CZSC_MIN_BI_LEN`, default 6) | `czsc/envs.py:40` | None | | `get_max_bi_num` | Get maximum number of bis (`CZSC_MAX_BI_NUM`, default 50) | `czsc/envs.py:46` | None | ``` -------------------------------- ### Add Dependencies for Czsc Signal Macros Source: https://github.com/waditu/czsc/blob/master/crates/czsc-signal-macros/README.md Include these dependencies in your Cargo.toml file to use the czsc-signal-macros and related crates. ```toml [dependencies] czsc-signal-macros = "1.0" czsc-signals = "1.0" inventory = "0.3" ``` -------------------------------- ### Strategy Research and Replay with CZSC Source: https://github.com/waditu/czsc/blob/master/README.md Facilitates strategy research and replay functionalities. 'run_replay' is used for single-symbol backtesting, while 'run_research' enables batch processing across multiple symbols. ```python from czsc import run_research, run_replay # 单品种回放 run_replay(bars, signals_seq, pos_seq, res_path='./results/') # 批量品种研究 run_research(symbols, signals_seq, pos_seq, res_path='./results/') ``` -------------------------------- ### Test Plot Signals Writes HTML Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md Tests the `plot signals` command to verify HTML generation for trading signals. It requires a temporary CSV of market data and a JSON configuration file for signals. ```python def test_plot_signals_writes_html(tmp_path): p = _bars_csv(tmp_path) cfg = tmp_path / "cfg.json" cfg.write_text('[{"name": "30分钟_D1_表里关系V230101_向上_任意_任意_0"}]') out = tmp_path / "s.html" r = runner.invoke(app, ["plot", "signals", str(p), "--signals-config", str(cfg), "--freq", "30分钟", "-o", str(out)]) assert r.exit_code == 0, r.output assert out.exists() and out.stat().st_size > 0 ``` -------------------------------- ### Placeholder for Analyze Function Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md A placeholder function for the 'analyze' command. This will be replaced with the actual implementation in a later task. ```python from __future__ import annotations def analyze() -> None: # 占位,Task 4 替换 ... ``` -------------------------------- ### Generate CZSC Trading Signals Source: https://github.com/waditu/czsc/blob/master/README.md Configures and generates trading signals based on a predefined sequence of signal functions, including those implemented in Rust for performance. It parses frequency and configuration requirements for the signals. ```python from czsc import generate_czsc_signals, get_signals_config, get_signals_freqs # 配置信号序列(使用 Rust 实现的信号函数) signals_seq = [ "czsc._native.signals.bar.bar_end_V230331", "czsc._native.signals.cxt.cxt_bi_status_V230101", ] # 解析信号所需的周期配置 freqs = get_signals_freqs(signals_seq) config = get_signals_config(signals_seq) # 生成信号序列 results = generate_czsc_signals(bars, signals_seq) ``` -------------------------------- ### Test Plot CZSC Writes HTML Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md Tests the `plot czsc` command to ensure it generates a non-empty HTML file for CZSC structures. Requires a temporary CSV file of market data. ```python from typer.testing import CliRunner from czsc.cli import app runner = CliRunner() def _bars_csv(tmp_path): from czsc.mock import generate_symbol_kines p = tmp_path / "k.csv" generate_symbol_kines("000001", "30分钟", "20230101", "20240101").to_csv(p, index=False) return p def test_plot_czsc_writes_html(tmp_path): p = _bars_csv(tmp_path) out = tmp_path / "c.html" r = runner.invoke(app, ["plot", "czsc", str(p), "--freq", "30分钟", "-o", str(out)]) assert r.exit_code == 0, r.output assert out.exists() and out.stat().st_size > 0 ``` -------------------------------- ### Placeholder for Schema Function Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md A placeholder function for the 'schema' command. This will be replaced with the actual implementation in a later task. ```python from __future__ import annotations def schema(): ... # 占位,Task 4 替换 ``` -------------------------------- ### CZSC Data Connectors Source: https://github.com/waditu/czsc/blob/master/CLAUDE.md The 'czsc/connectors/' module provides data source connectors for various providers like Tianqin, Tushare, and CCXT. It also includes 'local_data.py' for accessing CZSC research shared data locally. ```python from czsc.connectors.local_data import LocalConnector ``` -------------------------------- ### Import Streamlit Components Source: https://github.com/waditu/czsc/blob/master/tests/compat/baselines/streamlit_imports.txt Imports Streamlit's components module, often used for embedding custom HTML or third-party components. Requires Streamlit version 1.0 or higher. ```python import streamlit.components.v1 as components # noqa: PLC0415 ``` -------------------------------- ### Data Utilities Source: https://github.com/waditu/czsc/blob/master/README.md Utilities for generating and formatting market data. ```APIDOC ### Data Utilities - **`generate_symbol_kines`**: Generates test K-line data (from wbt). - **`format_standard_kline`**: Converts DataFrame to a list of `RawBar` objects. ``` -------------------------------- ### Candidate JSONL Format Source: https://github.com/waditu/czsc/blob/master/scripts/auto-czsc-quant/README.md Defines the structure for a single candidate position in a JSONL file. Each line represents a unique trial with an ID, a hypothesis, and the position configuration. ```json {"id":"trial_001","hypothesis":"入场优化:在开多 event 加入顶分型过滤","position":{...}} ``` -------------------------------- ### Run Tests with UV Source: https://github.com/waditu/czsc/blob/master/CLAUDE.md Execute tests using 'uv run'. The '--no-sync' flag skips lockfile and venv consistency checks for faster local development. Use '--cov=czsc' for coverage reports and '--run-slow' to include tests marked with '@pytest.mark.slow'. ```bash uv run --no-sync pytest ``` ```bash uv run --no-sync pytest tests/test_analyze.py -v ``` ```bash uv run --no-sync pytest tests/test_analyze.py::test_czsc_basic -v ``` ```bash uv run --no-sync pytest --cov=czsc ``` ```bash uv run --no-sync pytest --run-slow ``` -------------------------------- ### Add czsc-derive Dependency Source: https://github.com/waditu/czsc/blob/master/crates/czsc-derive/README.md Include `czsc-derive` and its related dependencies in your Cargo.toml file to use the derive macros. ```toml [dependencies] czsc-derive = "1.0" anyhow = "1" thiserror = "2" serde = { version = "1", features = ["derive"] } ``` -------------------------------- ### Test CZSC Bench Command Throughput Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md This test verifies that the `bench` command correctly reports throughput metrics in JSON format. It checks for positive `bars_per_sec` values for CZSC construction. ```python import json import pytest from typer.testing import CliRunner from czsc.cli import app runner = CliRunner() @pytest.mark.slow def test_bench_json_reports_throughput(): r = runner.invoke(app, ["bench", "--years", "1", "--freq", "30分钟", "--json"]) assert r.exit_code == 0, r.output data = json.loads(r.stdout) assert data["czsc_construct"]["bars_per_sec"] > 0 ``` -------------------------------- ### Import Streamlit CLI Source: https://github.com/waditu/czsc/blob/master/tests/compat/baselines/streamlit_imports.txt Imports the Streamlit command-line interface module for programmatic control of Streamlit applications. This is typically used for advanced scripting. ```python from streamlit.web import cli as stcli ``` -------------------------------- ### Add CZSC Dependency to Cargo.toml Source: https://github.com/waditu/czsc/blob/master/crates/czsc/README.md To use the CZSC framework in your Rust project, add the `czsc` crate to your `Cargo.toml` file. ```toml [dependencies] czsc = "1.0" ``` -------------------------------- ### Data Connectors Source: https://github.com/waditu/czsc/blob/master/docs/public_api.md The `czsc.connectors` module provides interfaces to various data sources. Users can import specific connectors like `ts_connector` or access individual functions such as `get_raw_bars`. ```APIDOC ## Data Connectors (connectors) Defined in `czsc/connectors/`, exposed via the `czsc.connectors` sub-package. | Module | Purpose | File Location | |----------------|------------------------------------------|------------------------------| | `tq_connector` | Tianqin Quant data source connector | `czsc/connectors/tq_connector.py` | | `ts_connector` | Tushare data source connector | `czsc/connectors/ts_connector.py` | | `ccxt_connector`| Cryptocurrency (CCXT) data source connector | `czsc/connectors/ccxt_connector.py` | | `local_data` | Local cache reading entry for research data | `czsc/connectors/local_data.py` | **Usage**: ```python from czsc.connectors import ts_connector # or from czsc.connectors.ts_connector import get_raw_bars ``` ``` -------------------------------- ### BarGenerator Object Source: https://github.com/waditu/czsc/blob/master/docs/public_api.md A multi-frequency K-line synthesizer that generates higher frequency K-lines from a base frequency. ```APIDOC ## BarGenerator ### Description A multi-frequency K-line synthesizer. It takes a base frequency K-line data and generates corresponding K-lines for multiple higher frequencies. This is useful for analyzing trends across different time scales simultaneously. ### Methods - **add_bar(bar: RawBar)**: Adds a new raw K-line to the generator to update the synthesized K-lines for all frequencies. ### Parameters - **base_freq** (Freq): The base frequency of the input K-lines. - **target_freqs** (list[Freq]): A list of target frequencies to synthesize. ### Returns - **BarGenerator**: An instance of the BarGenerator. ``` -------------------------------- ### CZSC Utility Module Source: https://github.com/waditu/czsc/blob/master/CLAUDE.md The 'czsc/utils/' module contains various utility functions for data caching, IO, logging, and analysis. Some TA operators are provided by Rust 'czsc._native.ta', with select top-level aliases retained. ```python from czsc.utils.optimize import OpensOptimize, ExitsOptimize, CzscOpenOptimStrategy, CzscExitOptimStrategy ``` ```python from czsc.utils.plotting import kline, weight ``` ```python from czsc.utils.plotting.lightweight import * # lightweight-charts self-contained HTML ``` -------------------------------- ### CZSC CLI Plot Command Implementation Source: https://github.com/waditu/czsc/blob/master/docs/superpowers/plans/2026-06-02-czsc-cli.md Python implementation for the `plot czsc` CLI command, which visualizes single-period CZSC structures into an HTML file. It handles input parsing, CZSC object creation, and plotting. ```python import json import typer from czsc.cli import _io app = typer.Typer(no_args_is_help=True) @app.command("czsc") def czsc_cmd( input: str = typer.Argument(..., help="标准行情文件"), freq: str = typer.Option("30分钟", "--freq", help="频率"), output: str = typer.Option("czsc.html", "-o", "--output", help="HTML 输出路径"), theme: str = typer.Option("light", "--theme", help="light/dark"), tail_bars: int = typer.Option(None, "--tail-bars", help="只画最后 N 根"), json_out: bool = typer.Option(False, "--json", help="JSON 输出"), ) -> None: """单周期缠论结构 HTML(plot_czsc)。""" with _io.error_boundary(json_out): from czsc import CZSC, format_standard_kline from czsc.utils.plotting.lightweight import plot_czsc df = _io.load_bars_df(input) c = CZSC(format_standard_kline(df, _io.freq_to_cn(freq))) plot_czsc(c, output="html", path=output, theme=theme, tail_bars=tail_bars) _io.emit({"output": output}, json_out=json_out, human=lambda d: typer.echo(f"已写入 {d['output']}")) ``` -------------------------------- ### CZSC Object Source: https://github.com/waditu/czsc/blob/master/docs/public_api.md The main object for Chan Lun analysis, managing raw K-lines, phân hình (FX), and bi lists. It is implemented in Rust and exposed via PyO3. ```APIDOC ## CZSC ### Description This is the main object for Chan Lun analysis. It manages the raw K-line data, phân hình (FX), and bi lists. The core functionality is implemented in Rust and exposed to Python through PyO3. ### Usage ```python # Example usage (conceptual) from czsc import CZSC # Assuming you have raw bar data # raw_bars = [...] # czsc_instance = CZSC(raw_bars) ``` ### Parameters - **raw_bars** (list[RawBar]): A list of raw K-line data objects. ### Returns - **CZSC**: An instance of the CZSC object. ```