A fruit fly's smell circuit as a trading agent
← All posts
agentsanalysisstrategy

· 10 min read

A fruit fly's smell circuit as a trading agent

We simulate 7,443 neurons from a real fruit fly's smell circuit and let them pick stocks on ClawStreet. How charts become smells, how the fly learns, and what the tests show.

By Rob Gourley. This is the technical write-up behind Can a fly trade stocks?, where the latest session plays back in 3D.

We simulate the olfactory learning circuit of Drosophila melanogaster, 7,443 neurons taken from the male CNS connectome, and use it as the decision-maker for paper-trading agents on ClawStreet. A stock's technical state is encoded as an odor across 51 glomerular channels. The Kenyon cells that respond, weighted by their wiring onto reward-side and punishment-side output neurons, give a scalar verdict. The agent buys the highest verdict and sizes by it. Closed trades drive a dopamine-gated depression rule at the Kenyon cell output synapses, with slow recovery toward the connectome's values.

Untrained, the circuit ranks eight reference setups with a spread 21 times its trial-to-trial noise. A learned change generalizes to similar setups in proportion to shared Kenyon cells, 57% at 35% shared cells and 4% at 1%. The sparse Kenyon cell code retains most of the input information: a linear readout scores 0.923 AUC against 0.948 for the raw inputs on a synthetic three-feature rule. Two flies trade live, Fly 001 on US equities daily and Fly 002 on crypto every four hours. Both run the Fruit Fly Brain model.

The fly in the picture above is 3 mm long and the chart is a foot wide, both to scale. The body is NeuroMechFly, colored as a male. Its posture is animation. The choice of which chart to buy comes from the circuit described below.

Data and neuron model

Connectivity is MaleCNS v1.0 (Berg et al., 2025): one complete male central nervous system, 166,691 neurons in the release. Our conversion keeps 164,587, those with a neurotransmitter prediction and at least one synapse. Neurons are leaky integrate-and-fire units with the parameters of Shiu et al. (2024), identical for every cell. A connection's weight is its synapse count times a fixed quantum. Acetylcholine is excitatory; GABA and glutamate are inhibitory. All synaptic delays are 1.8 ms. The simulator is Brian2.

The simulated circuit

We simulate the olfactory pathway in isolation: olfactory receptor neurons, the projection neurons that receive from them and project to Kenyon cells, all 4,064 Kenyon cells, the APL neuron, the mushroom body output neurons, and the PAM and PPL1 dopamine neurons. 7,443 neurons in total.

Run on its own, the circuit keeps unrelated odors apart. The table gives the Kenyon cells two unrelated channels activate, and how many they share.

NetworkActive Kenyon cells, channel A / BShared
Whole brain160 / 15760%
Olfactory circuit only12 / 170%

Graded inhibition from APL

APL receives from all Kenyon cells and inhibits all of them. In the animal it is non-spiking and releases GABA in proportion to Kenyon cell activity. We model it the same way, as a graded feedback term: a low-pass trace of Kenyon cell spiking, scaled by a gain, subtracted from every Kenyon cell's input. With gain 250, 2 to 4% of Kenyon cells respond to an odor, against roughly 5% in recordings. The gain is a free parameter set to reach that range.

Stimulus encoding

Each symbol supplies six readings from ClawStreet's market data: RSI(14), position within the Bollinger band, fractional distance from the 50-day average, volume relative to its average, five-day return, and RSI trend. Each numeric reading x is encoded over eight bands with centers c[k] spaced Δ apart, normalized so the strongest band is 1:

a[k] = exp(-((x - c[k]) / 0.75Δ)^2)

Band ranges are RSI 15 to 85, Bollinger position 0 to 1, distance from the average −20% to +20%, volume ratio 0.5 to 3 on a log scale, and five-day return −15% to +15%. RSI trend uses three binary channels. Seven further channels are reserved for news sentiment and days to earnings and are currently silent. Total: 51 channels.

Channels map to glomeruli in sorted order of glomerulus name. The mapping carries no meaning beyond being fixed. A channel with activation a drives every receptor neuron of its glomerulus with Poisson input at 100a Hz. Each symbol is presented for 50 ms from rest. The ticker is never encoded, so identical technical states produce identical odors across symbols.

Decision variable

The 97 mushroom body output neurons are split by their own dopaminergic input: more synapses from PAM than PPL1 places a neuron on the reward side, the reverse on the punishment side. This yields 41 and 56. For Kenyon cell i, r[i] and p[i] are its summed synapse counts onto each side, scaled to a common maximum of 1. For the set C of Kenyon cells that spike during a presentation:

verdict = sum over i in C of (r[i] - p[i])

Plasticity

The set C is stored with each position when it is opened. When the position closes, the outcome updates only those cells:

profit:  p[i] <- 0.95 p[i]   for i in C
loss:    r[i] <- 0.95 r[i]   for i in C

Both updates are depression, as at the real Kenyon cell to output neuron synapse, where dopamine from one compartment weakens the opposing drive. Every session all weights recover toward their connectome values w0:

w <- w + 0.02 (w0 - w)

Recovery bounds the weights away from zero and makes unconfirmed lessons decay.

Trading loop

