Manuscript Offprint
arXiv:2611.09528StockASkill: A Local-First AgentSkill for Intelligent Stock Selection
Abstract
Quantitative equity selection and portfolio construction in emerging and cross-border financial markets frequently encounter significant architectural friction: computational bottlenecks from row-oriented iterative scans, remote API rate exhaustion, lookahead and survivorship biases, and rigid real-world execution constraints (e.g., discrete board lots and investor-mandated drawdown limits). In this paper, we present StockASkill, a local-first, full-data-driven AgentSkill engineered as a specialized Quant Co-Processor for autonomous AI agents and quantitative researchers to perform intelligent stock selection and goal-constrained portfolio optimization. Tailored specifically for agile quantitative accounts, family offices, and autonomous AI trading agents with capital scale in the range RMB where discrete board lot rounding and cash buffer protection are mandatory real-world requirements, StockASkill establishes an embedded columnar Online Analytical Processing (OLAP) foundation atop DuckDB over 42.44 million historical price records and 186,432 quarterly accounting disclosures spanning 26 years across China A-shares, Hong Kong, US equities, and ETFs. By eliminating ad-hoc remote network dependencies during analysis, StockASkill reduces full-market multi-factor cross-sectional screening latency across 5,400+ equities from over 25 seconds to sub-0.5 seconds (a 95%+ performance gain). We formalize an end-to-end mathematical pipeline integrating a 7+1 factor alpha baseline model, a Sequential Least Squares Programming (SLSQP) convex optimizer operating under smooth surrogate drawdown bounds with exact path validation, dynamic 100-share board lot integer quantization, and an autonomous thesis lifecycle finite-state machine. Furthermore, we provide a zero-disk, strongly-typed JSON streaming interface designed specifically for high-throughput LLM agent tool-calling. The complete source code, documentation, and reproducible pipelines are open-sourced at https://github.com/axjing/stockaskill. Comprehensive empirical benchmarks validate the computational scalability, out-of-sample risk-adjusted return characteristics, and operational resilience of the proposed AgentSkill architecture.
Keywords: AgentSkills, AI Agents, Local-First Architecture, Intelligent Stock Selection, Factor Investing, DuckDB OLAP, Convex Optimization, SLSQP, Board Lot Discretization.
1 Introduction
The democratization of quantitative finance and algorithmic portfolio management has expanded rapidly over the past decade. Individual quants, family offices, and autonomous AI agents now require institutional-grade decision engines capable of evaluating massive cross-sections of financial instruments across multiple asset classes and historical market regimes [1,2]. Despite this progress, contemporary open-source quantitative tooling suffers from several severe structural limitations:
*Corresponding author: axjing.ai@gmail.com Affiliation: Independent Researcher Team. Date: November 2026.
-
Remote Query Fragility and Rate-Limit Exhaustion: Most quantitative toolkits rely on remote public REST/RPC APIs (e.g., EastMoney, Sina, Yahoo Finance) as their primary query layer. Repeatedly fetching long-term historical bars for cross-sectional screening inevitably triggers rate limits, socket disconnects (RemoteDisconnected), or IP throttling.
-
Row-Oriented and Iterative Compute Inefficiencies: Evaluating multi-factor models across 5,000+ stocks typically involves iterative Python loops or row-oriented SQLite transactions, incurring severe interpretive overhead and latency exceeding 30 seconds per scan.
-
The Disconnect Between Theoretical Alpha and Discrete Execution: Traditional Mean-Variance Optimizers (MVO) [3] output continuous theoretical weights (e.g., 3.471%) while ignoring rigid real-world execution constraints. In markets such as the Shanghai and Shenzhen Stock Exchanges, equities must be traded strictly in 100-share integer board lots (shou), and investor mandates demand strict bounds on Target CAGR and Maximum Drawdown.
-
Friction in AI Agent Integration: Contemporary large language model (LLM) agent harnesses lack zero-disk, strongly typed tool-calling protocols. Agents often spend significant token budgets parsing unstructured terminal ASCII tables or waiting on intermediate disk I/O.
To systematically resolve these challenges, we introduce StockASkill, a high-performance, local-first AgentSkill engineered for intelligent stock selection and goal-constrained portfolio optimization. Conforming to the open AgentSkills specification, StockASkill transforms raw financial market data into actionable mathematical alpha through a strictly local-first paradigm: a unified, 42.44-million-row DuckDB columnar analytical database serves as the single active source of truth. Remote APIs function purely as dynamic, watermark-driven incremental ingestion pipes rather than ad-hoc query layers.
-
Quant Co-Processor Architecture for AI Agents: We establish a hybrid cognitive-computational paradigm where the autonomous LLM agent formulates qualitative hypotheses and macro directives, while StockASkill serves as a zero-disk, deterministic quant co-processor executing sub-second mathematical optimizations tailored for RMB capital capacity.
-
Local-First Columnar Data Lake: We design a local-first storage foundation utilizing DuckDB [4] maintaining 42.44 million rows spanning 26 years (1998–2024+) across China A-shares, Hong Kong, US equities, and ETFs, with dynamic watermark synchronization and autonomous multi-source circuit breakers.
-
Sub-Second Intelligent Stock Selection Skill: We formalize an intelligent stock selection skill executing a 7+1 multi-factor alpha scoring model over vectorized SIMD analytical window functions, achieving sub-0.5s screening over 5,400+ equity instruments—a 95%+ latency reduction compared to conventional architectures.
-
Goal-Constrained SLSQP Optimization with Discrete Rounding: We formulate a non-linear convex optimization model that maximizes the portfolio Sharpe ratio under dual rigid user constraints (Target CAGR and Maximum Drawdown )
solved via smooth convex relaxation, combined with dynamic macro risk budgeting and exact 100-share board lot integer quantization.
-
Autonomous Thesis Lifecycle Tracking: We establish a finite-state machine (FSM) that tracks investment theses across their entire active lifecycle, incorporating trailing-stop risk patrols, catalyst tracking, and postmortem performance attribution.
-
Zero-Disk AgentSkill Streaming Protocol: We implement a standardized AgentSkill interface conforming to the AgentSkills specification, streaming validated, strongly typed JSON payloads directly to stdout for zero-disk-overhead consumption by autonomous LLM agents.
2 Related Work
2.1 Quantitative Investment Platforms and Backtesting Engines
Quantitative investment research relies heavily on backtesting frameworks to validate alpha hypotheses. Early open-source systems such as Zipline and Backtrader pioneered event-driven simulation, yet their row-by-row Python loop interpretations incur prohibitive execution latencies when scaling across thousands of securities over multi-decade horizons. Modern platforms, notably Microsoft Qlib [5], leverage vectorized NumPy/C++ kernels and proprietary binary array storage to accelerate offline machine learning model training. However, existing platforms are engineered primarily for human-in-the-loop Jupyter environments or distributed client-server clusters. They lack standardized, zero-disk tool-calling interfaces for autonomous language agents, require complex infrastructure setup, and neglect discrete board lot execution rounding during portfolio construction. StockASkill bridges this gap by embedding a lightweight, zero-dependency columnar OLAP engine directly into the application process.
2.2 Financial Large Language Models and Agentic Systems
The advent of large language models has sparked significant interest in financial AI, ranging from domain-adapted foundation models such as FinGPT [2] to autonomous agent frameworks using ReAct [6] and Toolformer paradigms. While LLMs excel at processing unstructured financial texts, corporate disclosures, and sentiment signals, empirical studies demonstrate that foundation models suffer from severe numerical hallucinations, arithmetic fragility, and high token overhead when performing multi-asset portfolio optimizations or large-scale matrix operations. Furthermore, standard CLI tools emit decorative ANSI terminal formatting that inflates token budgets and induces parsing failures. StockASkill formalizes a decoupled Quant Co-Processor architecture: the agent handles qualitative reasoning and strategic goal setting, while StockASkill guarantees deterministic, sub-second mathematical optimization streamed via strongly typed JSON.
2.3 Local-First Analytics and Embedded Columnar OLAP
Columnar database management systems have fundamentally reshaped analytical query processing [7]. Recent innovations in embeddable columnar stores, exemplified by DuckDB [4], demonstrate that vectorized execution algorithms utilizing modern SIMD hardware primitives (AVX-512, AVX2, NEON) can outpace distributed clusters on single-node analytical workloads. StockASkill leverages these architectural breakthroughs to establish a Local-First financial analytical lake: by maintaining 42.44 million historical price records and 186,432 quarterly accounting disclosures locally, all multi-factor screening and portfolio backtesting queries execute in-process without network latency, rate exhaustion, or remote API dependencies.

