Table of contents
Kelly_RM
Kelly_RM is an AlgoÉTS research repository about risk management with the Kelly criterion, the rule that sets a bet size from the probability of winning and the payoff ratio. Its root README is empty; the code pairs a coin-flip simulation of Kelly betting with a notebook that backtests an RSI strategy, measures win odds per ticker and turns them into a Kelly fraction. It suits readers who want to see how the formula behaves before applying it to a strategy.
1. Overview
Kelly_game/betting_strategies.py defines BaseGame, a repeated biased coin-flip game. Subclasses only decide the wager: Kelly bets the optimal fraction of wealth, KellyWithAnEstimate waits ten flips and bets on the observed frequency, ConstantDollar bets a fixed amount and BetLikeADummy bets big after three tails. The class plots wealth paths, simulates growth-rate distributions and draws expected growth against the fixed fraction wagered, with the Kelly point marked. Kelly_game/Playing the Game.ipynb runs the four strategies side by side; it describes itself as companion code for a video on the Kelly criterion.
sandbox/Main strategy.ipynb applies the idea to trading. It downloads price histories through src/data.py (Financial Modeling Prep and Binance helpers built on src/request_api.py), splits each series into three years of training data and an unseen remainder, and optimizes RsiOscillator from src/strategy.py with backtesting.py. From the resulting trade tables it computes, per ticker, the win probability and the mean and variance of win and loss sizes, keeps tickers seen in both periods, then applies f* = (p·b − q)/b with b = mean win / mean loss.
2. Use cases
Notebooks and helpers to estimate trade odds from backtests and size positions with the Kelly criterion.
- Simulate the Kelly coin game
- Quant researcher
BaseGame in Kelly_game/betting_strategies.py plays biased coin flips; Kelly, KellyWithAnEstimate, ConstantDollar and BetLikeADummy set the wager, and Playing the Game.ipynb plots wealth paths and growth rates with Altair.
- Download price history
- Quant researcherMarket data APIs
src/data.py wraps Financial Modeling Prep historical-price-full endpoints and Binance futures klines; src/request_api.py sends the requests with httpx and src/config.py reads the API keys from the environment.
- Optimize an RSI strategy
- Quant researcher
sandbox/Main strategy.ipynb splits each series into three training years and an unseen remainder, then grid-searches RsiOscillator bounds and window with backtesting.py and shows a seaborn heatmap.
- Estimate win odds per ticker
- Quant researcher
From each backtest trade table the notebook computes win probability, mean and variance of win and loss sizes per ticker, on training and unseen data, and keeps tickers present in both.
- Compute the Kelly fraction
- Quant researcher
The Kelly Criterion section applies f* = (p·b − q)/b with b = mean win size / mean loss size and stores the result in a Kelly_Fraction column.
2.1. Scenario: Size RSI trades with the Kelly criterion
- Run pip install -r requirements.txt, add the missing notebook packages (pandas_ta, scipy, sympy) and set FMP_API_KEY in the environment.
- Open sandbox/Main strategy.ipynb; it reads S&P 500 symbols from Wikipedia and downloads ten price histories through src/data.py.
- Split each series into a three-year training set and an unseen set.
- Optimize RsiOscillator with Backtest.optimize and read the parameter heatmap.
- Compute win probability and win/loss sizes per ticker on both sets, then the Kelly fraction for each kept ticker.
Files readREADME.mddocs/README.mdrequirements.txtrequirements-dev.txtenvironment.ymlsrc/config.pysrc/data.pysrc/request_api.pysrc/strategy.pysrc/signal.pyKelly_game/betting_strategies.pyKelly_game/Playing the Game.ipynbsandbox/Main strategy.ipynbdocs/notebook/strategy.ipynb
3. How the algorithm works
The Kelly fraction. For a bet won with probability p that pays b times the stake (and loses the stake otherwise), the fraction of wealth that maximises the long-run growth rate is
f* = p − q / b = (p·b − q) / b, with q = 1 − p
BaseGame.kelly_bet computes p + (p − 1) / b, the same expression, and clips it to [0, 1]: no short bets and no leverage. The quantity Kelly maximises is the expected log growth per bet, g(f) = p · ln(1 + b·f) + q · ln(1 − f), which plot_exp_growth_rates_by_perc_wager draws against f.
Worked example with the notebook’s game. Playing the Game.ipynb uses p = 0.5, b = 1.5, 10 flips and 500 $ of starting wealth.
| Fraction wagered | g(f) per flip | Typical wealth after 10 flips |
|---|---|---|
| 5% | +1.05% | × 1.11 |
| f = 1/6 ≈ 16.7%* | +2.04% | × 1.23 |
| 1/3 (twice Kelly) | 0.00% | × 1.00 |
| 40% | −2.04% | × 0.82 |
So the first Kelly bet is 500 / 6 ≈ 83.33 $. Betting twice the Kelly fraction gives zero growth, and anything above it shrinks wealth over time even though every flip has a positive expected value. The “typical wealth” column is exp(10 · g), the median outcome, not the mean.
The four strategies. Kelly bets f* of current wealth with the true p. KellyWithAnEstimate bets nothing for the first ten flips, then uses the observed heads frequency as p. ConstantDollar bets a fixed amount whatever the wealth. BetLikeADummy bets big after three tails in a row, the gambler’s fallacy. play_game caps any wager at the current wealth and stops at zero.
From coin flips to trades. sandbox/Main strategy.ipynb optimises an RSI strategy per ticker on its first three years of data (the loop downloads the first ten S&P 500 symbols, through the FMP helper written for crypto pairs), takes the trades, and computes per ticker p = share of winning trades, a win size and a loss size, then b = win size / loss size and f* = (p·b − q)/b.
flowchart LR
T["First 10 S&P 500 symbols"] --> D["Daily prices (FMP), first 3 years = training"]
D --> O["backtesting.py optimize: RSI window 10–25, bounds 15–55 / 35–80"]
O --> TR["Trade list per ticker"]
TR --> P["p = winning trades / trades"]
TR --> W["mean win, mean loss"]
P & W --> K["f* = (p·b − q) / b, b = win / loss"]
TR --> BT["Binomial test of p against 0.5"]
In the notebook, Win_Size is 0 for losing trades and Loss_Size is 0 for winning trades, and both are then averaged over all trades. The means are therefore p · E[win] and q · E[loss], so b comes out as (p · E[win]) / (q · E[loss]) instead of the payoff ratio E[win] / E[loss]. For p = 0.6, the computed b is 1.5 times the true ratio, which inflates the Kelly fraction.
4. Getting started
The French project description in docs/README.md gives the install step:
pip install -r requirements.txt
jupyter notebook
Set FMP_API_KEY (and BINANCE_API_KEY for the Binance helper) in the environment; src/config.py reads them. The notebooks also import packages that are not in requirements.txt, such as pandas_ta, scipy, sympy and altair; environment.yml is a full conda export that adds pandas-ta and SciPy but not every import.
5. Repository guide
Kelly_game/betting_strategies.pycontains the coin-flip game and its betting strategies.Kelly_game/Playing the Game.ipynbcompares the strategies with Altair charts.sandbox/Main strategy.ipynbruns the RSI optimization, odds estimation and Kelly fraction.src/data.py,src/request_api.pyandsrc/config.pyfetch prices from FMP and Binance.src/strategy.pydefines theEmaandRsiOscillatorbacktesting.py strategies.src/signal.pydraws support and resistance lines with trendln and an R² threshold.docs/README.mdis the French project description;docs/Kelle_complement.pdfis a reference paper on optimal trading under parameter uncertainty with a Monte Carlo approach.docs/notebook/strategy.ipynbis an empty placeholder.
6. Features
- Kelly, estimated-Kelly, constant-dollar and “bet big after tails” strategies on a simulated coin;
- wealth-path charts, growth-rate histograms and expected growth versus wager fraction;
- FMP stock and crypto history and Binance futures klines through httpx;
- RSI parameter grid search with a seaborn heatmap;
- per-ticker win probability and win/loss size statistics on training and unseen data;
- Kelly fraction per retained ticker.
7. Limits
- The root
README.mdis empty.docs/README.mddescribes risk limits inconfig.py, volatility adjustment, a user interface and a main script; none of these are in the code, andsrc/config.pyonly holds API keys and base URLs. - Dependencies are incomplete:
pandas_ta,trendln,fmp_python,scikit-learn,scipy,sympyandaltairare imported but not listed inrequirements.txt. sandbox/Main strategy.ipynbinserts a hard-coded Windows path intosys.pathand calls the crypto price helper for S&P 500 stock symbols. It usesDataFrame.append, which pandas 2 removed, and its consistency filters are set to −1, which disables them.- In
src/strategy.py, theEmastrategy computes its 150-period line with the 80-period parameter. - There are no tests, although
pytestis inrequirements-dev.txt. - Results depend on saved notebook state and live API data; the repository does not record them.
8. Sources
- GitHub repository
- Project description (
docs/README.md) Kelly_game/betting_strategies.pysandbox/Main strategy.ipynbsrc/data.pysrc/strategy.py
9. CI/CD pipeline
No CI/CD pipeline in the repository. The code is built and run by hand, as described above.
Generated from the source at commit faf4eeb.
10. Deployment diagram
Mermaid Deployment diagram
flowchart LR
repo[("GitHub repository")]
local["Local machine<br/>Python"]
repo -->|"clone and run"| local
The repository has no Dockerfile, Compose file or hosting configuration, so the code runs on the machine that clones it.
11. External dependencies
7 declared packages (7 runtime, 0 development) in requirements.txt.
Package table 7
| Package | Version | Scope | Purpose | Registry |
|---|---|---|---|---|
python-dotenv | ==0.21.1 | runtime | Configuration | pypi.org |
backtesting | ==0.3.3 | runtime | Testing | pypi.org |
pandas | ==1.4.0 | runtime | Data analysis | pypi.org |
polars | ==0.13.3 | runtime | Data analysis | pypi.org |
numpy | ==1.24.2 | runtime | Data analysis | pypi.org |
matplotlib | ==3.5.1 | runtime | Charts | pypi.org |
seaborn | ==0.11.2 | runtime | Charts | pypi.org |
12. Glossary
Repository
The versioned source files, configuration, and history of a project.
README
The repository’s entry document, usually covering its purpose and initial setup.
Dependency
A library, tool, or service that another component needs to build or run.
API
An interface through which software components exchange requests and results. An API does not have to use HTTP.
HTTP
A request-and-response protocol used by browsers and web services. A method, path, headers, and optional body describe a request.
Volume and bind mount
A volume is storage managed by the container platform; a bind mount exposes a chosen host path inside a container.
CLI
A text interface in which commands and arguments select operations. Exit codes let scripts detect success or failure.
Mermaid
A text-based diagram language. Nodes and connections describe a model; the diagram itself does not execute the project.
13. References
- AlgoETS. (2026, November 5). Kelly_RM. [Software repository] github.com.
- AlgoETS. (2026, November 5). Project description (docs/README.md). [Source file or documentation] github.com.
- AlgoETS. (2026, November 5). Kelly_game/betting_strategies.py. [Source file or documentation] github.com.
- AlgoETS. (2026, November 5). sandbox/Main strategy.ipynb. [Source file or documentation] github.com.
- AlgoETS. (2026, November 5). src/data.py. [Source file or documentation] github.com.
- AlgoETS. (2026, November 5). src/strategy.py. [Source file or documentation] github.com.
Sources without a publication date show the date they were last checked, November 5, 2026. File links retain the inspected revision where available.