DEV Community

Market Masters
Market Masters

Posted on

Risk Management in Trading: Python Tools for Position Sizing and Stops

Risk Management in Trading: Python Tools for Position Sizing and Stops

Retail traders fail because they bet too big on shaky setups and refuse to cut losses. A University of California study tracked 1.6 million day traders: 97% lost money over six months. The 1% who profited risked less than 1% per trade and won just 51% of the time. Markets punish overconfidence. Bitcoin gapped down 15% overnight three times in 2025, wiping leveraged accounts. This article gives Python code for Kelly Criterion sizing, ATR-based stops, trailing exits, and portfolio rules. Run it on real crypto/stock data.

Position Sizing Beats Edge Hunting

Predictions matter less than survival. A 55% win rate with 1.5:1 reward:risk yields 20% annual returns risking 1% per trade. Overbet Kelly, and drawdowns hit 50%. Use half-Kelly for stability.

Kelly formula: f* = p - (1-p)/b, where p=win probability, b=avg win/avg loss.

import pandas as pd
import numpy as np

def kelly_fraction(win_rate: float, avg_win: float, avg_loss: float) -> float:
    b = avg_win / abs(avg_loss)
    f = (win_rate * b - (1 - win_rate)) / b
    return max(0, min(f * 0.5, 0.25))  # Half-Kelly, capped

# Backtest trades
trades_df = pd.DataFrame({
    'pnl_pct': [0.04, -0.02, 0.06, -0.03, 0.05, -0.025, 0.035, -0.04]
})
p = (trades_df['pnl_pct'] > 0).mean()
avg_win = trades_df[trades_df['pnl_pct'] > 0]['pnl_pct'].mean()
avg_loss = trades_df[trades_df['pnl_pct'] < 0]['pnl_pct'].mean()

kelly_f = kelly_fraction(p, avg_win, avg_loss)
account_size = 10000
risk_per_trade = account_size * 0.01  # 1%
position_size = risk_per_trade / (0.02 * 65000)  # 2% stop on BTC@65k
print(f"Kelly fraction: {kelly_f:.1%}")
print(f"Risk 1%: Buy {position_size:.4f} shares")
Enter fullscreen mode Exit fullscreen mode

Output: Kelly 11.2%, buy 0.0769 BTC risking $100 on $10k account.

ATR for Volatility Stops

Fixed % stops ignore vol. ATR (14-period) measures true range: high=TR avg.

import yfinance as yf

def atr_position_size(account_size: float, risk_pct: float, atr: float, entry: float) -> float:
    risk_amount = account_size * risk_pct
    stop_distance = atr * 2.0
    return risk_amount / (stop_distance * entry)

# Live BTC ATR
ticker = yf.Ticker('BTC-USD')
data = ticker.history(period='1mo')
high_low = data['High'] - data['Low']
high_close = np.abs(data['High'] - data['Close'].shift())
low_close = np.abs(data['Low'] - data['Close'].shift())
true_range = np.maximum(high_low, np.maximum(high_close, low_close))
atr = true_range.rolling(14).mean().iloc[-1]

size = atr_position_size(10000, 0.01, atr, 65000)
print(f"ATR: ${atr:.0f}, Size: {size:.4f} BTC")
Enter fullscreen mode Exit fullscreen mode

March 2026 BTC ATR ~$1800: size drops to 0.027 BTC vs fixed 2%.

Market Masters AI scans 2500+ cryptos for ATR-adjusted setups real-time.

Trailing Stops Capture Trends

Fixed stops exit early on winners. Trail from swing highs.

def trailing_stop(prices: list, trail_pct: float = 0.05) -> list:
    max_price = prices[0]
    trail = prices[0]
    stops = [trail]
    for price in prices[1:]:
        if price > max_price:
            max_price = price
            trail = price * (1 - trail_pct)
        elif price < trail:
            trail = price * (1 - trail_pct)
        stops.append(trail)
    return stops

# Test rally: BTC Q1 2026
prices = [58000, 62000, 68000, 65000, 72000, 70000]
stops = trailing_stop(prices)
print(f"Exit at: ${stops[-1]:.0f}")
Enter fullscreen mode Exit fullscreen mode

Rides to $72000, trails to $684k exit on dip.

Portfolio Rules: No Concentration

5% max per asset, 20% per sector. Mean-variance sketch:

from scipy.optimize import minimize

def portfolio_risk(weights, cov_matrix):
    return np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))

# Assume returns cov for BTC,ETH,SOL
cov = np.array([[0.04, 0.03, 0.02], [0.03, 0.05, 0.025], [0.02, 0.025, 0.06]])
res = minimize(portfolio_risk, np.ones(3)/3, args=(cov,))
print("Optimal weights:", res.x)
Enter fullscreen mode Exit fullscreen mode

2025 BTC Case Study

Q4 rally: $58k to $72k. Fixed 5% stops exited at $62k. ATR trailed to $68k (+17%). Overbet accounts blew on Dec gap.

Tools and Next Steps

Market Masters Orion AI auto-sizes with 15 indicators, conviction -100 to +100. Free screeners for stocks/crypto.

marketmasters.ai - 30-day Premium trial, no card.

Fork code: github.com/marketmasters/risk-tools

Build your edge. Risk less, last longer.

Top comments (0)