Back to blog
Applied ML

AthenAI: Compressing Thousands of Trading Algorithms into an RL State

How I built an offline macro-aware finance-RL pipeline around algorithm clustering, proxy labels, and honest backtesting boundaries.

Adam MaltoniPublished on 14 September 2026, 09:0020 min read
AthenAI strategy clustering diagnostics from the experimental report

The tempting version of a finance-RL competition project is to jump straight to the agent. Pick PPO, define an action space, train a policy, draw a beautiful equity curve. The AthenAI project pushed me in the opposite direction.

The hard part was not the acronym after "agent." The hard part was building a state representation that an agent could honestly learn from.

I treated the challenge less as "I know finance" and more as a representation-learning problem with unusually strict leakage rules. Every attractive idea had to pass a simple test: could this signal exist at decision time, and does it encode future performance by accident? If the answer was unclear, the feature had to be downgraded to diagnostics or future work.

The raw universe contained thousands of proprietary trading-algorithm files, each with intraday OHLC rows. There was also a benchmark trade file. A naive RL setup would treat every algorithm as an asset and ask a model to allocate across all of them directly. That is fragile for three reasons:

  • Many algorithm series are short, sparse, constant, or broken.
  • The universe is non-stationary.
  • Deployment should not depend on live macro APIs, even if macro labels are useful during training.

So the project became a layered offline pipeline:

raw algorithm CSVs
  -> daily close reconstruction
  -> quality gate
  -> return and trade encoding
  -> personality features
  -> behavioral clustering
  -> cluster-level time series
  -> rolling state features
  -> macro proxy layers
  -> RL/backtesting interface

That is less flashy than "trained a trading bot." It is also more honest.

AthenAI offline pipeline from raw competition files to daily returns, static personality, factor clustering, proxy state, and RL/backtesting interface.

The competition as an offline portfolio problem

The formal framing was a sequential portfolio-management problem. At each decision date, the system observes the current state of the algorithm universe and chooses a capital allocation. The reward arrives later through portfolio returns, adjusted for risk and costs.

In notation, a portfolio action can be written as a vector over C investable units:

w_t in simplex(C)
sum_c w_t,c = 1
w_t,c >= 0

The useful mental model is a constrained MDP, except the state is reconstructed offline and the action space is a compressed cluster universe:

s_t = [cluster_features_t, proxy_scores_t, alive_mask_t, w_t-1]
a_t = w_t

r_t+1 =
  dot(w_t, R_t+1)
  - cost_rate * ||w_t - w_t-1||_1
  - risk_penalty * max(0, drawdown_t+1 - drawdown_limit)

That last term was not about claiming a final production reward function. It was a design reminder: in portfolio RL, the agent should be punished for fragile equity paths, not only rewarded for point returns.

But the original universe had far too many raw algorithms for that to be a clean action space. The central design choice was to compress algorithm behavior into cluster-level "super-assets" before attempting RL.

The report is careful about scope: the final RL layer was developed as a DQN/backtesting interface, not as a completed PPO production result. PPO and SAC are good future candidates for continuous allocation, but the current artifact is mainly the data reconstruction, state-building, clustering, proxy modeling, and RL scaffolding.

Reconstructing the daily panel

Each algorithm file stores intraday OHLC rows with timestamps and close prices. The first step was to collapse each algorithm to a daily close:

P_i,t = last close observed for algorithm i on day t

From that, the system computed simple and logarithmic daily returns:

r_i,t = clip(P_i,t / P_i,t-1 - 1, -0.50, 0.50)
l_i,t = clip(log(P_i,t) - log(P_i,t-1), -0.50, 0.50)

The clipping threshold is wide by design. It is not meant to suppress ordinary strategy variation. It prevents broken close jumps from dominating rolling statistics, PCA, and distance-based clustering.

In the regenerated analysis documented in the report, the pipeline read 14,761 algorithm files and produced 8,879,120 daily algorithm rows. Of the 13,663 identifiers with usable rows, 9,491 passed the quality gate. That accepted set represented about 69.5% of observed algorithms, with a median of 639 daily observations and median calendar coverage of 84.6%.

Those numbers are the first important result. Before there is a model, there is a reconstructed universe.

The quality gate avoided performance leakage

The quality filter did not select "good" algorithms. It selected usable time series.

An algorithm passed if it had enough observations, enough calendar coverage, more than two unique close values, and non-negligible return volatility:

accepted if:
  n_i >= 60
  coverage_i >= 0.70
  unique_closes_i > 2
  std(return_i) > 1e-9

This is an important kind of restraint. Filtering by Sharpe, return, or drawdown at this stage would leak ex-post performance into every downstream result. The gate only removed series that were too short, too sparse, or effectively constant.

The accepted daily return distribution still had a large spike around zero and fat tails, which is what I would expect from strategy-like curves: many algorithms do little on a given day, while a smaller set makes discrete moves. The report gives the accepted universe mean daily return as approximately -0.008%, standard deviation as 0.493%, and 1%/99% quantiles of -1.67% and 1.53%.

