API 参考¶
本页只列出面向策略作者和本地研究的稳定公共接口。策略推荐从顶层 tualpha 导入;下方模块路径用于生成准确的 API 签名。
回测入口¶
tualpha.core.algorithm.run_algorithm
¶
run_algorithm(
*,
start,
end,
initialize=None,
handle_data=None,
analyze=None,
capital_base=1000000.0,
bundle_root=DEFAULT_BUNDLE_ROOT,
adjustment=AdjustmentMode.QFQ,
execution_time=ExecutionTime.OPEN,
output_dir=None,
benchmark=None,
strategy_name="TuAlpha 回测策略",
generate_report=True,
show_progress=True,
plotly_js=PlotlyJsMode.INLINE,
bundle_name="tualpha",
column_cache_mib=None,
fee_model=None,
)
Run a point-in-time daily stock/ETF backtest.
Set show_progress=False to disable the default tqdm session progress bar.
tualpha.core.algorithm.TradingAlgorithm
¶
TradingAlgorithm(
config,
*,
initialize=None,
handle_data=None,
analyze=None,
fee_model=None,
)
Coordinate local data, simulated execution, callbacks, and metrics.
资产¶
tualpha.model.asset.Asset
dataclass
¶
Asset(
sid,
ts_code,
symbol,
name,
asset_type,
exchange,
board,
list_date=None,
delist_date=None,
price_tick=0.01,
settlement_days=1,
)
A tradable A-share stock or exchange-traded fund.
tualpha.model.asset.AssetFinder
¶
AssetFinder(bundle_root, bundle_name=BUNDLE_NAME)
Resolve stable tradable assets from the Bundle asset manifest.
retrieve_asset
¶
retrieve_asset(code, as_of_date=None)
Resolve a sid, Tushare code, or unambiguous six-digit symbol.
tualpha.apis.strategy.symbol
¶
symbol(code)
Resolve a stock or ETF by Tushare code or unique six-digit symbol.
行情数据¶
BarData 只在 handle_data 回调内有效。
tualpha.data.bar.BarData
¶
BarData(portal)
A callback-scoped, point-in-time data facade similar to Zipline BarData.
prefetch
¶
prefetch(assets, fields)
Warm repeated cross-sectional columns without exposing physical storage.
current_arrays
¶
current_arrays(assets, fields)
Return read-only NumPy arrays for a batch current-data query.
fundamental_arrays
¶
fundamental_arrays(assets, fields, *, report_type='1')
Return read-only arrays of latest callback-visible financial values.
index_current
¶
index_current(index_code, fields)
Return raw index daily values for the current callback session.
index_history
¶
index_history(index_code, fields, bar_count)
Return raw index daily history ending at the current callback session.
index_constituents
¶
index_constituents(index_code)
Return the latest index constituents visible before this session.
指数日线¶
BarData.index_current() 和 BarData.index_history() 按指数代码读取当前或历史原始点位。指数不可下单,读取结果不参与股票/ETF 复权。
close = data.index_current("000300.SH", "close")
history = data.index_history("000300.SH", ["close", "volume"], 20)
订单接口¶
tualpha.apis.strategy.order
¶
order(asset, amount)
Submit a signed quantity for execution at the next session endpoint.
tualpha.apis.strategy.order_value
¶
order_value(asset, value)
Trade within a signed CNY limit at the next execution endpoint.
tualpha.apis.strategy.order_percent
¶
order_percent(asset, percent)
Trade a signed fraction of D+1 pre-match portfolio equity.
tualpha.apis.strategy.order_target
¶
order_target(asset, target)
Move a position toward a target quantity.
tualpha.apis.strategy.order_target_value
¶
order_target_value(asset, target)
Move toward a CNY target using the D+1 execution price.
tualpha.apis.strategy.order_target_percent
¶
order_target_percent(asset, target)
Move toward a D+1 pre-match equity weight.
批量订单¶
tualpha.apis.strategy.order_many
¶
order_many(requests)
Submit mapping-ordered fixed-quantity orders.
tualpha.apis.strategy.order_value_many
¶
order_value_many(requests)
Submit mapping-ordered CNY-limited orders.
tualpha.apis.strategy.order_percent_many
¶
order_percent_many(requests)
Submit mapping-ordered percent-of-equity orders.
tualpha.apis.strategy.order_target_many
¶
order_target_many(targets, *, position_limit=None)
Submit cash-adaptive batch quantity targets.
tualpha.apis.strategy.order_target_value_many
¶
order_target_value_many(targets, *, position_limit=None)
Submit mapping-ordered target-value orders.
tualpha.apis.strategy.order_target_percent_many
¶
order_target_percent_many(targets, *, position_limit=None)
Submit mapping-ordered target-weight orders.
订单管理¶
组合记录与费用¶
tualpha.apis.strategy.record
¶
record(**values)
Attach custom scalar values to the current daily performance row.
tualpha.apis.strategy.set_commission
¶
set_commission(model)
Replace the fee model, normally during initialize.
tualpha.broker.costs.ChinaFeeModel
dataclass
¶
ChinaFeeModel(
stock_commission_rate=0.0003,
etf_commission_rate=0.0003,
stock_min_commission=5.0,
etf_min_commission=5.0,
stamp_tax=(lambda: _DEFAULT_STAMP_TAX)(),
stock_transfer=(lambda: _DEFAULT_TRANSFER)(),
)
Broker-realistic default with explicit, non-duplicated fee components.
Commission is treated as an all-in brokerage charge that already contains exchange handling fees; handling fees are never charged separately.
tualpha.broker.costs.RateSchedule
dataclass
¶
RateSchedule(entries)
Piecewise-constant rates keyed by inclusive effective dates.
本地数据查询¶
tualpha.data.query.local_data
¶
local_data(
bundle_root=DEFAULT_BUNDLE_ROOT, bundle_name=BUNDLE_NAME
)
tualpha.data.query.LocalDataClient
¶
LocalDataClient(
bundle_root=DEFAULT_BUNDLE_ROOT, bundle_name=BUNDLE_NAME
)
One read-locked DuckDB session exposing registered Parquet tables.
因子研究¶
tualpha.data.research.factor_data
¶
factor_data(**kwargs)
Create a context-manageable :class:FactorData research session.
tualpha.data.research.FactorData
¶
FactorData(
*,
start,
end,
assets=None,
index_code=None,
asset_type=None,
bundle_root=DEFAULT_BUNDLE_ROOT,
bundle_name=BUNDLE_NAME,
adjustment=AdjustmentMode.RAW,
exclude_st=False,
min_listed_days=0,
exclude_suspended=False,
column_cache_mib=None,
)
Fast date-by-asset factor history for offline research.
The configured universe can be fixed or based on strictly point-in-time index snapshots. Optional ST, listing-age, and suspension filters are applied on each signal date, never backfilled from current classifications.
available_fields
¶
available_fields(namespace=None)
Return physical fields available in the underlying Bundle.
history
¶
history(expressions, *, allow_future=False)
Calculate factor expressions over the configured range and universe.
A single expression returns a date-by-code DataFrame. Multiple
expressions return the standard (asset, field) column layout.
allow_future exists for analysis labels such as
FUTURE_RETURNS and should never be used to construct a signal.
history_arrays
¶
history_arrays(expressions, *, allow_future=False)
Return expression-keyed matrices without assembling MultiIndex columns.
This is the memory-bounded interface for performance benchmarks and
streaming factor pipelines. :meth:history uses it internally before
assembling the conventional public DataFrame layout.
tualpha.analysis.factor.run_factor_analysis
¶
run_factor_analysis(
factors,
*,
start,
end,
assets=None,
index_code=None,
periods=(1, 5, 10),
quantiles=5,
minimum_observations=5,
industry_neutral=False,
market_cap_neutral=False,
industry_field="industry.l1_name",
market_cap_field="daily_basic.total_mv",
bundle_root=DEFAULT_BUNDLE_ROOT,
bundle_name="tualpha",
adjustment=AdjustmentMode.RAW,
exclude_st=True,
min_listed_days=365,
exclude_suspended=True,
column_cache_mib=None,
output_dir=None,
title="TuAlpha 因子分析",
plotly_js=PlotlyJsMode.INLINE,
)
Load PIT factor data and produce a complete Alphalens-style analysis.
tualpha.analysis.factor.analyze_factor_data
¶
analyze_factor_data(
factors,
forward_returns,
*,
industries=None,
market_caps=None,
industry_neutral=False,
market_cap_neutral=False,
factor_expressions=None,
quantiles=5,
minimum_observations=5,
title="TuAlpha 因子分析",
plotly_js=PlotlyJsMode.INLINE,
metadata=None,
output_dir=None,
)
Calculate Alphalens-style diagnostics for factor matrices.
tualpha.analysis.factor.neutralize_factor_values
¶
neutralize_factor_values(
factor, *, industries=None, market_caps=None
)
Residualize daily factor values against industry and/or log market cap.
Supplying both exposures is equivalent to a joint regression with industry
fixed effects and log(total_mv). Missing exposures are excluded rather
than filled, so they cannot enter later rankings or correlations.
tualpha.analysis.factor.FactorAnalysisResult
dataclass
¶
FactorAnalysisResult(
factors,
periods,
start,
end,
daily_metrics,
summary_metrics,
quantile_returns,
factor_expressions=dict(),
return_analysis=pd.DataFrame(),
sector_ic=pd.DataFrame(),
sector_quantile_returns=pd.DataFrame(),
title="TuAlpha 因子分析",
plotly_js=PlotlyJsMode.INLINE,
metadata=dict(),
report_path=None,
metrics_path=None,
)
Structured factor diagnostics and atomic report export helpers.
回测结果¶
tualpha.result.BacktestResult
dataclass
¶
BacktestResult(
config,
performance,
daily_positions,
orders,
transactions,
closed_trades,
metrics,
records=pd.DataFrame(),
report_path=None,
positions_path=None,
)