Figure 1: StockASkill Architecture as an Autonomous AgentSkill. An end-to-end, local-first intelligent stock selection and portfolio decision pipeline. Autonomous LLM agents issue quantitative commands conforming to the AgentSkills specification, which execute over an embedded DuckDB OLAP store (42.44M rows), evaluate a vectorized 7+1 multi-factor alpha model, solve a goal-constrained SLSQP optimization problem with exact 100-share board lot rounding, and stream structured JSON results back to the agent without disk I/O overhead.
3 System Architecture and Local-First Data Strategy
3.1 The Local-First Paradigm and Data Lake Schema
Traditional financial analysis platforms treat remote APIs as query engines, resulting in high query latency and severe availability risks. StockASkill enforces a Local-First architecture wherein all mathematical analysis, screening, optimization, and backtesting execute strictly against local embedded storage.
The physical storage foundation is implemented via DuckDB (quant_cache.duckdb), an embeddable, columnar OLAP database optimized for vectorized execution on modern SIMD hardware [4, 7]. The active database contains 42,442,180 daily price records, 186,432 quarterly financial indicator records, and complete trading calendars across 26 years. Table 1 outlines the primary physical relational schemas.
To eliminate unexecutable survivorship bias and micro-cap illiquidity distortions in real-world trading, the data ingestion and screening pipelines enforce strict statutory investability filters: (i) Special Treatment & Delisting Guard: Automatic exclusion of equities flagged with ST, *ST, or entering exchange delisting transition periods; (ii) Seasoning Window: Exclusion of newly listed equities with fewer than 60 exchange trading days to prevent anomalous secondary listing volatility; (iii) Liquidity Tail Truncation: Exclusion of the bottom 10% trailing 20-day average daily turnover quantile, filtering out illiquid micro-caps with severe market impact; (iv) Execution Limit-Price Sentry: Explicit tracking of statutory limit-up (+10%/ + 20%) and limit-down (-10%/ - 20%) price states, preventing unexecutable buying at ceiling prices or forced selling at frozen floor prices.
Table 1: Primary Physical Table Schemas in DuckDB Engine
| Table Name | Primary Key | Description & Compression |
|---|---|---|
| daily_price | (code, market, date) | Split-adjusted OHLCV, turnover, VWAP, quality flags (RLE/BITPACKING) |
| financial_indicator | (code, market, report_date) | Quarterly ROE, gross margin, FCF, debt-to-asset, revenue YoY |
| stock_pool | (code, market) | Universe metadata, listing date, ST/delisted flags, completeness score |
| sync_state | (scope_type, scope_key, data_kind) | Sync watermarks, last success timestamp, stream status |
| factor_daily_snapshot | (code, market, trade_date) | Precomputed cross-sectional factor values and percentile ranks |
| trade_calendar | (market, date) | Valid open exchange trading dates per market |
3.2 Dynamic Incremental Watermark Synchronization
To maintain dataset freshness without triggering full-universe downloads, StockASkill implements dynamic watermark gap detection. Let denote the latest cached trading date for symbol , and let denote the latest open exchange date retrieved from the local trading calendar.
The incremental backfill window is computed as:
\mathcal{W}(s)=\begin{cases}\emptyset,& \text{if } T_{local}(s) \geq T_{target}\\[T_{local}(s)-\delta_{pad},\ T_{target}],& \text{if } T_{local}(s) < T_{target}\\[T_{cold},\ T_{target}],& \text{if } T_{local}(s) = \emptyset\end{cases} \tag{1}where trading days represents an intentional safety overlap to capture retrospective corporate dividend adjustments, split corrections, and delayed fundamental restatements. Writes are executed via atomic UPSERT (ON CONFLICT (code, market, date) DO UPDATE) semantics, guaranteeing idempotency.
3.3 Multi-Source Resilience and Fallback Circuit Breakers
To ensure continuous operational availability without single-point failure, StockASkill incorporates a multi-source fallback topology with circuit breakers. Market data ingestion coordinates across multiple specialized public endpoints:
-
Historical OHLCV Streams: In the domestic China A-share market, high-volume K-line bars prioritize BaoStock [8] for low-latency continuity. When remote timeouts or transient exchange rate limits occur, the ingestion pipeline fails over sequentially to AKShare [9] / EastMoney [10] and efinance [11]. For cross-border Hong Kong and US equities, the pipeline leverages AKShare alongside yfinance [12].
-
Fundamental Statements and Financial Indicators: Quarterly accounting disclosures, balance sheets, cash flow metrics, and consensus forecasts are ingested via Tonghuashun (THS) and Sina Finance through AKShare [9], before undergoing schema normalization and columnar persistence.
-
Circuit Breakers and Adaptive Backoff: Source health is dynamically tracked in data_quality_backoff. Repetitive connection failures trigger exponential backoff, preventing redundant API spamming and quota exhaustion while falling back gracefully to validated local cache.
4 Vectorized Cross-Sectional Multi-Factor Alpha Engine
4.1 Mathematical Formulation of the 7+1 Factor Model
StockASkill formalizes a 7+1 factor scoring architecture adapted for emerging equity markets, building on empirical asset pricing literature [13–16]. Let represent the raw observation for asset , factor , at time . Each factor stream undergoes cross-sectional median absolute deviation (MAD) Winsorization:
followed by cross-sectional standardization into z-scores:
The individual factor models are specified as follows:
- Value Factor (): Composite relative value combining earnings-to-price, book-to-market, and dividend yield percentiles:
where denotes the standard normal cumulative distribution function mapping scores to .
- Quality Factor (): Adapting Asness et al. [15] and Piotroski [17], evaluating operating profitability, balance sheet stability, and cash earnings quality:
- Growth Factor (): Captures quarterly year-over-year revenue and operating profit expansion alongside momentum-based growth acceleration:
- Momentum Factor (): Following Jegadeesh and Titman [18], computing 6-month intermediate price momentum while skipping the most recent 1-month reversal period, augmented with moving average trend alignment:
- Short-Term Reversal Factor (): Following Jegadeesh [19], capturing 1-month short-term price reversal:
exploiting liquidity provision compensation and behavioral overreaction dampening in retail-heavy market segments.
- Low Volatility Factor (): Exploiting the low-volatility anomaly [16] via 250-day annualized daily return volatility:
-
Size Factor (): Small-capitalization premium formulation: .
-
Analyst Consensus Factor (): Forward revision momentum and earnings forecast dispersion (+1 exogenous forecast dimension).
The final composite score is computed via vector dot product against user-selected or regime-adaptive factor weights :
Collinearity Mitigation and Model Extensibility: In practical asset pricing, raw style factors exhibit cross-sectional correlations (e.g., low volatility and large market capitalization). To eliminate spurious beta exposure, StockASkill supports cross-sectional industry and size residualization prior to composite aggregation:
While this 7+1 factor suite provides a robust, transparent baseline, the engine architecture defines an open Feature Plug-in Interface. Autonomous agents can dynamically bind learned non-linear embeddings (e.g., gradient boosted decision trees or sequence representations) directly into the columnar execution morsel without modifying the core pipeline.
4.2 Columnar Vectorization in DuckDB
Rather than executing factor transformations in iterative Python memory space, StockASkill expresses cross-sectional calculations directly in DuckDB SQL using window functions (OVER (PARTITION BY market ORDER BY ...)). Because DuckDB processes queries in vectorized morsels utilizing AVX-512 and AVX2 vector instructions, cross-sectional ranking across 5,400+ instruments completes in under 450 milliseconds.
5 Goal-Constrained Portfolio Optimization and Execution Discretization
5.1 Convex Optimization Formulation with Dual Rigid Bounds
Classical Markowitz mean-variance optimization [3] minimizes portfolio variance for a given expected return. In real-world asset management, however, institutional mandates impose simultaneous rigid bounds on both minimum expected compounding rate and maximum tolerable peak-to-trough drawdown.
We formalize this as a non-linear constrained optimization problem solved via Sequential Least Squares Programming (SLSQP) [20, 21]. Let be the portfolio weight vector over screened assets, be expected annualized asset returns, and be the Ledoit-Wolf shrunken covariance matrix [22]:
(12) subject to the dual rigid constraints and budget bounds:
where is the risk-free rate, and MaxDrawdown(w) is computed via historical simulation of the synthetic portfolio path:
Smooth Surrogate Approximation and Exact Validation: In its raw mathematical form, the sample-path maximum drawdown MDD(w) is a piecewise-linear, non-differentiable minimax function. Its non-smooth gradient discontinuities can destabilize standard Sequential Quadratic Programming (SQP) gradient approximations. To ensure numerical robustness, StockASkill implements a two-stage hybrid formulation: (i) During iterative SLSQP descent, the optimizer evaluates a smooth convex surrogate constraint via tail Conditional Value-at-Risk (CVaR), which supplies well-conditioned analytical gradients for the BFGS quasi-Newton updates; (ii) Upon solver convergence, the system performs exact empirical path simulation of . If the exact realized trajectory slightly exceeds , a monotone line-search projection smoothly dampens equity weights along the cash-buffer ray until both constraints (13) and (14) are strictly satisfied.
5.2 Macro Regime Risk Budgeting
Before capital allocation, the engine interrogates current market breadth (the percentage of equities trading above their 20-day and 60-day moving averages) to determine the macro risk regime multiplier :
Total target equity exposure is constrained by , with held in risk-free cash buffers.
5.3 Integer Board Lot Discretization Algorithm
Continuous weights produced by convex optimizers cannot be directly executed in exchanges that mandate lot-size minimums (e.g., shares in China A-shares). A naive rounding scheme introduces portfolio drift and can violate cash budget constraints. We formalize an integer knapsack-style allocation algorithm that guarantees non-negative cash residual and minimal tracking error.
Algorithm 1 Integer Board Lot Allocation with Cash Buffer Guard
Require: Optimal continuous weights , total capital , regime multiplier , current prices , board lot size .
Ensure: Integer share execution vector , residual cash .
1:
2: ,
3: for to do
4:
5:
6:
7: end for
8:
9:
10: while do
11: Find
12: if no valid exists then break
13: end if
14:
15:
16: end while
17:
18: return
Algorithm 1 guarantees that , eliminates odd-lot execution failures, and minimizes tracking error relative to theoretical continuous optimization.
6 Thesis Lifecycle Management and Dynamic Risk Control
Quantitative portfolios frequently suffer from discretionary behavioral drift after positions are established. StockASkill incorporates a formal Thesis Memory Finite-State Machine (FSM):
When an asset is acquired, the system logs its entry catalyst, expected holding horizon, fundamental target, and initial trailing-stop threshold. During each market close, the risk-alert subsystem evaluates active positions:
If , the thesis transitions to the Alerted state, issuing mandatory exit tickets. Upon trade conclusion, a structured postmortem captures attribution (, , ) to continuously refine model priors.
7 AI Agent Integration and Streaming Protocol
StockASkill is designed from the ground up to comply with the AgentSkills.io open specification [23]. Standard quantitative command-line interfaces emit decorative ASCII tables and progress bars designed for terminal human viewing. When invoked by LLM agents (e.g., Claude Code, OpenCode, Codex), visual formatting causes three issues: (i) inflated prompt token consumption, (ii) parsing fragility via regular expressions, and (iii) I/O latency from temporary intermediate files.
StockASkill resolves this via zero-disk standard output streaming:
-
Decoupled Stream Pipeline: Passing --json suppresses all ANSI formatting, logger outputs, and interactive status bars from stdout, redirecting diagnostics strictly to stderr.
-
Schema-Compliant JSON on stdout: The process writes a single, strongly-typed JSON document directly to standard output, enabling LLMs to pipe and ingest results via zero-copy in-memory deserialization (json.loads(stdout)).
Listing 1 illustrates a representative zero-disk execution stream emitted on stdout for a portfolio optimization request. Because all diagnostics and sync telemetry route exclusively to stderr, the agent consumes the structured JSON payload directly without regex parsing or intermediate disk I/O overhead.
{
"status": "success",
"task": "portfolio_optimize",
"capacity": 500000.0,
"macro_regime": {"breadth": 0.72, "regime": "BULL", "equity_mult": 1.00},
"optimization": {
"target_cagr": 0.15, "realized_cagr": 0.1842,
"max_drawdown_limit": 0.12, "realized_mdd": 0.0891, "sharpe": 1.482
},
"allocations": [
{"code": "600519", "market": "A", "weight": 0.284, "shares": 200, "price": 1780.0},
{"code": "000858", "market": "A", "weight": 0.211, "shares": 800, "price": 142.5}
],
"cash_residual": 8450.0,
"board_lot": 100
}
Listing 1: Representative Zero-Disk Machine-Parsable Payload on stdout
8 Empirical Evaluation and Benchmarks
8.1 Computational Latency Benchmarks
We evaluate the computational performance of StockASkill against a conventional row-oriented SQLite implementation and a standard in-memory Pandas multithreaded scanning loop. Tests were conducted on an AMD Ryzen 9 7950X workstation (32 threads, 64 GB DDR5 RAM, PCIe 4.0 NVMe SSD) across the full China A-share universe of 5,421 equities over the 26-year historical dataset (42.44 million rows).
As demonstrated in Table 2, StockASkill completes cross-sectional factor ranking for 5,421 equities in 0.38 seconds, representing a 74.9× speedup over conventional SQLite loops. This efficiency stems from DuckDB's columnar SIMD execution and the elimination of Python object conversion overhead.
8.2 Backtested Portfolio Performance and Attribution
We backtest the goal-constrained portfolio optimization model over the seven-year period from January 2018 through October 2024, encompassing both prolonged market contractions and rapid cyclical expansions. The investment universe is constructed using official historical point-in-time
Table 2: End-to-End Latency Benchmark across Full Market Universe (5,421 Equities)
| Task Description | Engine Architecture | Latency | Speedup | Network I/O |
|---|---|---|---|---|
| Full-Market Screen | Row SQLite + Python Loop | 28.45 s | 1.0× | 0 MB |
| Full-Market Screen | In-Memory Pandas Threads | 14.12 s | 2.0× | 0 MB |
| Full-Market Screen | StockASkill (DuckDB SIMD) | 0.38 s | 74.9× | 0 MB |
| Single Stock Diagnosis | Ad-hoc Remote REST API | 4.82 s | 1.0× | 2.4 MB |
| Single Stock Diagnosis | StockASkill Local-First | 0.08 s | 60.2× | 0 MB |
| Goal-Constrained MVO | Scipy SLSQP + Board Lot | 0.41 s | — | 0 MB |
constituent lists for the CSI 300 and CSI 500 indices (reconstituted semi-annually per China Securities Index Co. schedules). Crucially, the dataset preserves the full historical records of securities that were subsequently delisted, suspended, or restructured, strictly eliminating survivorship bias [24].
To guarantee full reproducibility, Table 3 provides a comprehensive specification of all empirical hyperparameters, factor weights, and execution constraints.
Table 3: Key Empirical Backtest Parameters and Execution Specifications
| Parameter Category | Specification / Methodology | Value / Rule |
|---|---|---|
| Investment Universe | Dynamic Point-in-Time CSI 300 + CSI 500 | 800 Equities |
| Capital Capacity | Target Retail/Micro-Fund Capital Scale () | 500,000 RMB |
| Rebalancing Frequency | Monthly Execution Schedule | Every 21 Trading Days |
| Portfolio Size | Top- Screened Alpha Candidates | Equities |
| Composite Factor Weights | Equal-Weighted Baseline () | 1/8 per factor |
| Covariance Estimator | Ledoit-Wolf Shrinkage Matrix () | Trailing 126 Days |
| Risk-Free Rate | PBOC 1-Year Benchmark Deposit Rate () | 2.50% Annualized |
| Trailing Stop-Loss | Dynamic Peak-to-Trough Exit Threshold () | 8.0% |
| Round-Trip Friction | Stamp Tax (5 bps) + Commissions (2.5 bps) + Slippage (7.5 bps) | 15.0 bps |
| Investability Guard | Exclude ST/*ST, IPO < 60d, Turnover tail 10%, Limit-up/down | Strictly Enforced |
Prior to portfolio optimization, the 7+1 neutralized factor baseline delivers statistically robust cross-sectional predictive power across the test horizon, achieving an annualized average Rank Information Coefficient () of 4.21% (-statistic = 3.48, ) and an Information Ratio (ICIR) of 0.86.
Table 4: Empirical Backtest Metrics (2018–2024)
| Strategy Preset | Constraint Mandate | Ann. Return | MaxDD | Sharpe | Calmar |
|---|---|---|---|---|---|
| CSI 300 Benchmark | Passive Buy & Hold | 3.12% | -39.54% | 0.22 | 0.08 |
| Momentum Enhanced | CAGR ≥ 15%, MDD ≤ 12% | 18.42% | -11.85% | 1.48 | 1.55 |
| Low Volatility | CAGR ≥ 10%, MDD ≤ 6% | 12.65% | -5.82% | 1.62 | 2.17 |
| Quality Growth | CAGR ≥ 12%, MDD ≤ 8% | 15.11% | -7.94% | 1.54 | 1.90 |
Performance Attribution and Honest Benchmark Deconstruction: While Table 4 exhibits dramatic risk-adjusted outperformance over the benchmark index, a rigorous quantitative attribution reveals that the outperformance stems from two orthogonal drivers: (i) Macro Risk Budgeting (Beta Timing): The dynamic equity multiplier () accounts for approximately 58% of the total drawdown compression by de-risking into cash buffers during broad market breadth contractions (e.g., 2018 deleveraging and 2022–2023 broad declines); (ii) Cross-Sectional Stock Selection Alpha: The 7+1 factor scoring and goal-constrained SLSQP convex optimization account for the remaining 42% of drawdown mitigation and generate the primary excess return spread, achieving Sharpe ratios exceeding 1.48. Disentangling macro beta exposure from pure cross-sectional selection alpha confirms that the engine honors real-world risk budgets without disguised leverage.
9 Conclusion and Future Work
In this paper, we introduced StockASkill, an offline-first, full-data-driven quantitative decision engine engineered as a specialized Quant Co-Processor for autonomous AI agents. By utilizing an embedded 42.44M-row DuckDB columnar OLAP store, StockASkill eliminates remote API fragility and reduces cross-sectional screening latency across 5,400+ equities to sub-0.5 seconds. We formalized a goal-constrained SLSQP optimizer operating under smooth surrogate drawdown bounds with exact path projection, incorporating real-world 100-share board lot constraints and macro regime budgeting, alongside a finite-state thesis tracking architecture and a zero-disk streaming protocol for autonomous LLM agents.
Future extensions include: (i) All-Weather Multi-Asset Risk Parity: Expanding beyond equities to balance risk contributions across government bonds, commodities, and inflation-protected ETFs; (ii) End-to-End Non-Linear Learned Representations: Integrating gradient-boosted decision trees and sequence neural embeddings directly into the DuckDB analytical morsel via the open feature plug-in interface; and (iii) Multi-Agent Consensus Protocols: Extending the AgentSkills specification to multi-agent adversarial setups (e.g., Fundamental Analyst Agent versus Risk Sentry Agent) with formal execution guarantees.
Author Contributions
Xiangjing An: Conceptualization, methodology, system architecture, core DuckDB columnar engine design, quantitative modeling, algorithmic implementation, empirical backtesting, project administration, and writing – original draft.
Zhibin Jiao and Aiting Chen: Conceptualization (discussion), data curation, empirical validation, visualization design, and writing – review & editing.
Declaration on Generative AI in Scientific Writing
During the preparation of this manuscript, the authors utilized generative artificial intelligence and large language model assistants (e.g., Claude, Antigravity) strictly to improve linguistic clarity, refine grammatical phrasing, and assist with IATEX structural formatting and typographic consistency. After utilizing these assistive services, the authors critically reviewed, verified, and edited all generated content.
Data and Code Availability
The complete source code of StockASkill1, including the local-first DuckDB columnar analytical pipelines, the 7+1 factor scoring modules, the goal-constrained SLSQP portfolio optimizer with 100-share board lot quantization, the thesis lifecycle state machine, and the AgentSkills-compliant zero-disk streaming harness, is publicly open-sourced under an open-source license at https://github.com/axjing/stockaskill. All market price records, fundamental accounting indicators, and trading calendar databases are fully reproducible via the automated ingestion and watermark synchronization scripts provided in the repository.
Disclaimer and Risk Disclosure
This paper and the accompanying open-source software (StockASkill) are developed strictly for academic research, algorithmic reproducibility, and educational demonstration purposes. Nothing contained in this manuscript or the codebase constitutes financial, investment, legal, or tax advice, nor should it be construed as an offer, solicitation, endorsement, or recommendation to acquire or liquidate any security, portfolio, or financial instrument.
Quantitative trading and equity market investments inherently involve substantial financial risks, including the potential loss of principal. Simulated backtesting results and historical statistical performance metrics (e.g., CAGR, MaxDD, Sharpe ratio, Calmar ratio) are hypothetical, calculated under empirical assumptions, and do not guarantee or represent future realized returns. Autonomous AI agent tool execution and quantitative optimization systems are subject to model misspecification, unanticipated market regime shifts, exchange trading halts, and technological execution slippages. Neither the authors, the independent researcher team, nor any affiliated contributors assume any legal liability or financial responsibility for direct, indirect, or consequential losses arising from the practical deployment or reliance upon the algorithms, data pipelines, or code presented herein. Users and autonomous agents operate this software entirely at their own discretion and risk.
References
[1] Eugene F Fama and Kenneth R French. A five-factor asset pricing model. Journal of Financial Economics, 116(1):1–22, 2015.
[2] Hongyang Yang, Xiao-Yang Liu, and Christina Dan Wang. Fingpt: Open-source financial large language models. FinLLM Symposium at IJCAI, 2023.
[3] Harry Markowitz. Portfolio selection. The Journal of Finance, 7(1):77–91, 1952.
[4] Mark Raasveldt and Hannes Mühleisen. Duckdb: an embeddable analytical database. In Proceedings of the 2019 International Conference on Management of Data (SIGMOD), pages 1981–1984, 2019.
[5] Xiao Yang, Weiqing Liu, Dong Zhou, Jiang Bian, and Tie-Yan Liu. Qlib: An ai-oriented quantitative investment platform. arXiv preprint arXiv:2009.11189, 2020.
[6] Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao. ReAct: Synergizing reasoning and acting in language models. International Conference on Learning Representations (ICLR), 2023.
[7] Daniel Abadi, Peter Boncz, and Stavros Harizopoulos. Column-oriented database systems. Communications of the ACM, 52(9):166–174, 2009.
[8] BaoStock Development Group. BaoStock: Securities big data platform for historical market data. http://baostock.com, 2021.
[9] Tian Huang. AKShare: An open-source financial data interface library for python. https://akshare.akfamily.xyz, 2020.
[10] EastMoney Information Co., Ltd. Eastmoney financial market information and securities database. https://www.eastmoney.com, 2024.
[11] Yifan Lu. efinance: A python library for public financial market data extraction. https://github.com/Micro-sheep/efinance, 2022.
[12] Ran Arakane. yfinance: Open-source financial data downloader for global equities. https://github.com/ranaroussi/yfinance, 2020.
[13] Eugene F Fama and Kenneth R French. Common risk factors in the returns on stocks and bonds. Journal of Financial Economics, 33(1):3–56, 1993.
[14] Mark M Carhart. On persistence in mutual fund performance. The Journal of Finance, 52(1):57–82, 1997.
[15] Clifford S Asness, Andrea Frazzini, and Lasse Heje Pedersen. Quality minus junk. Review of Accounting Studies, 24(1):34–112, 2019.
[16] Andrew Ang, Robert J Hodrick, Yuhang Xing, and Xiaoyan Zhang. The cross-section of volatility and expected returns. The Journal of Finance, 61(1):259–299, 2006.
[17] Joseph D Piotroski. Value investing: The use of historical financial statement information to separate winners from losers. Journal of Accounting Research, 38:1–41, 2000.
[18] Narasimhan Jegadeesh and Sheridan Titman. Returns to buying winners and selling losers: Implications for stock market efficiency. The Journal of Finance, 48(1):65–91, 1993.
[19] Narasimhan Jegadeesh. Evidence of predictable behavior of security returns. The Journal of Finance, 45(3):881–898, 1990.
[20] Dieter Kraft. A software package for sequential quadratic programming. DFVLR-FB, 88:28, 1988.
[21] Jorge Nocedal and Stephen J Wright. Numerical Optimization. Springer Science & Business Media, 2006.
[22] Olivier Ledoit and Michael Wolf. Honey, i shrunk the sample covariance matrix. The Journal of Portfolio Management, 30(4):110–119, 2004.
[23] AgentSkills Working Group. Agentskills: Open modular tool-calling specification for ai agents. https://agentskills.io, 2024.
[24] Stephen J Brown, William Goetzmann, Roger G Ibbotson, and Stephen A Ross. Survivorship bias in performance studies. The Review of Financial Studies, 5(4):553–580, 1992.