The benchmark was a trace, not an oracle

The benchmark file contained 5,394 trades across 271 distinct algorithms, with a median holding period of 26 calendar days. It included product name, signed volume, opening date, closing date, invested amount, AUM, and end-of-day equity fields.

I encoded it as a position trace:

h_i,t = sum of signed volumes for open trades in algorithm i at time t
w_i,t = h_i,t / (epsilon + sum_k abs(h_k,t))

This is useful for forensics and sanity checks. It shows where the benchmark moved through the algorithm universe. But it should not be treated as an optimal policy label. The benchmark traded only 271 algorithms out of a much larger universe, and openings were concentrated in the later part of the sample. That makes it informative, but risky as the only imitation-learning target.

Algorithm personality features

The main modeling idea was that algorithms should not be anonymous columns. Each one has a behavioral profile: volatility, drawdown shape, tail risk, autocorrelation, momentum, and stability. I called this its static personality.

For each accepted algorithm, the pipeline computed features such as:

  • Mean return and standard deviation.
  • Annualized volatility.
  • Sharpe and Sortino ratios.
  • Empirical quantiles and tail ratios.
  • Skewness and excess kurtosis.
  • Maximum drawdown and ulcer index.
  • Average drawdown depth and time in drawdown.
  • One-day return autocorrelation.
  • Absolute-return autocorrelation.
  • 120-day log momentum.
  • Stability diagnostics across the first and second halves of the sample.

The familiar formulas are simple but useful:

Sharpe_i  = sqrt(252) * mean(r_i) / std(r_i)
Sortino_i = sqrt(252) * mean(r_i) / downside_std(r_i)

drawdown_i,t = P_i,t / max_previous_price_i,t - 1
max_drawdown_i = min_t drawdown_i,t

This feature vector gave the clustering layer economic meaning. Two algorithms can have the same average return but completely different tail behavior, drawdown persistence, and exposure to common factors.

Internal factors and exposures

The pipeline also built internal factor features. The simplest is the algorithm-universe market factor:

market_factor_t = mean return across alive algorithms at time t

It also computed PCA factors over a standardized return matrix. Each algorithm then received ridge-estimated exposures to the internal market and PCA factors. The point was not to create a perfect factor model; it was to add co-movement information to the static personality vector.

The clustering input was roughly:

algorithm_vector_i =
  [personality_i, factor_exposures_i, R2_i, residual_volatility_i]

The vectors were robust-scaled with median and interquartile range, then clustered.

Behavioral clusters as super-assets

The main clustering configuration in the report was behavioral_k100_v1: 100 clusters learned from robust-scaled personality and factor diagnostics. The project also implemented a correlation/PCA embedding cluster family, but the behavioral 100-cluster setup was the main downstream compression.

Cluster-level returns were built by averaging the returns of alive algorithms in each cluster:

R_c,t = mean return of algorithms assigned to cluster c and alive at time t
alive_ratio_c,t = alive algorithms in cluster c at time t / total algorithms in cluster c

This is where the learning problem changed. Instead of asking a model to understand around 9.5k accepted algorithm series directly, the state now had 100 behaviorally coherent super-assets, each with metadata, rolling features, and alive masks.

That compression is not cosmetic. It is the main contribution of the implementation.

Behavioral clustering diagnostics showing a robust-PCA view, cluster size profile, cluster risk-return map, and momentum hit-rate profile.

The clustering figure is the part of the project I would show first in an interview. It says more than "I used k-means." The PCA view checks whether the accepted algorithms have obvious outliers and co-movement structure. The size distribution checks whether the compression produced a few giant clusters and many tiny ones. The risk-return and hit-rate panels give the clusters a behavioral texture that an RL state can actually use. The clusters are not labels for a dashboard; they are the new action-space vocabulary.

Windowed state features

The state layer used multiple horizons because market behavior is not one-speed:

  • 5 and 10 days for short-term reaction and jump behavior.
  • 20 days for a trading-month view and realized volatility.
  • 60 days for quarterly-style Sharpe and drawdown proxies.
  • 120 days for slower momentum in the personality layer.

From cluster returns, the pipeline computed universe-level features such as breadth, dispersion, tails, rolling volatility, rolling correlations, jumpiness, and drawdown proxies.

For example:

breadth_t = fraction of clusters with positive return at t
dispersion_t = cross-sectional std of cluster returns at t

This matters because stress regimes often show up as joint patterns: falling breadth, rising correlation, higher volatility, fatter left tails. A single aggregate return cannot capture that structure.

Internal universe state reconstructed from cluster returns, including market return, cross-sectional breadth, volatility, and rolling correlation features.

