Algorithmic Trading & Indicators
Beginner
Dynamic ATR Trailing Stop-Loss & Position Sizing Calculator in Python
Calculate volatility-adjusted Average True Range (ATR) trailing stop-loss levels and exact share/lot position sizes based on fixed account risk percentage.
#pandas#numpy
Problem Statement
Fixed percentage stop-losses get whipped out in high-beta stocks and leave too much risk on the table in low-volatility stocks. This script computes dynamic ATR stops and exact position size per trade.
Formula / Core Logic
Long Stop = Entry_Price - (Multiplier x ATR_14)
Position Size (Qty) = (Account_Capital x Risk_Pct) / (Multiplier x ATR_14)
Installation
pip install pandas numpy
atr-stop-loss-calculation-script-python.py
import pandas as pd
import numpy as np
def atr_position_sizer(df, capital=100000, risk_pct=0.01, period=14, atr_mult=2.0):
df = df.copy()
tr = pd.concat([
df['High'] - df['Low'],
(df['High'] - df['Close'].shift(1)).abs(),
(df['Low'] - df['Close'].shift(1)).abs()
], axis=1).max(axis=1)
df['ATR'] = tr.ewm(alpha=1/period, adjust=False).mean()
df['Long_SL'] = np.round(df['Close'] - (atr_mult * df['ATR']), 2)
df['Short_SL'] = np.round(df['Close'] + (atr_mult * df['ATR']), 2)
risk_amount = capital * risk_pct
df['Suggested_Qty'] = np.floor(risk_amount / (atr_mult * df['ATR']))
return df
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: What ATR multiplier is ideal for swing trading?
A 2.0x to 2.5x ATR multiplier gives trades enough breathing room outside normal daily noise.