py-beacon¶
py-beacon is a Python library for building indices, ETFs and Delta-1 derivatives. You define an index methodology, calculate the index's history on a real exchange calendar, backtest a portfolio that tracks it, and analyse the result. The same library runs the local engine behind the Beacon desktop app.
Install¶
py-beacon needs Python 3.11 or later.
In code, import it as beacon. A plain install does everything but serve the
API and download market data: data, indices, backtests, portfolios, funds,
derivatives, risk and analysis, charts and interactive charts, PDF and Excel
reports, the optimiser and Postgres stores. It brings pandas, numpy, pydantic,
exchange_calendars, matplotlib, plotly, fonttools, reportlab, openpyxl, scipy,
psycopg and platformdirs.
Two extras add the rest:
| Extra | Adds | For |
|---|---|---|
server |
fastapi, uvicorn, orjson, websockets | The local API server |
data |
yfinance | Downloading prices and reference data from Yahoo Finance |
Install one with pip install "py-beacon-kit[server]", or both with
pip install "py-beacon-kit[server,data]". Using a feature without its extra
raises a MissingDependencyError that names the extra to install. The docs
and dev extras are for building this site and working on py-beacon itself.
The extras earlier releases had for charts, reports, Excel, the optimiser and
Postgres (plot, plot-interactive, pdf, excel, optimise and
postgres) still install, and add nothing.
Quickstart¶
Define an index, calculate it, and backtest a portfolio that tracks it. The example builds its own small dataset, so it runs as it is. Each block is a cell, as in a notebook.
import logging
import numpy as np
import pandas as pd
from beacon.backtest import Backtest
from beacon.data import DataFetcher, MarketData, ReferenceData
from beacon.index import EqualWeighted, IndexDefinition
from beacon.index.schedule import sessions
logging.getLogger("beacon").setLevel(logging.ERROR) # keep the output short
Data. Four stocks priced on every New York Stock Exchange session in 2024, from a seeded random walk, and the reference data that lists them.
days = sessions(pd.Timestamp("2024-01-02"), pd.Timestamp("2024-12-31"), "XNYS")
names = ["AAA", "BBB", "CCC", "DDD"]
rng = np.random.default_rng(28)
returns = rng.normal(0.0004, 0.015, size=(len(days), len(names)))
closes = pd.DataFrame(100 * np.exp(returns.cumsum(axis=0)),
index=days,
columns=names)
prices = [{"IDENTIFIER": name,
"DATE": day,
"CLOSE": closes.at[day, name],
"SHARES_OUTSTANDING": 1_000_000}
for day in days
for name in names]
listings = [{"IDENTIFIER": name,
"NAME": name,
"CURRENCY": "USD",
"EXCHANGE": "XNYS",
"DATE_FROM": "2020-01-01"}
for name in names]
data = DataFetcher(MarketData.from_dataframe(pd.DataFrame(prices)),
ReferenceData.from_dataframe(pd.DataFrame(listings)))
The index. Equal weight across the four, rebalanced monthly on the NYSE calendar.
definition = IndexDefinition(index_id="DEMO",
index_name="Demo Equal-Weight Index",
base_date="2024-01-02",
base_value=1000.0,
currency="USD",
eligibility_rules=[],
weighting_scheme=EqualWeighted(),
rebalancing_frequency="MONTHLY",
calendar="XNYS",
universe_identifiers=names)
The backtest. Calculate the index, then simulate a portfolio trading to its weights, paying 5 basis points on every trade.
backtest = Backtest(initial_capital=100_000.0,
transaction_cost_bps=5.0,
data_provider=data)
result = backtest.run(definition,
end="2024-12-31")
Results. The index level and the portfolio's NAV each day, and the portfolio's summary metrics against the index.
daily = pd.DataFrame({"Index level": result.index.target.levels,
"Portfolio NAV": result.portfolio.nav})
daily.tail().round(2)
| Index level | Portfolio NAV | |
|---|---|---|
| 2024-12-24 | 1088.28 | 108747.08 |
| 2024-12-26 | 1091.06 | 109025.21 |
| 2024-12-27 | 1097.57 | 109675.70 |
| 2024-12-30 | 1119.11 | 111828.46 |
| 2024-12-31 | 1133.80 | 113295.48 |
| Portfolio | |
|---|---|
| total_return | 0.1330 |
| annualised_return | 0.1330 |
| volatility | 0.1214 |
| sharpe_ratio | 1.0888 |
| max_drawdown | -0.1148 |
| hit_rate_monthly | 0.5000 |
| tracking_error | 0.0005 |
| tracking_difference | -0.0008 |
Charts. The index among its four stocks, then the portfolio's growth and
drawdown. The charts here have no background of their own:
transparent-dark-axes is for a light page and transparent-light-axes for
a dark one, and these are shown in whichever matches yours. use("light")
and use("dark") draw on Beacon's own canvas.
from beacon.plot import use
use("transparent-dark-axes") # no background, for a light page
result.plot.constituents()