This plot is exactly why I did not want a state made only of recent portfolio returns. The market factor, breadth, volatility, and correlation state move on different rhythms. Breadth is noisy but gives cross-sectional participation. Volatility clusters. Correlations spike and decay. A portfolio agent should see those differences because they imply different action costs: sometimes the right response is to reduce turnover, sometimes to rotate clusters, and sometimes simply to distrust the proxy layer.

Macro proxies without live macro dependency

The competition constraint made external macro data tricky. VIX, Treasury yields, and factor returns are valuable training context, but relying on live external APIs at deployment would weaken the offline design.

The compromise was a proxy layer:

during training:
  fetch external macro/factor data
  create targets
  train internal proxy models from algorithm-universe features

during prediction:
  use only internal features and trained proxy models

The report documents several proxy layers.

The VIX spike proxy attempted to predict large forward changes in log VIX. Its AUC was around 0.50 +/- 0.10, essentially baseline-like. Calibration improved expected calibration error from 0.036 to 0.0007, but the classification signal was weak.

The rates direction proxy predicted whether the 10-year Treasury yield moved down, stayed neutral, or moved up over a 10-day horizon. This was the strongest proxy, with documented sign accuracy of 80.6% +/- 10.8% and a shuffle leakage diagnostic separating real and shuffled targets.

The internal risk-off proxy used the future 10-day minimum return of the cluster market factor and marked the bottom decile as risk-off. In the regenerated target, the threshold was -0.301% and the positive rate was 9.93%. The current model AUC was around 0.46 +/- 0.10, so the target definition was useful, but the predictor was not yet strong.

The factor monitor aggregated universe features monthly and attempted to predict Fama-French-style factor signs, especially momentum. With only 54 monthly observations, it was treated as a diagnostic/future-work layer rather than a strong production signal.

This section is where I think the report is strongest: it reports negative results. The point was not to pretend every proxy worked. The point was to identify which macro concepts the internal universe currently can and cannot reconstruct.

The RL interface

After clustering and proxy construction, the decision state can be written as:

s_t = [
  rolling cluster features,
  internal universe state,
  proxy scores/probabilities,
  alive mask,
  previous allocation
]

The previous allocation matters because transaction costs depend on turnover:

portfolio_return_t+1 =
  dot(w_t, cluster_returns_t+1)
  - cost_rate * L1_norm(w_t - w_t-1)

The backtest then tracks equity:

E_t+1 = E_t * (1 + portfolio_return_t+1)

and reports metrics such as Sharpe, maximum drawdown, win rate, and Calmar ratio.

The current repository includes DQN scaffolding: replay buffer, target network, epsilon-greedy action selection, Smooth L1 loss, and backtesting utilities. Because DQN is discrete-action, the continuous portfolio simplex would need to be discretized into actions such as holding the previous allocation, shifting weight toward a selected cluster, moving to cash, or choosing among predefined cluster baskets.

For a future continuous-allocation version, PPO or SAC would make sense. But the report does not claim completed PPO performance, and neither should the blog post.

What the benchmark showed

The benchmark yearly return file showed positive returns in every available year. The best year was 2022 at 7.13%, followed by 2024 at 6.99%. The weakest was 2020 at 0.54%, with the caveat that the monthly file begins in June 2020. Compounding the monthly return file gave a total return of 22.95%, with a maximum monthly-resolution drawdown of -1.87%.

Benchmark diagnostics with year-over-year returns, cumulative monthly return, monthly return heatmap, and realized drawdown.

That drawdown should be read carefully. It is based on monthly benchmark returns, not fabricated intramonth equity. Again, the theme is restraint: report what the data supports and do not fill missing resolution with imagination.

What the project actually achieved

The final system was not a finished trading policy. It was an auditably constructed state and modeling pipeline:

  • Reconstructed a large algorithm universe into a daily panel.
  • Filtered algorithms using reliability rather than ex-post performance.
  • Encoded benchmark trades as an action trace.
  • Built static personality features for each accepted algorithm.
  • Compressed roughly 9.5k accepted algorithms into 100 behavioral clusters.
  • Built cluster-level returns, alive masks, and rolling features.
  • Trained and evaluated macro proxy layers with explicit leakage checks.
  • Exposed the resulting state to a DQN/backtesting interface.

The most important observation was that clustering changed the learning problem. Instead of presenting an RL agent with thousands of sparse, noisy algorithm columns, the model receives a smaller set of behaviorally coherent time series with interpretable metadata.

The lesson

A lot of applied ML work is won or lost before the model trains. This project is a good example. The interesting decisions were not only in the RL algorithm; they were in the representation:

What is an asset?
What counts as alive?
Which filters leak performance?
Which macro signals are allowed at deployment?
What should the action space see?
How do we report unsupported results honestly?

The AthenAI pipeline taught me that an offline finance-RL system should be built like an evidence chain. Every transformation needs a reason, every target needs a leakage story, and every final claim should be limited to what the regenerated artifacts support.

That is the kind of restraint that makes a competition project more useful after the competition is over.