alpacahq / Momentum-Trading-Example

An example algorithm for a momentum-based day trading strategy.
642 stars 218 forks source link

Calculating shares_to_buy within handle_second_bar() #11

Open DanOKeefe opened 4 years ago

DanOKeefe commented 4 years ago

When calculating the number of shares to buy, I think the formula you use should be

shares_to_buy = portfolio_value * risk // data.close

instead of

https://github.com/alpacahq/Momentum-Trading-Example/blob/be4352838eebdd2d124eedd341e31fbae8774f3d/algo.py#L253-L255

I think that the number of shares you buy should be independent of the difference between the current stock price and your stop loss.

For example:

portfolio_value = 200000
risk = 0.001
close = 100
stop_price = 95
# new calculation of shares_to_buy
shares_to_buy = portfolio_value * risk // close

print('portfolio_value * risk: ' + str(portfolio_value*risk))
print('share price: ' + str(close))
print('shares_to_buy: ' + str(shares_to_buy))
print('shares_to_buy * close: ' + str(shares_to_buy*close))
print('shares_to_buy*close/portfolio_value: ' + str(shares_to_buy*close/portfolio_value))

portfolio_value risk: 200.0 share price: 100 shares_to_buy: 2.0 shares_to_buy close: 200.0 shares_to_buy*close/portfolio_value: 0.001

# original calculation of shares_to_buy
shares_to_buy = portfolio_value * risk // (close-stop_price)

print('portfolio_value * risk: ' + str(portfolio_value*risk))
print('share price: ' + str(close))
print('shares_to_buy: ' + str(shares_to_buy))
print('shares_to_buy * close: ' + str(shares_to_buy*close))

# exceeds risk threshold
print('shares_to_buy*close/portfolio_value: ' + str(shares_to_buy*close/portfolio_value))

portfolio_value risk: 200.0 share price: 100 shares_to_buy: 40.0 shares_to_buy close: 4000.0 shares_to_buy*close/portfolio_value: 0.02

The above order would make up 2% of your portfolio, higher than the 0.1% of your portfolio that you said you would allocate to any one position

DanOKeefe commented 4 years ago

The formula, as is, is correct if you're defining risk to be the proportion of the portfolio at risk cannot be greater than 0.001.

But the comment when defining risk says:

# How much of our portfolio to allocate to any one position
risk = 0.001

So I think either the comment or the code is incorrect

sylvanosullivan commented 4 years ago

I think it makes sense to include the stop loss in this equation while keeping that same risk level because you only stand to lose the difference between the buy price and the stop-loss. So if you buy 40 shares at $100 a piece, that's 2% of your respectable $200k portfolio. However, if your stop-loss is $95, you only stand to lose $5 on each share, or $200 total - which would be .001 of your portfolio. I assume that's how risk is calculated here.