edtechre / pybroker

Algorithmic Trading in Python with Machine Learning
https://www.pybroker.com
Other
2.09k stars 262 forks source link

Access equity amount during backtest for sizing #141

Closed markxbaker closed 2 months ago

markxbaker commented 2 months ago

Hi Ed, is it possible to access equity amount during backtest? For example if I want to allocate 1% per trade and calculate number of shares based on stop, but then also add a max risk per trade also, so no more than say 5% in total shares to help manage risk?

markxbaker commented 2 months ago

Sorry ignore - this seems to work ok! Might be helpful for others

def exec_fn(ctx: ExecContext): sma_short = ctx.indicator('sma_short') sma_long = ctx.indicator('sma_long') atr_10d = ctx.indicator('ATR_10')

# Calculate stop loss distance (ATR-based)
ATR = 3.5 * atr_10d[-1]

# Calculate the dollar risk (2% of account balance)

# Assume entry price is the current close price, and stop-loss is some price below the entry
entry_price = ctx.close[-1]  # Current price
stop_loss_price = entry_price - ATR  # Using ATR as the stop-loss distance for example
dollar_risk_per_share = entry_price - stop_loss_price  # Risk per share based on stop-loss

# Calculate the dollar risk (e.g., 2% of account balance)
account_value = float(ctx.cash) + (float(ctx.long_pos().shares) * entry_price if ctx.long_pos() else 0)
risk_per_trade = account_value * 0.02  # Risk 2% of account

# Calculate position size based on dollar risk per share
target_shares = risk_per_trade / dollar_risk_per_share

# Debug prints with separators
print("////////////////////////////////")
print(f"Account Cash: {ctx.cash}")
print(f"Total Account Value: {account_value}")
print(f"Entry Price: {entry_price}")
print(f"Stop Loss Price: {stop_loss_price}")
print(f"ATR: {ATR}")
print(f"Risk per Trade: {risk_per_trade}")
print(f"Dollar Risk per Share: {dollar_risk_per_share}")
print(f"Target Shares: {target_shares}")

long_pos = ctx.long_pos()
if not long_pos:
    if sma_short[-1] > sma_long[-1]:
        ctx.buy_shares = target_shares
        ctx.stop_loss = ATR
        ctx.hold_bars = 8
        ctx.score = ctx.volume[-1]