Code & Kapital logoCode & KapitalQuant Research Systems
Portfolio ConstructionApril 11, 202612 min read

Research Article

Leverage and Margin in Python: Scaling Minimum Variance to Equal Weight Risk

A raw minimum variance portfolio often looks safer because it is simply running less risk. A better comparison is to scale it up to the volatility of equal weight, then make the borrowing cost explicit.

Core idea

Volatility matched

scale MinVar until risk matches equal weight

Leverage range

2.4x to 4.2x

average target leverage was about 3.2x

Funding lesson

Sharpe compresses

1.17 falls to 0.77 once financing is applied

By Code & Kapital ResearchApplied research for serious practitioners

Research standard

This article is written from a production-first perspective: assumptions are part of the result, not a footnote.

The emphasis is on failure modes, implementation detail, and why process quality matters more than an elegant historical curve.

The fair comparison is risk matched, not capital matched

A constrained minimum variance portfolio often looks excellent next to equal weight on volatility and drawdown, but that is only part of the story. In many cases it is also carrying dramatically less total risk. If one portfolio runs at roughly one-third of the volatility of another, comparing raw returns without adjusting for that gap is not really a like-for-like test.

The cleaner comparison is to scale the minimum variance portfolio until its realized volatility matches equal weight. Once that is done, the question becomes much more interesting: does the covariance-aware portfolio still deliver a better risk profile after leverage is introduced, and what happens once borrowing costs are no longer ignored?

Related article

This article builds directly on the minimum variance framework

If you have not read the minimum variance piece yet, start there first. This article assumes the covariance intuition, the optimization setup, and the constrained multi-asset example from that earlier research note.

Callout

Leverage is a comparison tool here, not a free lunch

The goal is not to make minimum variance look better by adding leverage mechanically. The goal is to compare two portfolios at the same risk level so the construction method, rather than the raw volatility gap, drives the interpretation.

How the volatility match works

The starting point is the realized volatility of two portfolios: equal weight and constrained minimum variance. The target leverage is simply the ratio of those two volatilities. If minimum variance is less volatile, the ratio will be greater than one, which means the strategy needs to be levered up to occupy the same risk budget.

That ratio is also where margin intuition enters. If the target leverage is L, gross exposure becomes L times capital, borrowed capital is approximately L minus 1, and the implied equity margin behind the position is 1 divided by L. A 3.0x target therefore corresponds to roughly 200% borrowed capital and an implied margin of about 33%.

Target leverage and implied margin

The implementation can be written in two short steps: first compute the risk-matching leverage ratio, then apply it to the minimum variance weights.

Lt = σEW,t / σMV,t
wlevered,t = Lt wMV,t
Implied margint = 1 / Lt

When minimum variance volatility is much lower than equal weight volatility, the leverage ratio can become meaningfully larger than one, which is exactly why financing assumptions matter in the next step.

Computing the leverage target in Python

python

window = 252

realized_vol = returns.rolling(window=window, min_periods=window).std() * np.sqrt(252)
target_leverage = realized_vol["Equal Weight"] / realized_vol["MinVarConstrained"]
target_leverage = target_leverage.to_frame(name="MinVar Target Leverage").dropna()

This is the risk-matching logic directly. The realized-volatility window determines how quickly the leverage estimate moves, so this choice is part of the strategy definition rather than a cosmetic implementation detail.

The required leverage is high because minimum variance runs much less risk

Target leverage
54322015-122019-052022-112026-04

Across the sample, the target leverage ranged from about 2.4x to 4.2x and averaged roughly 3.2x. That implies a margin profile that is far from trivial, which is why a raw minimum variance portfolio and an equal-weight portfolio should not be compared on headline returns alone.

What that leverage ratio is really saying

The message from the chart is not just that minimum variance is low volatility. It is that the constrained portfolio is so low volatility that matching equal weight requires material leverage almost the entire time. In gross-exposure terms, the strategy is often running around three dollars of assets for each dollar of equity.

That also makes the implied margin easy to interpret. Near the low end of the leverage range, a 2.4x target implies equity of about 42% of gross exposure. Near the high end, a 4.2x target implies equity closer to 24%. Even before financing is modeled explicitly, that should change how the strategy is evaluated.

Callout

The Code & Kapital Backtesting Engine handles this workflow directly

This kind of setup is built for the Code & Kapital Backtesting Engine: covariance estimation, weighting, leverage scaling, margin handling, and financing can all live inside one reproducible research pipeline instead of being stitched together manually across disconnected steps.

What margin is actually doing here

Margin is the mechanism that allows gross exposure to exceed the capital in the account. Once the portfolio is scaled above 1.0x exposure, part of the position is no longer funded by equity alone and must be supported by borrowed capital. In practical terms, that means a levered portfolio is partly financed by the investor's own capital and partly financed by a lender or broker balance sheet.

That is why leverage and margin should be thought about together. Leverage describes the size of the portfolio relative to equity, while margin describes how much equity is required to support that exposure and what happens when financing or collateral constraints become binding. In a backtest, making margin explicit is a way of acknowledging that the portfolio is not just magically larger. It is larger because borrowed capital is being introduced into the process.

Applying leverage and margin in the backtest

python

