order_target_percent ordering too much?

Hi,

I'm struggling to figure out what I'm missing with the order_target_percent function. When I run the following code, it seems to work correctly, oscillating between investing 100% in the ETF and 100% in cash (allowing for small amounts of extra cash because of fractional share issues etc.).

However, when I run the code with the two securities below, it sometimes "blows up," ordering stocks well in excess of 100% of the portfolio value and generating losses of almost 2000%. I had thought that the function would basically allocate a certain % of the total portfolio value between a list of securities, so I could (in theory) say order_target_percent(sid1, 0.5) on one sid and order_target_percent(sid2, 0.5) on the other and it would split the total value 50/50 between the two stocks, or alternatively say order_target_percent(sid1, 1) to put all money into that stock, or order_target_percent(sid1, 0) to sell off all interest in sid1.

Anyone know what I'm missing?

Thanks,

Andy

import talib

# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
context.stocks = [ sid(8554), sid(27102) ]
context.longs = { }

# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
prices = history(50, '1d', 'price') # 50-day lookback window
for stock in context.stocks:
if context.longs.get(stock) is None:
context.longs[stock] = 0.0
price = data[stock].price
upper, middle, lower = talib.BBANDS(prices[stock], timeperiod=50, nbdevup=2, nbdevdn=2, matype=0)
upper, middle, lower = upper[-1], middle[-1], lower[-1] # latest b-band value
mavg200 = data[stock].mavg(200)
if price <= lower and price <= mavg200:
context.longs[stock] = 1.0
if price >= upper and price >= mavg200:
context.longs[stock] = 0.0

total_longs = sum(context.longs.values())
if total_longs > 0:
log.debug("total longs is {tl}".format(tl=total_longs))
record(cash=context.portfolio.cash)
for stock in context.stocks:
if total_longs <= 0:
order_target_percent(stock, 0.0)
else:
order_target_percent(stock, context.longs[stock] / total_longs)
log.debug("adjusting {s} to {p} percent".format(s=stock, p=100.0*context.longs[stock] / total_longs))

3 responses

Hi Andy,

You ran into one of the current rough edges - the ordering method doesn't check for open orders before calculating the number of shares to buy.

A large order may take several bars to fill, according to the slippage model. While this order is being filled, handle_data is getting called every minute and your order_target_percent is adjusting its values, creating a queue of open orders. This may lead to large swings of order amounts.

In your code on line 15, I added a check for open orders. Hope this helps!

Alisa

73
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
 Returns 1 Month 3 Month 6 Month 12 Month
 Alpha 1 Month 3 Month 6 Month 12 Month
 Beta 1 Month 3 Month 6 Month 12 Month
 Sharpe 1 Month 3 Month 6 Month 12 Month
 Sortino 1 Month 3 Month 6 Month 12 Month
 Volatility 1 Month 3 Month 6 Month 12 Month
 Max Drawdown 1 Month 3 Month 6 Month 12 Month
import talib

# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
context.stocks = [ sid(8554), sid(27102) ]
context.longs = { }

# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
prices = history(50, '1d', 'price') # 50-day lookback window
for stock in context.stocks:

# Do nothing if there are open orders:
if has_orders(context):
print('has open orders - doing nothing!')
return

if context.longs.get(stock) is None:
context.longs[stock] = 0.0
price = data[stock].price
upper, middle, lower = talib.BBANDS(prices[stock], timeperiod=50, nbdevup=2, nbdevdn=2, matype=0)
upper, middle, lower = upper[-1], middle[-1], lower[-1] # latest b-band value
mavg200 = data[stock].mavg(200)
if price <= lower and price <= mavg200:
context.longs[stock] = 1.0
if price >= upper and price >= mavg200:
context.longs[stock] = 0.0

total_longs = sum(context.longs.values())
if total_longs > 0:
log.debug("total longs is {tl}".format(tl=total_longs))
record(cash=context.portfolio.cash)
for stock in context.stocks:
if total_longs <= 0:
order_target_percent(stock, 0.0)
else:
order_target_percent(stock, context.longs[stock] / total_longs)
log.debug("adjusting {s} to {p} percent".format(s=stock, p=100.0*context.longs[stock] / total_longs))

def has_orders(context):
# Return true if there are pending orders.
has_orders = False
for sec in context.stocks:
orders = get_open_orders(sec)
if orders:
for oo in orders:
message = 'Open order for {amount} shares in {stock}'
message = message.format(amount=oo.amount, stock=sec)
log.info(message)

has_orders = True
return has_orders            
There was a runtime error.
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Thanks Alisa!

Hi,

Occasionally I find this post. I would like to say, could I use the following code at the very beginning to avoid overbuying?