An experimental portfolio-research platform combining release-safe macroeconomic data, a 503-security U.S. equity universe, graph features, reinforcement learning, convex portfolio constraints, and SVG-based portfolio geometry. It also models multi-asset sleeves, cash vehicles, investor/account tax context, option overlays, leverage, and risk-adjusted sleeve comparisons.
The next milestone is to connect the existing semantic contracts to one account-aware CVXPY optimizer with point-in-time market, option-chain, tax-lot, liquidity, and margin data.
This project is for research and education. It is not investment advice, and the current pipeline is not production-ready.
Implemented:
- Canonical prices and returns for 503 securities with quality reports and release-safe macro joins
- A 19-instrument hierarchy spanning equity, Treasuries, credit, real assets, and currency
- Constrained efficient-frontier, then-versus-now, graph-RL, and CVXPY experiments
- A reproducible $100,000 model portfolio with an explicit high-yield-savings reserve
- Versioned legal, tax, account, cash, option, leverage, and protection semantics
- Covered-call, protective-put, collar, and 1.25x leverage payoff scenarios
- Volatility, downside-deviation, drawdown, and CVaR sleeve-efficiency metrics
- Deterministic CSV/SVG artifacts and 32 invariant tests across seven test modules
- A cross-platform Python command-line orchestrator and legacy exploratory R analysis
Known limitations:
- Several scrapers depend on page structure, Selenium, and bundled macOS Chrome drivers.
- Source licensing is not fully audited, and several legacy macro sources lack true vintage histories.
- The equity universe is a current-constituent snapshot, so historical experiments retain survivorship bias.
- Option strikes, premiums, financing rates, cash yields, and tax rates are illustrative rather than executable quotes or individualized rules.
- Tax lots, cross-account wash sales, option assignment, broker house margin, and live settlement state are not yet modeled.
- The active scientific Python environment is not currently reproducible from one modern lock file.
- Some scripts execute work at import time and use broad exception handling.
The data directories represent successive stages:
| Directory | Purpose |
|---|---|
data/raw/ |
HTML and CSV responses close to their source form |
data/processed/ |
Cleaned individual economic and index series |
data/stock_data/ |
Per-ticker market-history CSV files |
data/formatted/ |
Date-aligned, model-ready tables |
data/canonical/ |
Long-form return series and release-safe macro features |
data/metadata/ |
Universe, policy, cash, derivative, and data contracts |
data/quality/ |
Coverage and invariant reports |
plots/ |
Generated charts |
.
|-- analysis/R/ # Exploratory R analysis
|-- data/ # Raw, canonical, metadata, quality, and legacy datasets
|-- drivers/ # Legacy bundled Chrome drivers
|-- plots/ # Generated figures
|-- scripts/
| |-- data_quality/ # Canonical dataset builders and validators
| |-- experiments/ # Portfolio, graph, cash, tax, and derivative studies
| |-- semantics/ # Typed legal, tax, cash, risk, and derivative contracts
| |-- scrap_data/ # Data acquisition
| |-- refine_data/ # Source-specific cleaning
| |-- format_data/ # Alignment and dataset merging
| |-- stock_data/ # Per-ticker download and formatting
| `-- plot/ # Legacy plot generation
|-- tests/ # Schema, constraint, semantic, and artifact tests
|-- main.py # Pipeline command-line entry point
|-- tickers.txt # Stock universe
`-- requirements.txt # Legacy dependency pins plus CVXPY
The dependency pins are legacy-era and should be installed in an isolated Python 3.9 environment until the environment-refresh roadmap item is complete.
conda create -n stockgraph python=3.9
conda activate stockgraph
python -m pip install -r requirements.txtOptional components:
- Install R and place
RscriptonPATHto run the R analysis. - Install a Chrome/ChromeDriver combination compatible with your operating system before using the Selenium scrapers. The bundled drivers are macOS-only.
Run commands from the repository root. --mode and --stocks are mutually exclusive, and a failed child script now produces a nonzero exit code.
# Refresh the S&P 500 ticker list
python main.py --mode scrape
# Clean the existing raw macroeconomic data
python main.py --mode refine
# Align and merge processed datasets
python main.py --mode format
# Run the existing plotting script
python main.py --mode plot
# Reproduce the constrained portfolio experiment and SVG plots
python main.py --mode experiment
# Run the graph-aware RL policy with CVXPY projection
python main.py --mode hybrid
# Rebuild and validate canonical P0 data artifacts
python main.py --mode quality
python -m unittest tests.test_p0_data -v
# Run the 19-instrument hierarchical multi-asset experiment
python scripts/data_quality/build_multi_asset.py --refresh
python main.py --mode multi-asset
python -m unittest tests.test_multi_asset -v
# Compare one hypothetical return across explicit account-policy scenarios
python main.py --mode legal-tax
python -m unittest tests.test_legal_tax_semantics -v
# Compare cash-like vehicles by yield, liquidity, tax, and protection semantics
python main.py --mode cash-semantics
python -m unittest tests.test_cash_semantics -v
# Build the reproducible $100,000 model portfolio
python main.py --mode portfolio-100k
python -m unittest tests.test_portfolio_100k -v
# Compare option overlays, 1.25x leverage, and sleeve risk-adjusted metrics
python main.py --mode derivatives
python -m unittest tests.test_derivative_variations -v
# Run all 32 repository tests
python -m unittest discover -s tests -v
# Refresh the eight experiment tickers through today, then rerun all experiments
python scripts/experiments/portfolio_geometry.py --refresh
python main.py --mode experiment
# Run exploratory R analysis
python main.py --mode r
# Download/update per-ticker histories
python main.py --stocks download
# Normalize per-ticker CSV files
python main.py --stocks formatAcquisition commands use external services and can be slow or break when upstream schemas change. Review each data source's terms before redistributing downloaded data.
P0 establishes a reproducible boundary between legacy source tables and model-ready data:
| Artifact | Contract |
|---|---|
data/canonical/stock_returns.csv.gz |
Long-form prices and returns for all 503 securities |
data/canonical/macro_releases.csv |
One row per macro value and availability date |
data/canonical/macro_features_release_safe.csv |
Market-date features joined only to information available on or before that date |
data/metadata/data_dictionary.csv |
Units, frequency, source, availability rule, and revision policy |
data/metadata/universe_manifest.json |
Universe definition, symbol normalization, coverage, and survivorship-bias exposure |
data/quality/stock_quality_report.csv |
Coverage, missing dates, duplicates, invalid values, and stale-price runs by ticker |
Simple returns are the selected optimization return. Log returns are retained as a diagnostic and for models where additivity is useful.
The macro release layer uses recorded release or event dates wherever the source retained them. The original World Bank GDP extraction did not preserve vintage publication timestamps, so annual GDP uses July 1 of the following year as an explicit conservative availability proxy. It must not be described as the actual historical publication date.
The stock universe is a current-constituent snapshot, not a point-in-time S&P 500 universe. All 503 securities therefore use current or future membership information for analyses beginning before the snapshot, and no historical additions or removals are represented. The direction of survivorship bias is known, but its performance magnitude is not identifiable until historical constituent records are added.
The first constrained portfolio experiment uses adjusted daily returns for eight stocks: AAPL, MSFT, NVDA, JPM, XOM, JNJ, PG, and NEE. Parameters are estimated on 2020-2023 data, while 2024 is held out for evaluation. The feasible portfolios are fully invested, long-only, and capped at 35% per stock. The covariance estimate uses 10% diagonal shrinkage.
The optimizer solves the convex objective maximize mu^T w - gamma w^T Sigma w with projected gradient descent over the capped simplex. A fixed random seed makes the feasible portfolio cloud reproducible.
| Portfolio | Annual return | Annual volatility | Interpretation |
|---|---|---|---|
| Equal weight | 27.16% | 11.66% | Simple benchmark |
| Minimum variance | 5.36% | 11.08% | Lowest realized volatility |
| Maximum training return/risk | 50.14% | 21.15% | Higher realized return with substantially higher risk |
These figures describe one small historical sample. They do not establish future performance. The selection of the maximum return/risk portfolio uses training data only; all reported 2024 metrics are out of sample.
Market histories were refreshed through August 28, 2026, the latest completed trading day available on August 29. The comparison holds the asset universe, four-year window length, covariance method, and portfolio constraints constant:
- Then: January 2020 through December 2023
- Now: August 28, 2022 through August 28, 2026
The largest estimated-return increases were NVDA, from 67.65% to 77.31%, and JPM, from 13.62% to 32.90%. AAPL and MSFT fell from approximately 30% and 28% to approximately 21% each. Estimated volatility declined for every asset in this basket.
The minimum-variance solution was previously concentrated at the 35% cap in both JNJ and PG. The current solution is more distributed: JNJ 29.74%, PG 26.81%, XOM 13.35%, MSFT 12.32%, JPM 10.00%, with smaller allocations to the remaining stocks.
| Calibration | Portfolio | Estimated return | Estimated volatility | Return/risk |
|---|---|---|---|---|
| Then | Equal weight | 22.88% | 22.96% | 1.00 |
| Then | Minimum variance | 11.74% | 18.59% | 0.63 |
| Then | Maximum return/risk | 38.57% | 30.74% | 1.25 |
| Now | Equal weight | 23.76% | 14.36% | 1.65 |
| Now | Minimum variance | 16.72% | 11.79% | 1.42 |
| Now | Maximum return/risk | 35.97% | 17.13% | 2.10 |
The maximum estimated return/risk solution changed more sharply:
| Asset | Then weight | Now weight |
|---|---|---|
| AAPL | 23.60% | 0.00% |
| MSFT | 6.78% | 0.00% |
| NVDA | 35.00% | 24.51% |
| JPM | 0.00% | 30.13% |
| XOM | 23.99% | 10.36% |
| JNJ | 0.05% | 35.00% |
| PG | 10.58% | 0.00% |
| NEE | 0.00% | 0.00% |
This is a comparison of historical parameter estimates, not a claim that the current allocation will outperform. Mean-return estimates are especially unstable; the next experiment should compare shrinkage or factor-based expected returns with walk-forward evaluation.
The hybrid experiment gives each component a distinct role:
- A rolling 60-day correlation graph supplies node centrality and spectral stock positions.
- A lightweight REINFORCE-style policy uses 21-day momentum, 60-day momentum, volatility, and graph centrality to propose weights.
- CVXPY projects each proposal onto a fully invested, long-only portfolio with a 35% asset cap and 60% turnover limit.
- The projection objective also penalizes covariance risk, turnover, and distance from the RL proposal.
- Monthly walk-forward evaluation begins in 2025 and applies the dated Mirae Asset buy/sell charge schedule.
| Strategy | Annual return | Annual volatility | Return/risk | Maximum drawdown |
|---|---|---|---|---|
| Graph RL + CVXPY | 21.45% | 13.54% | 1.58 | -6.75% |
| Equal weight | 25.72% | 10.15% | 2.53 | -6.46% |
| Minimum variance | 19.32% | 10.85% | 1.78 | -5.56% |
The initial RL policy does not beat equal weight. This is a useful baseline: the feasibility layer works, but the learned proposal needs stronger state signals, multiple training windows, and a reward that accounts for covariance risk and turnover during training rather than only during execution.
The multi-asset layer is separate from the 503-security stock universe. Its registry contains 19 liquid proxies across five allocation groups:
| Group | Instruments | Constraint |
|---|---|---|
| Equity | SPY, QQQ, IWM, EFA, EEM | 20-65% |
| Treasury | SGOV, SHY, IEF, TLT, TIP | 10-60% |
| Credit | LQD, HYG, EMB | 0-30% |
| Real assets | GLD, SLV, DBC, USO, VNQ | 0-30% |
| Currency | UUP | 0-10% |
The policy observes all 19 nodes, proposes sleeve weights, and passes them through CVXPY. Instrument caps, group bounds, full investment, long-only weights, covariance risk, turnover costs, and a 60% rebalance limit are enforced at every decision.
| Strategy | Annual return | Annual volatility | Return/risk | Maximum drawdown |
|---|---|---|---|---|
| Hierarchical RL + CVXPY | 12.14% | 7.98% | 1.52 | -3.94% |
| Equal sleeve | 17.78% | 6.38% | 2.79 | -2.67% |
| Minimum variance | 6.86% | 2.97% | 2.31 | -1.90% |
| 60/40 SPY-IEF | 12.38% | 8.12% | 1.53 | -3.89% |
The hierarchical policy modestly exceeds the 60/40 benchmark in this initial window, but it does not beat equal-sleeve allocation. This remains a research baseline, not evidence of future performance.
Portfolio return is contextual. The same instrument and market path can produce different investor outcomes because taxation, withholding, account rules, eligibility, and realized tax lots depend on the investor-account-policy combination.
Investor facts Account facts Instrument facts
tax residency registration domicile
immigration status tax treatment income source
treaty claim trading permissions income character
\ | /
+-------------------+-------------------+
|
dated policy selection
|
after-tax return model
|
legal constraints + CVXPY
Immigration status and tax residency are stored separately. The pipeline must never infer a tax classification or rate directly from a visa label. Every policy record has an effective date, jurisdiction, source, and assumption status. The checked-in scenarios are illustrative research inputs, not individualized legal or tax advice.
Current-period taxable return is decomposed into price return, qualified and ordinary dividends, interest, realized short-term gains, realized long-term gains, and fees. Unrealized appreciation is not taxed by the demonstration. Tax-deferred and tax-exempt scenarios defer withdrawal and qualification rules to a future cash-flow model.
| Artifact | Purpose |
|---|---|
data/metadata/investor_scenario_example.csv |
Keeps immigration status, tax residency, jurisdiction, treaty claim, and valuation date distinct |
data/metadata/legal_tax_policy_scenarios.csv |
Stores dated account permissions and explicit rate assumptions |
scripts/semantics/legal_tax.py |
Validates policy contracts and calculates current-period after-tax returns |
plots/legal_tax_semantics/ |
Contains the reproducible account comparison and assumptions used |
Authoritative starting references are the IRS guidance on visa status versus tax residency, investment income and wash sales, taxation of nonresident investors, and Traditional and Roth IRAs. Rules must be reviewed for the relevant jurisdiction and effective date before a scenario is used.
Cash is not encoded as a universal zero-return node. The initial registry distinguishes idle brokerage cash, a bank deposit sweep, a high-yield savings account, a government money-market fund, and a Treasury bill. Each vehicle carries its own currency, income character, settlement delay, principal-stability assumption, stress haircut, and protection regime. Here, "high yield" means a high-yield savings deposit, not a below-investment-grade bond allocation.
cash requirement
|
+-- immediate liquidity ------> idle cash / bank sweep
+-- transfer liquidity -------> high-yield savings
+-- daily liquidity ----------> money-market fund
+-- maturity-matched reserve -> Treasury bill
|
+-- yield and fees
+-- tax character
+-- settlement delay
+-- institution-level aggregation
`-- protection or credit regime
The protection field is descriptive rather than a common risk score. FDIC deposit insurance generally aggregates eligible deposits by depositor, insured bank, and ownership category, so the model includes an aggregation key and checks other balances before calculating scenario coverage. FDIC Bank sweeps and money-market funds are distinct: eligible bank deposits may receive FDIC insurance, while money-market fund shares are securities and are not FDIC-insured. SEC Investor.gov Treasury-bill earnings are federally taxable but exempt from state and local tax; that jurisdiction split remains a planned extension to the tax-rate engine. TreasuryDirect
The checked-in yields and stress haircuts are illustrative assumptions rather than live quotes. They exist to exercise the semantic contract and must be replaced by dated, sourced observations for research results.
The first capitalized portfolio reserves $10,000 in the illustrative high-yield savings vehicle and scales the latest hierarchical model weights across the remaining $90,000. Allocations are rounded to $10 with a largest-remainder method, so the exported positions total exactly $100,000.
| Sleeve | Allocation | Portfolio weight |
|---|---|---|
| High-yield savings reserve | $10,000 | 10.00% |
| Equity | $22,100 | 22.10% |
| Treasury | $22,860 | 22.86% |
| Credit | $13,670 | 13.67% |
| Real assets | $27,010 | 27.01% |
| Currency | $4,360 | 4.36% |
| Total | $100,000 | 100.00% |
The complete 20-position allocation is in plots/portfolio_100k/portfolio_100k.csv. It uses the August 28, 2026 model snapshot and dollar targets rather than share quantities. Prices, bid-ask spreads, taxes, trading fees, whole-share requirements, the investor's emergency-cash need, and institution-level deposit balances are not incorporated. The underlying hierarchical policy did not outperform equal-sleeve allocation in its initial test, so this artifact is a reproducible research output rather than a recommendation to deploy $100,000.
Options and borrowing are modeled as overlays on capital rather than new independent asset classes. The initial experiment compares an unhedged $10,000 normalized SPY sleeve with a covered call, protective put, and collar, plus a separately financed 1.25x portfolio. Strike and premium inputs are illustrative; they are not executable contracts or current option-chain quotes.
| Variation | Economic purpose | Risk deliberately retained |
|---|---|---|
| Covered call | Collect premium and reduce small losses | Most downside remains; upside is capped; early assignment is possible |
| Protective put | Establish a downside floor | Premium drag and expiration timing |
| Collar | Bound downside at lower cost | Upside is capped and short-call assignment remains possible |
| 1.25x leverage | Increase exposure without changing sleeve proportions | Financing drag, amplified losses, margin calls, and forced liquidation |
The model requires an account-permission label and collateral rule for every overlay. Short calls in the examples are covered; no naked-option strategy is enabled. FINRA notes that options and spreads commonly require margin-account approval and that firms may impose requirements beyond regulatory minimums. FINRA Regulatory Notice 21-15 OCC education describes a collar as a protective put combined with a covered call, producing a downside floor and upside ceiling. Options Industry Council The SEC warns that leverage can make relatively small market movements produce substantial gains or losses and that complex leveraged products may not behave as investors expect. SEC
The active identity scenario is a Korean national in U.S. F-1 immigration status using Mirae Asset Securities Korea. Immigration status is not treated as tax residency: the profile deliberately records tax residency as undetermined until the applicable U.S. substantial-presence, exempt-individual, Korean residency, and treaty analysis is supplied.
The dated standard broker schedule uses Mirae Asset's published online U.S. equity rates effective April 2, 2026:
| Charge | Buy | Sell |
|---|---|---|
| Online commission | 0.25000% | 0.25000% |
| Published U.S. sell-side charge | - | 0.00206% |
| Modeled total | 0.25000% | 0.25206% |
Selling $100,000 therefore has a modeled charge of $252.06; buying and later selling $100,000 has a modeled round-trip charge of $502.06. This excludes bid-ask spread, market impact, FX conversion, tax, account-specific promotions, and negotiated rates. Mirae Asset's current U.S. trading page publishes the 0.25% online commission and 0.00206% sell-side charge. Mirae Asset Securities Korea The underlying U.S. Section 31 rate is $20.60 per $1 million for covered sales beginning April 4, 2026; the broker's customer schedule states an April 2 effective date, so the repository follows the broker-published date for this account scenario. SEC fee-rate advisory
The RL reward now subtracts the directional broker charge:
reward = realized portfolio return
- buy_rate * sum(increases in weight)
- sell_rate * sum(decreases in weight)
- downside penalty
CVXPY uses the same asymmetric buy/sell expression in its projection objective with a configurable charge-aversion multiplier of 4, and walk-forward results record the unmultiplied realized broker charge separately from turnover. The multiplier preserves a conservative reluctance to trade; it is a model hyperparameter, not a fee. This replaces the earlier generic 10-basis-point turnover assumption. The schedule is versioned in data/metadata/broker_charge_scenarios.csv; promotions must be added as separate dated schedules rather than overwriting the standard rate.
"Risk/revenue" is interpreted as several return-to-risk ratios calculated on the common August 29, 2022 through August 28, 2026 sample:
- Return/volatility measures reward per unit of total variability, following the broad reward-to-variability idea behind the Sharpe ratio.
- Return/downside deviation avoids counting favorable variation as risk, but it is still incomplete for asymmetric strategies. CFA Institute
- Return/maximum drawdown measures historical path damage.
- Return/CVaR compares return with the average loss in the worst 5% of daily observations and is included because option strategies can have asymmetric tails. Rockafellar and Uryasev publications
The results are exported to sleeve_risk_adjusted_metrics.csv. SGOV ranks unusually high because its observed volatility and downside deviation were extremely small; this denominator effect is why no single ratio directly determines sleeve weight. Cboe's BXM benchmark provides a useful external covered-call comparison, but its published results are pre-tax and strategy-specific rather than proof that covered calls dominate an unhedged sleeve. Cboe BXM factsheet
The base $100,000 artifact remains unlevered and contains no live option orders. Promoting a variation into an executable portfolio requires current option chains, contract multipliers, implied volatility, spreads, tax-lot effects, broker permissions, margin rules, and assignment-aware simulation.
Any predictive or optimization experiment should follow these rules:
- Use adjusted returns, not raw price levels, for risk and covariance estimation.
- Align features to their actual public release time; do not backfill revised values into earlier dates.
- Split training and evaluation data chronologically.
- Fit scalers, imputers, covariance estimators, and models only on the training window.
- Compare against simple baselines such as equal weight, minimum variance, and a market index.
- Report turnover, transaction costs, constraint violations, and out-of-sample performance.
- Add a data dictionary with units, frequency, source URL, availability rule, and revision policy for every canonical feature.
- Convert all 503 stock histories to canonical
date,ticker,adjusted_close, andvolumefields. - Compute simple and log returns; select simple returns for optimization.
- Report missing dates, duplicates, stale prices, invalid values, coverage gaps, and normalized ticker changes.
- Build macro features with backward as-of joins on recorded or conservatively proxied availability dates.
- Classify the universe as a current snapshot and quantify its point-in-time coverage deficit and survivorship-bias exposure.
- Add schema and invariant tests for P0 source, canonical, release-safe, metadata, and quality stages.
- Add
cvxpyand select a supported convex solver. - Define explicit eight-stock and 19-instrument universes with chronological estimation windows.
- Estimate expected returns with historical sample means as the documented baseline.
- Add diagonal covariance shrinkage to the initial frontier experiment and wrap covariance inputs as positive semidefinite for CVXPY.
- Prototype a minimum-variance objective: minimize
w^T Sigma w. - Prototype a risk-adjusted objective: maximize
mu^T w - gamma w^T Sigma w. - Add the budget constraint
sum(w) = 1. - Add configurable long-only and per-asset upper bounds.
- Add asset-class bounds and turnover constraints to the hierarchical CVXPY projection.
- Validate CVXPY solver status and test weight, group, and turnover invariants.
- Compare optimized allocations with equal-weight, minimum-variance, and 60/40 benchmarks out of sample.
- Add liquidity, target-return, cash-floor, gross-exposure, and account-level constraints.
- Add explicit infeasibility diagnostics and recovery policies for conflicting configurations.
- Sweep the risk-aversion parameter to generate an initial efficient frontier.
- Plot feasible portfolios in expected-return/risk space and highlight optimal boundary points.
- Show how each active constraint cuts the feasible region for two- and three-asset examples.
- Project high-dimensional portfolio weights into two dimensions with PCA for exploratory geometry.
- Build an initial stock similarity graph from training-period correlations.
- Visualize node size as portfolio weight and edge weight as dependence.
- Relate active constraints and dual values to geometric supporting hyperplanes.
- Export CSV weights, diagnostics, performance summaries, and SVG figures for implemented experiments.
- Add a run manifest that hashes every optimization input and configuration.
- Move source paths, date ranges, solver settings, and constraints into a versioned configuration file.
- Convert scripts that execute at import time into small testable functions with
main()guards. - Replace broad exception handlers with specific errors and structured logging.
- Replace bundled browser binaries with automatic, platform-aware driver discovery.
- Consolidate repeated Selenium scraping logic into one reusable module.
- Add unit tests for canonical data, multi-asset constraints, tax, cash, derivatives, and the $100,000 portfolio.
- Add a small fixture dataset, linting, formatting, and continuous integration.
- Pin a single supported Python environment and remove redundant dependency definitions.
- Add monthly walk-forward tests with turnover costs, drawdown, return/volatility, and benchmark comparisons.
- Add multiple-window stability analysis and confidence intervals.
- Separate immigration status, tax residency, account type, jurisdiction, and treaty identifiers.
- Add versioned policy scenarios with source and assumption-status fields.
- Decompose gross return into income characters and demonstrate account-dependent after-tax return.
- Validate policy dates and reject missing or invalid rates.
- Distinguish cash-like vehicles by yield, fees, settlement, income character, and protection regime.
- Add aggregation-aware scenario coverage for capped deposit protection.
- Add point-in-time tax lots, holding periods, basis adjustments, and realized-gain selection.
- Model wash-sale relationships across taxable, spouse-controlled, and retirement accounts.
- Add country-specific withholding and treaty rules through reviewed policy plug-ins.
- Represent account eligibility, leverage, shorting, concentration, and product restrictions as named constraints.
- Optimize asset location jointly across multiple accounts without allowing wealth to move between accounts implicitly.
- Add contribution, withdrawal, required-distribution, and penalty cash flows.
- Record policy provenance, reviewer, effective interval, superseding rule, and reproducible scenario hash.
- Expose tax drag, active legal constraints, slack, and dual values in portfolio geometry plots.
- Add cash floors, liquidity buckets, settlement calendars, and stressed redemption constraints to CVXPY.
- Separate federal, state, local, and treaty tax rates for Treasury and municipal cash substitutes.
- Source point-in-time cash yields and sweep rates rather than treating the risk-free rate as universal.
- Add normalized covered-call, protective-put, collar, and leverage payoff scenarios.
- Compare sleeves with volatility, downside, drawdown, and CVaR return-efficiency ratios.
- Add a dated Mirae Asset Korea U.S. equity charge schedule and directional RL/CVXPY cost function.
- Ingest point-in-time option chains with bid/ask, Greeks, implied volatility, open interest, and corporate-action adjustments.
- Add assignment, exercise, expiration, contract-multiplier, and tax-lot state transitions.
- Enforce account approval, collateral, house margin, gross exposure, and maintenance-margin constraints before execution.
- Backtest option overlays without using closing option quotes unavailable at the decision timestamp.
For asset weights w, expected returns mu, covariance matrix Sigma, and risk-aversion parameter gamma > 0:
maximize mu^T w - gamma * w^T Sigma w
subject to 1^T w = 1
lower_i <= w_i <= upper_i
sector_lower <= A_sector w <= sector_upper
||w - w_previous||_1 <= turnover_limit
This is a convex quadratic program when Sigma is positive semidefinite and all constraints are convex. The weights form a point inside a convex feasible polytope; changing gamma traces optimal boundary points that become the efficient frontier in risk-return space. Dual values can identify which constraint surfaces determine each solution.
Keep acquisition, transformation, modeling, and visualization separate. New transformations should be deterministic, accept explicit inputs, write explicit outputs, and include a small test that protects dates, schemas, and row counts.