strat_minvar_levered = Strategy(
    "MinVarLevered",
    [
        RunAfterDate("2016-01-01"),
        RunDaily(),
        SelectAll(),
        cov_algo,
        WeightMinVar(bounds=(0.01, 0.4)),
        ScaleWeights(scale=target_leverage),
        Margin(margin=6),
        Rebalance(),
    ],
)

This scales the constrained minimum variance weights by the target leverage series and then applies margin explicitly in the strategy definition. That keeps the borrowing assumption visible inside the research workflow instead of burying it in a post-processing adjustment.

Risk matching brings the return comparison much closer

Equal Weight
MinVar
MinVarLevered
MinVarLeveredFinancing
60040020002015-122019-062022-102026-04

Once the minimum variance portfolio is levered to roughly the same volatility as equal weight, its cumulative path becomes much more comparable. The gap in headline performance narrows sharply, which is exactly the point of doing the risk match in the first place. Adding a financing series then shows how quickly the edge can fade once leverage is no longer treated as free.

Equal weight vs minimum variance vs levered minimum variance

MetricEqual WeightMinVarMinVarLeveredMinVarLeveredFinancing
CAGR14.2%4.3%13.6%8.5%
Volatility11.7%3.5%11.5%11.5%
Max Drawdown-22.8%-7.2%-21.6%-21.8%
VaR-1.0%-0.3%-1.0%-1.1%
Sharpe1.201.211.170.77

This table reports CAGR, annualized volatility, maximum drawdown, daily 95% VaR, and Sharpe ratio for the four portfolio variants shown above. In the funding-cost version, the borrowed balance is charged using the Fed Funds rate as a simple short-term financing proxy.

What changes once the comparison is made properly

The table reframes the earlier minimum variance result. On a standalone basis, the constrained minimum variance portfolio compounds at only 4.3%, but it does so at just 3.5% volatility and a 7.2% maximum drawdown. After levering it to equal weight risk, CAGR rises to 13.6%, almost closing the gap with equal weight's 14.2%, while drawdown still remains modestly better at 21.6% versus 22.8%.

That is the interesting middle ground. The covariance-aware portfolio does not suddenly dominate equal weight after leverage is introduced, but it does look far more competitive than the raw unlevered comparison suggests. In other words, much of the original return gap was simply the price of running a much smaller risk budget.

Related article

This is also why implementation assumptions matter so much

Leverage can make a backtest look cleaner or worse depending on how timing, turnover, slippage, and financing are handled. If those assumptions are sloppy, the resulting curve becomes much less informative than it appears.

Borrowing costs are the next reality check

Matching volatility is still not enough on its own, because leveraged portfolios do not borrow for free. A simple funding proxy is the Fed Funds rate. That is not meant to replicate every broker or prime-broker financing schedule exactly, but it is a clean baseline for showing that the economics of leverage depend on the rate regime.

This matters most when the target leverage is persistently high. A strategy that regularly runs around three times gross exposure is effectively renting a large amount of balance sheet. When funding costs rise, part of the apparent portfolio edge is transferred away through financing drag.

Related article

Need the rate data itself

The financing assumption in this article uses the Fed Funds series as the borrowing-rate proxy. If you want the underlying workflow for pulling and structuring that macro data in Python, the FRED article walks through it step by step.

Funding costs stopped being negligible once rates moved higher

Fed Funds
64202016-012019-052022-102026-02

The Fed Funds rate remained trivial for part of the sample and then rose sharply. That regime change is exactly why financing can leave a levered strategy looking acceptable in one period and much less compelling in another.

Applying a financing rate inside the strategy

python

strat_minvar_levered_financing = Strategy(
    "MinVarLeveredFinancing",
    [
        RunAfterDate("2016-01-01"),
        RunDaily(),
        SelectAll(),
        cov_algo,
        WeightMinVar(bounds=(0.01, 0.4)),
        ScaleWeights(scale=target_leverage),
        Margin(margin=6, financing_rate=fedfunds / 100),
        Rebalance(),
    ],
)

This keeps the financing drag inside the backtest rather than bolting it on afterward. That is the right way to evaluate leveraged portfolio construction, because the cost of balance sheet is part of the strategy, not an optional footnote.

Callout

This side-by-side comparison fits naturally inside Portfolio Diagnostics

The Code & Kapital Portfolio Diagnostics workflow is designed for exactly this type of review: compare raw and risk-matched portfolios, inspect the drawdown trade-off, and measure how financing assumptions compress Sharpe and cumulative performance before capital is committed.

Leverage does not fix a portfolio. It reveals what the portfolio actually looks like once risk is held constant.
Code & Kapital Research

A better way to judge the strategy

The main lesson is simple. A low-volatility optimizer should not be evaluated only on raw return because part of the return shortfall may just be the result of running much less risk. Volatility matching closes that gap and turns the comparison into a cleaner test of construction quality.

The second lesson is just as important. Once leverage is made explicit, margin and financing become central research variables. That is where production-minded portfolio construction begins: not with a prettier chart, but with a clearer accounting of how much risk, borrowing, and implementation drag the strategy truly requires.

Continue the research

Receive future research and product updates directly.

Join the newsletter for serious commentary on backtesting, data engineering, portfolio construction, and the systems behind robust quant work.

Weekly research notes, product updates, and serious quant commentary.

No spam. Unsubscribe anytime.

Related Research

Continue reading

View research archive