torchtrade icon indicating copy to clipboard operation
torchtrade copied to clipboard

PortfolioTradingEnv: broker-agnostic multi-asset portfolio env (target weights incl. cash)

Open BY571 opened this issue 2 months ago • 1 comments

Motivation

All TorchTrade envs trade a single asset, where the agent barely affects its own state. In portfolio management the agent's holdings are part of the state: every rebalance changes what it holds, what it pays in costs, and what it is exposed to next. This issue proposes an offline multi-asset env where the agent allocates across many assets (e.g. crypto, equities, commodities), usable by RL agents and classic portfolio-selection algorithms through the same interface, as a scalar and a vectorized env.

The design follows the problem formulation of Jiang, Xu & Liang (2017), A Deep Reinforcement Learning Framework for the Financial Portfolio Management Problem (DPM), and extends it where noted. Equation and section numbers below refer to that paper. Wherever TorchTrade already has a convention (SequentialTradingEnv, VectorizedSequentialTradingEnv, TorchTradeOfflineEnv, default_rewards.py), the env follows it; places without an existing convention are marked new convention.

Broker-agnostic, dataset-driven

PortfolioTradingEnv is an offline env and knows nothing about any broker. Everything asset- or venue-specific comes from the data and the config:

  • Like the existing offline envs, the env takes DataFrames, not a dataset name. The number of assets N is read from them at construction, and the observation and action specs are built from it. More assets means larger specs; no code change and no broker-specific subclass.
  • Fee and cost parameters are config values. Funding is applied only if a funding table is passed (e.g. perpetuals); spot data skips it. Shorting is a config switch. Trading hours come from the data, not from the env (see Tradable flag).
  • Train/test separation follows the existing convention: the caller slices the DataFrames before constructing the env. There are no date-range config fields.

Data contract (long format, one row per asset and bar):

Table Required columns Optional
bars timestamp (UTC, bar open), inst_id, open, high, low, close, volume, quote_volume tradable (bool), mark_close
instruments inst_id asset_class, contract specs
funding — (table optional) timestamp, inst_id, funding_rate

The env builds one common timeline from all timestamps. A missing row for an asset at a timestamp means the asset was not tradable then (market closed, not listed yet, or delisted). A present row is tradable unless its tradable column says otherwise; without the column, every present row is tradable. Duplicate rows and NaN prices raise at construction. mark_close is not used by the default env (see valuation below).

Official dataset: Torch-Trade/okx-multi-asset-1h (current version v2026.09), the first dataset that satisfies this contract, loaded into the three DataFrames by a small helper outside the env. It contains 40 OKX USDT perpetual swaps (15 crypto, 21 equities/ETFs, 4 commodities) on a common hourly grid (4,464 bars each, 2026-03-12 to 2026-09-13 UTC), plus mark prices, funding settlements and contract specs. Every instrument has every hourly bar, and nothing is filled or adjusted; the dataset card documents coverage, columns, caveats and versioning (new data is published as new vYYYY.MM tags, so results can pin a version).

Role for now: developing, testing and verifying the env, e.g. unit and integration tests, examples, and checking that baselines run end to end. With six months of history it is too small for serious training or for drawing performance conclusions; a larger dataset will follow.

Selection bias in the official dataset. Its 40 instruments were chosen by liquidity (median 90-day volume) measured at the end of the window. DPM §3.1 warns against exactly this: volume correlates with past performance, so selecting by volume from the test period leaks future information and favours survivors. Re-applying the same rule with only the first 30 days keeps 20 of the 40 instruments (details in the dataset card). Backtests over the full v2026.09 window therefore carry a selection bias; choose the universe from data before the test window when results are meant to be taken seriously.

Action: target weights, cash first

action = [w_cash, w_1, ..., w_N]      w_cash + Σ|w_i| = 1,   w_cash ≥ 0
  • Cash is element 0, the convention of DPM (§2.2) and most portfolio-selection literature, so baselines and papers map directly onto the env. It is an explicit asset: "go to cash" is a deliberate action.
  • w_i > 0 long, w_i < 0 short, as a fraction of portfolio value.
  • Invalid actions are normalised, not rejected: rescale so w_cash + Σ|w_i| = 1, then scale asset weights down to max_gross and move the remainder to cash. Long-only mode (allow_short=False, the default) clips negative weights to 0, which makes the action a point on the simplex, as in DPM (softmax output).
  • Assets that are not tradable at the decision bar keep their current weight, whatever the action says (see Tradable flag).

Tradable flag: trading hours, listing, delisting (new convention)