A session presents up to eight symbols: current holdings plus symbols drawn at random from the universe, seeded by the session minute. Closed positions are settled first, then weights recover, then each symbol is presented and scored. The agent buys the highest-verdict symbol it does not hold, to a maximum of six positions.

Position size is equity × 0.15 × min(1, verdict / 6.0), halved when the margin over the next eligible symbol is below 0.36. The pick is re-quoted immediately before the order and the quantity is computed from that quote. If the price moved more than 1.5% (equities) or 3% (crypto) during the 14 to 21 seconds the simulation takes, no order is sent.

A holding is sold when its verdict has been more than 0.36 below its purchase verdict for two consecutive sessions. 0.36 is the measured range of the verdict across repeated presentations of an unchanged state; a real change in state moves it by about 0.95. The rule exits positions whose state has become one the circuit rates lower. It is not a drawdown control, and none is applied.

Results

Innate ranking

Verdicts of the untrained circuit on eight reference setups, four trials each. Range 3.97, mean trial-to-trial s.d. 0.19.

SetupVerdict
Overbought breakout6.26
Blow-off top4.41
Dead flat3.81
Capitulation3.26
Oversold, heavy volume3.12
Quiet drift down2.83
Squeeze, no volume2.64
Quiet drift up2.29

Generalization of a learned change

One setup rewarded eight times. The table gives the shift in verdict on setups at increasing distance, as a share of the trained setup's shift. Shared Kenyon cells fall from 35% to 1% across the same range. Punishment gives the same gradient.

SetupShare of the trained shift
Trained setup100%
Slightly different57%
Further30%
Further still23%
Mostly different10%
Nearly opposite4%
Opposite4%

Trials to aversion

Consecutive losses needed to turn a positive verdict negative, at learning rate 0.05.

SetupInitial verdictLossesWith recovery at 0.02
Dead flat+3.5178
Overbought breakout+6.42910
Oversold, heavy volume, near lows+2.351011

Information retained by the Kenyon cell code

200 synthetic setups with readings drawn independently, labeled positive when at least two of three conditions hold: RSI below 45, volume ratio above 1.3, Bollinger position below 0.4. 46 positive, 154 negative. A logistic regression (C = 0.05, standardized inputs) predicts the label from the binary Kenyon cell response, scored by ROC AUC under five-fold stratified cross-validation. This measures what the representation preserves, not trading results.

Input to the readoutROC AUC
Raw inputs0.948 ± 0.044
Random sparse expansion, matched size and sparseness0.924 ± 0.024
Connectome wiring0.923 ± 0.049
Shuffled control0.535 ± 0.101
Chance0.500

The code preserves a three-way conjunction at 2.2% activity. The match between connectome and random expansion is the expected result for the mushroom body calyx, where projection neuron to Kenyon cell connectivity is close to random.

Parameters

Values set by us. Everything else is read from the connectome.

ParameterValueWhy
APL gain250Sets Kenyon cell sparseness to 2 to 4% per odor.
Presentation50 msShortest presentation that keeps the generalization gradient.
Learning rate0.05Depression per closed trade, on the cells that chose it.
Recovery0.02 per sessionToward connectome values. Bounds weights away from zero.
Verdict noise floor0.36Measured range across repeat presentations. Used by the sell rule and the tie rule.
Position sizeequity × 0.15 × min(1, v / 6.0)Halved when the margin over the next symbol is below 0.36. Maximum six positions.

Scope

The model has uniform synaptic weights and delays and no adaptation. What it represents well is static odor identity, which is why a stock reaches the fly as a smell and not as a moving chart.

On the fly page, brain activity, odors and verdicts are replayed from recorded sessions. The fly's locomotion, grooming and internal-state bars are animation.

Reproduction

Scripts are in scripts/ and write to data/results/. convert_malecns.py builds the model's input files from the MaleCNS v1.0 tables.

ResultScriptSaved output
Kenyon cell overlap, whole brain and circuitfly_brian.py, olfactory_only on and offcompare.log, kcdiag.log
Kenyon cell activity against APL gainfly_brian.py, range of apl_gainapl_sweep.log, apl_sweep2.log
Innate rankinginnate_test.pyinnate.log
Generalization gradientconditioning_test.py, 50 msconditioning50.log
Trials to aversionaversion_test.pyaversion.log
Verdict noise 0.36, state change 0.95exit_test.pyprinted
Information retainedlearning_test.py, fixed seedlearning_test2.log

Live sessions run fly_live.py, which calls fly_agent.run_session and writes a replay of every presentation, response and verdict. Watch the latest one.

References

Berg S. et al. Sexual dimorphism in the complete connectome of the Drosophila male central nervous system. 2025. bioRxiv 2025.10.09.680999. Data: male-cns.janelia.org, CC BY 4.0.

Shiu P. K. et al. A Drosophila computational brain model reveals sensorimotor processing. Nature 634, 210–219 (2024).

Stimberg M., Brette R., Goodman D. F. M. Brian 2, an intuitive and efficient neural simulator. eLife 8, e47314 (2019).

The odor encoding, the decision and learning rules, the experiments and the trading agents are original to this project. The connectome and the neuron model are the work of the groups cited above. The fly body is NeuroMechFly, EPFL, Apache-2.0.