Any chart becomes interactive: .interactive() returns a plotly figure drawn
from the same layout, with a popup under the pointer giving each series' value
on the date there. Its HTML carries its fonts and plotly.js, so it works
offline.
result.index.target holds the index the run aimed at, and
result.portfolio holds the simulated portfolio: its NAV, positions, cash and
transactions. The portfolio ends a little behind the index because it pays
for its trades. Even without costs the two rarely agree exactly, because an
index level and a traded portfolio are calculated differently;
Backtest explains why.
How it fits together¶
Everything reads its data through one DataFetcher, and the work runs in
three layers, each depending only on the ones before it:
Methodology IndexDefinition: universe, rules, weighting, capping, schedule
|
v
Calculation IndexCalculator.run() -> IndexResult
| levels, divisor, what each rebalance decided, daily weights
v
Backtest Backtest.run() -> BacktestResult
the portfolio's books, compared with the index it tracked
- Methodology. An
IndexDefinitionholds the rules: a universe of identifiers, eligibility rules that select from it, a weighting scheme (EqualWeighted, orMarketCapWeightedwith optional free-float adjustment), an optional cap on any one constituent's weight, and a schedule. Every index names a trading calendar (an exchange MIC such asXNYS); there is no default. The definition also sets the rebalance day rule, the return type (price, total return or net total return), and how many sessions a new composition waits before taking effect. - Calculation.
IndexCalculator.run()walks the sessions of the index's calendar and returns anIndexResult: the index levels, the divisor history, the constituents and weights chosen at each rebalance, and the weights held on every day. - Backtest.
Backtestis the front door. You give it the assumptions (capital, transaction costs in basis points, currency, a benchmark) once, then callrun(definition, start, end)for each index. It calculates the index, reusing a cached calculation when it can, and hands the weights toBacktestEngine, which trades towards them on each rebalance (sells before buys). TheBacktestResultkeeps the portfolio's books onresult.portfolio, the calculated index onresult.index, and the benchmark, when one was given, onresult.benchmark.summary()gives the headline metrics andagainst(other)compares the run with anything that has a level series.
Funds, derivatives, the optimiser, risk models and analytics all build on these results. Concepts walks through each part.
What's in the library¶
| Module | What it does | Read more |
|---|---|---|
beacon.data |
MarketData, ReferenceData and the DataFetcher every calculation reads through; loading from files, a data store on disk, a Postgres database or Yahoo Finance |
Data, Serving data |
beacon.synthetic |
Realistic synthetic market data at demo scale, with the reference data, shares, free float and corporate actions to match | Serving data |
beacon.testing |
A small, fixed dataset for examples and tests | Sample dataset |
beacon.expressions |
Typed expressions such as data.market.market_cap > 1e9, used by rules and universes |
Expressions |
beacon.universe |
Building a universe by filtering rather than listing | Universe |
beacon.index |
IndexDefinition, eligibility rules, weighting schemes, capping, IndexCalculator and IndexResult, and optimised indices derived from another index |
Methodology |
beacon.backtest |
Backtest, BacktestEngine, modifiers that skip or adjust a rebalance, and BacktestResult |
Backtest |
beacon.portfolio |
The Portfolio ledger (holdings, cash, transactions, NAV) and Excel reporting |
Reference |
beacon.fund |
Fund, a fund product with share classes, a strategy and a vehicle |
Funds |
beacon.derivatives |
IndexFuture, ETFFuture and TotalReturnSwap, rate curves, futures term structures and pricing functions |
Derivatives |
beacon.optimise |
Constraints and solvers: tracking-error minimisation, minimum variance, efficient frontiers | Optimiser |
beacon.risk |
Covariance estimation with shrinkage, factor models and risk contributions | Risk model |
beacon.analysis |
Attribution, concentration, drift, liquidity, risk metrics and ETF tracking analytics | Attribution |
beacon.plot |
Charts through a .plot accessor on result objects |
Charts, Gallery |
beacon.report |
Paginated reports, rendered to PDF | Reports |
beacon.server |
The local API server Beacon desktop talks to | Server guide |
The Reference documents every public class and function. The example notebooks go further: backtest analysis, index futures, and optimised indices.