Not every asset can be traded at every bar: stock markets close at night, on weekends and on holidays, assets get listed later than others, and assets get delisted. The env handles all of these with one binary flag per asset, part of the observation so the agent knows what it can trade:

Situation tradable_i What the env does with asset i
Normal 1 trades to the target weight
Market closed (night, weekend, holiday, halt) 0 holds the position unchanged; it cannot be bought or sold
Not listed yet 0 position is 0 and stays 0
Delisted 0 from then on position is closed to cash at the last tradable close (paying commission like any trade), then stays 0
Cash always tradable not part of the flag vector

Action handling with closed assets. At a decision bar, the target of every non-tradable asset is replaced by its current drifted weight w'_i. The remaining budget, 1 - Σ_{closed} |w'_i|, is distributed over cash and the tradable assets in the proportions the agent requested. Crypto keeps trading while equities are closed; nothing is frozen that does not have to be. An agent that wants less equity exposure over a weekend has to reduce it before Friday's close.

Valuation while closed. If the data contains bars during the closure (as on OKX, where equity perps trade 24/7), those prices are used. If it does not (e.g. stock-broker data without weekend bars), the last close is carried forward: the position's value does not move while the market is shut, and the gap is applied when trading resumes, which is the real gap risk of holding over a closure. Funding is still charged on held positions if the funding table contains settlements during the closure.

Features while closed. Observation windows use the carried-forward prices for missing bars; the flag tells the agent the price is stale rather than calm. Before listing, features for the asset are 0.

On the official dataset every asset is tradable at every bar: equity perps on OKX trade around the clock (99.6% of weekend equity bars have volume, and no hour-of-week slot of any equity perp has zero volume in more than half the weeks; weekend volume is about a fifth of weekday volume). The flag is still part of the first version, because adding an observation key later would change the observation spec and break agents trained on the old one. Tests therefore need a small synthetic dataset with closures, e.g. the official bars with equity rows removed on weekends.

Decision frequency: execute_on, as in the existing envs

One step() is one execute_on bar and one agent decision, exactly as in SequentialTradingEnv: the sampler resamples the data to the execute_on grid and steps over it. There is no separate rebalance counter. execute_on is a config parameter with default "4Hour".

  • The holding period is the execute_on bar: e.g. hourly data with execute_on="4Hour" means a decision every 4 hours, and the agent cannot act in between.
  • Observations come from time_frames × window_sizes and can be finer than the decision grid, e.g. time_frames=["1Hour"], window_sizes=[50] for DPM's 50-bar price window with 4-hourly decisions.
  • Warm-up is automatic: the sampler never starts before every observation window is full, so no warm-up config is needed.

Observation: minimal Markov state

An element is in the observation only if it cannot be derived from the rest and the optimal decision depends on it. This matches DPM's state s_t = (X_t, w_{t-1}) (eq. 20), extended by the tradable flag:

observation_spec = Composite(
    portfolio_weights=Bounded(low=-max_gross, high=max_gross, shape=(N + 1,)),  # cash first, current weights after drift
    tradable=Binary(shape=(N,)),                                                # 1 = asset can be traded at this bar
    market_data_1Hour_50=Unbounded(shape=(N, W, F)),  # one key per (time_frame, window_size), existing key naming
)
  • portfolio_weights: where the agent is now. Costs depend on the distance to the new target, so without this the agent cannot see how its action changes the next state. DPM feeds the previous action w_{t-1} via its Portfolio-Vector Memory; the env provides the drifted weights w'_t = (y_t ⊙ w_{t-1}) / (y_t · w_{t-1}) (eq. 7) instead. The information is the same (y_t is part of the market data), but w'_t is the quantity transaction costs are computed from.
  • tradable: which assets the action can change at this bar. Not derivable from prices (a flat price can be a calm market or a closed one), and it determines which part of the action takes effect.
  • market_data_{tf}_{window}: the existing key naming, with an asset axis added: [N, W, F] for N assets, W bars of history, F features per bar, built from bars up to and including the decision bar.
    • feature_set="price_window": DPM's input (eq. 18), close, high and low over the window, each divided by the latest close; W=50, F=3 in the paper.
    • feature_set="summary": one row per asset (W=1) of engineered features, e.g. returns over 1h/24h/7d, 7d volatility, 30d drawdown, current funding rate (if available), volume change.

Deliberately excluded:

Element Why not
gross/net exposure, exposure per asset class, concentration, leverage headroom derivable from portfolio_weights and static asset classes / config
previous targets, position returns since entry path history; past gains or losses do not change the optimal action from here
cumulative fees, funding paid, last turnover sunk costs; forward-looking cost information is the funding rate and the known cost model
portfolio value irrelevant under proportional costs and zero market impact (DPM §4.1 excludes it for this reason); added only when market impact is enabled
steps remaining lets an agent game the episode end; live trading has no horizon
time until a market opens or closes not derivable in general, but also not needed for a first version; can be added as a feature later without changing the flag
drawdown only if a configured reward or termination rule depends on it

Execution timing and valuation

Same order as SequentialTradingEnv and the SL/TP envs (#281, #292, #294, #297), so all TorchTrade envs share one timing:

  1. At decision bar N the agent observes features built from bars up to and including N.
  2. The rebalance fills at close of bar N (execution_price="close"; next_open optional), for tradable assets only.
  3. The env advances to bar N+1 and applies it to the resulting positions: liquidation check (only relevant with shorts or leverage), funding, then valuation.

Valuation uses close, like every offline env (_get_portfolio_value): positions, portfolio value and reward are all computed at the close of the execute_on bar (carried forward for closed assets without bars). mark_close is not used by default because it is optional in the data contract (spot data has none), and because filling at close but valuing at the mark would move portfolio value by the close/mark gap right after every trade (up to 114 bps on the official dataset's equity perps). Live envs use the venue's mark price because the venue reports it; offline stays on close.

This timing is not lookahead (the agent trades at the last price it has seen), but it assumes execution at that price. On the official dataset |open(N+1) / close(N) - 1| has a median of 0 to 1 bps per asset class, with tails in thin markets (up to 194 bps for a newly listed equity perp on a weekend). Those tails belong to the cost model, not to a different fill price. The env docs must state this timing explicitly.

Transaction costs: exact remainder factor, impact optional

Fee rate. transaction_fee defaults to 0.0, like SequentialTradingEnv, so nobody silently gets an invented rate. Examples and baseline comparisons set a realistic rate explicitly. For the official dataset that is OKX's perpetual swap taker rate for the regular tier, because fills at close behave like market orders. That rate still has to be verified: a summary of OKX's fee page gives 0.08% maker / 0.10% taker for regular users, but does not say whether this is the spot or the perpetual swap schedule. The rate matters: an agent that trades 50% of its portfolio value every 4 hours over the 186-day window loses about 11% to fees at 0.02%, 24% at 0.05%, and 75% at DPM's 0.25%.

Default: proportional commission, computed exactly (new convention: existing offline envs charge a flat notional * transaction_fee). Rebalancing from the drifted weights w'_t to the target w_t shrinks portfolio value by the transaction remainder factor μ_t ∈ (0, 1] (eq. 14), with c = transaction_fee for buys and sells and cash at index 0:

μ_t = 1 / (1 - c·w_{t,0}) · [ 1 - c·w'_{t,0} - (2c - c²) · Σ_{i≥1} (w'_{t,i} - μ_t·w_{t,i})⁺ ]

μ_t appears on both sides, so it is solved by fixed-point iteration starting from μ⁰ = c · Σ|w'_{t,i} - w_{t,i}| (eq. 16); DPM Theorem 1 proves convergence from any start in [0, 1]. The flat fee · |trade| is only the starting guess. Non-tradable assets have w_{t,i} = w'_{t,i} and therefore contribute no cost. DPM derives μ_t for long-only weights on the simplex; the long-short case (allow_short=True) is not covered by the paper and needs its own derivation, checked by tests against a direct simulation of the individual buy and sell trades.

The default makes DPM's two explicit assumptions (§2.4), which the env docs must state:

  1. Zero slippage: every trade fills at the execution price.
  2. Zero market impact: the agent's trades do not move prices.

Optional: market impact (impact_coef > 0), addressing the weakness DPM itself names (§7): an additional cost per asset impact_coef · σ_i · sqrt(|trade_i| / ADV_i) · |trade_i| (square-root impact), with ADV_i a rolling average of quote volume (not the current bar, which can be zero) and σ_i rolling volatility. Impact makes absolute size matter, so when enabled portfolio value is added to the observation spec.

Costs are deterministic. The symmetric random slippage of SequentialTradingEnv (uniform(1 - s, 1 + s)) averages to zero, so it adds noise but does not penalise turnover; the portfolio env does not use it.

Funding (new convention)

No TorchTrade env models funding today, offline or live (see envs/live/README.md). The portfolio env defines it:

  • Which settlements a step pays: every settlement timestamp in (T_N, T_{N+1}], where T_N is this step's fill time and T_{N+1} the next step's. Each settlement belongs to exactly one step, so funding is never charged twice or skipped.
  • Which position pays: the position held after this step's trade: funding_cost = Σ_i w_i · V · rate_i. Longs pay when the rate is positive, shorts receive it (and the reverse for negative rates). Positions in closed markets still pay if the funding table has settlements during the closure.
  • A settlement exactly at a fill time belongs to the previous step and is charged on the position before the trade. Closing a position exactly at settlement does not dodge that payment, and opening one at settlement does not pay it, matching exchanges, which charge whoever holds the position at the snapshot.
  • Where it sits in the step: after the fill and the liquidation check, before valuation and the history record, the same slot liquidation uses in SequentialTradingEnv._step.
  • Prices used: weights and portfolio value at the end of the step. This is exact when settlements fall on execute_on bar boundaries (e.g. 4-hourly decisions and settlements at 00:00, 08:00, 16:00 UTC) and a small approximation otherwise, which the docs must state.
  • Settlement intervals differ per instrument and change over time, so the funding table's timestamps are used as given; no fixed interval is assumed.

Reward: existing log_return_reward

The env uses the existing reward functions from envs/core/default_rewards.py unchanged:

  • Default log_return_reward(history): ln(portfolio_values[-1] / portfolio_values[-2]), -10 on bankruptcy. Portfolio value is net of commission and funding, so the reward of a step covers everything that happened in it: the rebalance cost, all price moves of the execute_on bar, and funding. Summed over an episode this is ln(final value / initial value), what DPM maximises (eq. 21).
  • sharpe_ratio_reward and drawdown_penalty_reward only read portfolio values, so they work unchanged.
  • Same ordering as SequentialTradingEnv: record the step in the history, compute the reward from it, write the reward back.
  • The vectorized env uses the existing batched signature fn(old_pvs, new_pvs) (batched_log_return_reward).

Episodes: existing TorchTradeOfflineEnv._reset()

Behaviour (existing convention)
Start random_start=True (default): uniformly random start index with room for a full max_traj_length; otherwise the first valid bar
Warm-up automatic, from the sampler
Initial state flat: 100% cash, w = [1, 0, ..., 0], as in DPM; initial_cash a number or a [min, max] range
Truncated data exhausted, or step_counter >= max_traj_length
Terminated portfolio value < bankrupt_threshold * initial (default 0.1)
Seeding np.random.SeedSequence(seed).spawn(...), one independent stream per random component

Vectorized variant

A VectorizedPortfolioTradingEnv is part of the scope, following VectorizedSequentialTradingEnv:

  • a separate EnvBase that holds num_envs environments as tensors (weights (num_envs, N + 1), tradable flags, step indices, portfolio values) and steps all of them in one _step() call with pure tensor operations, no Python loop over environments
  • money, prices and positions in float64, cast to float32 only for observations and rewards (#293)
  • per-environment random start indices and resets
  • the batched reward signature fn(old_pvs, new_pvs)

One cost implementation for everything. The scalar env, the vectorized env and DPM training all call the same pure, batched, differentiable cost function (weight drift, tradable handling, μ_t, funding, portfolio value). The single-asset envs have separate scalar and vectorized money code today, and several bugs came from the two disagreeing (#274, #302). With one shared function that class of bug cannot occur, and a single equivalence test (scalar env vs vectorized env on the same actions) guards it.

Config

@dataclass
class PortfolioTradingEnvConfig:
    # existing offline-env fields, same names and semantics
    time_frames: list[str] = ("1Hour",)
    window_sizes: list[int] = (50,)
    execute_on: str = "4Hour"
    initial_cash: int | float | tuple = 10_000
    transaction_fee: float = 0.0           # c in the remainder factor; set explicitly in examples
    bankrupt_threshold: float = 0.1
    max_traj_length: int | None = None
    random_start: bool = True
    seed: int | None = 42
    reward_function: Callable = log_return_reward
    # new for the portfolio env
    feature_set: str = "price_window"      # or "summary"
    execution_price: str = "close"         # or "next_open"
    max_gross: float = 1.0
    allow_short: bool = False              # long-only comparison track by default
    impact_coef: float = 0.0               # > 0 enables market impact
    cash_rate: float = 0.0                 # annual yield on cash

@dataclass
class VectorizedPortfolioTradingEnvConfig(PortfolioTradingEnvConfig):
    num_envs: int = 64

The env is constructed with the bars, instruments and (optional) funding DataFrames plus this config. reward_spec = Unbounded(shape=(1,)); action_spec = Bounded(low=0 if long-only else -max_gross, high=max_gross, shape=(N + 1,)).

Extension points in the existing code

  • Multi-asset sampler: MarketDataObservationSampler reads one DataFrame; the portfolio env needs a version that samples N assets on a common timeline, returns [N, W, F] windows plus the tradable flags, carries prices forward for missing bars, and keeps the existing start-index, warm-up and truncation logic.
  • HistoryTracker: stores a single scalar position; needs per-asset weights, per-asset trades, and costs split into commission, impact and funding.
  • Pure cost function: shared by the scalar env, the vectorized env and DPM training (see Vectorized variant).
  • Dataset loader: a helper that loads a HuggingFace dataset version into the three DataFrames of the data contract.

Baselines and comparison track

All baselines below are long-only, so comparisons between them and RL agents use the long-only track (allow_short=False).

Baseline Description Role
DPM (EIIE-CNN + PVM) the paper's agent: identical per-asset evaluators with shared weights, previous weights inserted before the scoring layer, softmax with cash bias RL reference; the shared per-asset network works for any N, matching the dataset-driven design
UBAH uniform buy and hold: equal weights once, never rebalance market exposure without trading costs
UCRP uniform constant rebalanced portfolio: back to equal weights every period same exposure as UBAH but pays to rebalance; the gap is the cost of rebalancing
OLMAR online moving-average reversion (Li et al. 2015) a classic non-learning strategy that actually trades
Best Stock the single asset with the highest final value in hindsight reference line only; uses future information, not a strategy

DPM runs on cross-asset data, not restricted to crypto. Nothing in EIIE is crypto-specific, the authors name single-market testing as a weakness of their own work (§7), and uncorrelated assets give allocation decisions real consequences instead of choosing between assets that move together.

DPM with the tradable flag. DPM's softmax assumes every asset can be traded. With closed assets, the weights of non-tradable assets are fixed to their current drifted weights, and the softmax runs over cash and the tradable assets only (logits of non-tradable assets set to -inf), scaled to the remaining budget. Without this, DPM would output weights the env overrides, and its training objective would not match what the env executes. The classic baselines need the same rule (e.g. UCRP rebalances only tradable assets).

DPM and the Portfolio-Vector Memory fit this env. The PVM belongs to the training algorithm, not the env. DPM does not train by stepping the env: it samples contiguous windows of history, reads each period's previous weights from the PVM (a table indexed by time), computes all portfolio vectors of the window in parallel, evaluates the exact reward, takes a gradient-ascent step, and writes its outputs back. This is valid because actions do not change prices (zero impact), so the env is used for evaluation while training reads the data directly. Two requirements follow:

  1. Cost and reward math as a pure, batched, differentiable torch function (see Vectorized variant), so DPM's training objective and the env's evaluation reward cannot diverge.
  2. Batched access to the market data, tradable flags and price relatives for arbitrary index ranges, without stepping the env.

With market impact enabled, costs depend on portfolio value, so a PVM would also have to store portfolio value per period.

Implementation notes:

  • DPM: reimplement in PyTorch/TorchRL from the paper. The authors' PGPortfolio is TensorFlow-era, GPL-3.0 and inactive since 2021 (and per its README several versions ahead of the article), so it is a reference for checking behaviour, not code to vendor.
  • UBAH, UCRP, OLMAR: universal-portfolios implements bah, crp and olmar (plus ~20 more). Its license must be checked before reusing code; the algorithms are short enough to reimplement against the env interface.

Metrics (as in DPM §6.2, plus cost diagnostics): final accumulated portfolio value (p_f / p_0), Sharpe ratio of periodic returns (cash as the risk-free asset), maximum drawdown, turnover, and total costs split into commission, impact and funding.

Naming

PortfolioTradingEnv and VectorizedPortfolioTradingEnv, following the offline convention (SequentialTradingEnv, VectorizedSequentialTradingEnv). A live counterpart for a specific venue would follow the live convention, e.g. OKXPortfolioTorchTradingEnv.

Later: LLM policies

Once the env, DPM, the classic baselines and RL training work, LLM policies can be added as a bonus, e.g. an actor that renders the observation as text and parses a weight vector back into the action. Out of scope for this issue.

BY571 avatar Sep 14 '26 20:09 BY571

Done for the framework: #436 (PortfolioTradingEnv, VectorizedPortfolioTradingEnv, portfolio_step, PortfolioSampler, load_portfolio_dataset) and #438 (UBAH/UCRP/OLMAR baselines, portfolio_metrics, turnover, docs with baseline results at 1h/4h/1d). The DPM training recipe is developed separately and will be proposed here once it has results against UCRP. Leverage, market impact, cash_rate, next_open and summary features stay deferred until training results justify them.

BY571 avatar Sep 16 '26 12:09 BY571