本文整理汇总了Python中zipline.api.order_target函数的典型用法代码示例。如果您正苦于以下问题:Python order_target函数的具体用法?Python order_target怎么用?Python order_target使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了order_target函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle_data_magc
def handle_data_magc(context, data):
context.i += 1
if context.i < 60:
return
ma20 = history(20, '1d', 'price').mean()
ma60 = history(60, '1d', 'price').mean()
buy = False
sell = False
sym = symbol(code)
count = int(100000 / data[sym].price)
if context.investment == False:
if ma20[sym] > ma60[sym] :
order_target(sym, count)
context.investment = True
context.buy_price = data[sym].price
buy = True
else:
if (data[sym].price > context.buy_price + (context.buy_price * sell_point)):
order_target(sym, -count)
context.investment = False
sell = True
record(code=data[sym].price, ma20=ma20[sym], ma60=ma60[sym], buy=buy, sell=sell)
示例2: handle_data_macd
def handle_data_macd(context, data):
context.i += 1
if context.i < 60:
return
buy = False
sell = False
sym = symbol(code)
count = int(100000 / data[sym].price)
prices = history(40, '1d', 'price')
macd = prices.apply(MACD, fastperiod=12, slowperiod=26, signalperiod=9)
if context.investment == False:
if macd[sym] > 0 and context.position == -1:
order_target(sym, count)
context.investment = True
context.buy_price = data[sym].price
buy = True
context.position = 1
else:
if (data[sym].price > context.buy_price + (context.buy_price * sell_point)):
order_target(sym, -count)
context.investment = False
sell = True
if macd[sym] < 0 :
context.position = -1
if macd[sym] > 0 :
context.position = 1
record(code=data[sym].price, macd=macd[sym], buy=buy, sell=sell)
示例3: handle_data
def handle_data(context, data):
# Skip first 300 days to get full windows
context.i += 1
if context.i < 300:
return
# Compute averages
# history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = history(100, '1d', 'price').mean()
long_mavg = history(300, '1d', 'price').mean()
# price_history = data.history(assets=symbol('TEST'), fields="price", bar_count=5, frequency="1d")
# Trading logic
if short_mavg[0] > long_mavg[0]:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(symbol('AAPL'), 100)
elif short_mavg[0] < long_mavg[0]:
order_target(symbol('AAPL'), 0)
# Save values for later inspection
record(AAPL=data[symbol('AAPL')].price,
short_mavg=short_mavg[0],
long_mavg=long_mavg[0])
示例4: handle_data
def handle_data(context, data):
#trading algorithm (executed on every event)
#skip first 300 days to get full windows
context.i += 1
if context.i < 300:
return
#compute short and long moving averages:
short_mavg = history(100, '1d', 'price').mean()
long_mavg = history(300, '1d', 'price').mean()
buy = False
sell = False
#trading logic
if (short_mavg[0] > long_mavg[0]) and not context.invested:
buy = True
context.invested = True
order_target(symbol('AAPL'), 100)
elif (short_mavg[0] < long_mavg[0]) and context.invested:
sell = True
context.invested = False
order_target(symbol('AAPL'), -100)
#save values for plotting
record(AAPL = data[symbol('AAPL')].price,
short_mavg = short_mavg[0],
long_mavg = long_mavg[0],
buy=buy,
sell=sell)
示例5: handle_data
def handle_data(context, data):
# Skip first 300 days to get full windows
context.i += 1
dp = context.history_container.digest_panels
for k in dp.keys():
df = dp[k].buffer['price']
a = df.dropna()
print('No.',context.i,':Len.',len(a))
print('Contents:')
print(a)
print(context.history_container.buffer_panel.buffer['price'])
if context.i < 40:
return
# Compute averages
# history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = history(20, '1d', 'price').mean()
long_mavg = history(40, '1d', 'price').mean()
# Trading logic
if short_mavg[context.sym] > long_mavg[context.sym]:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(context.sym, 100)
elif short_mavg[context.sym] < long_mavg[context.sym]:
order_target(context.sym, 0)
# Save values for later inspection
record(AAPL=data[context.sym].price,
short_mavg=short_mavg[context.sym],
long_mavg=long_mavg[context.sym])
示例6: handle_data
def handle_data(context, data):
# Skip first 300 days to get full windows
context.i += 1
if context.i < 10:
return
# Compute averages
# history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = history(5, '1d', 'price').mean()
long_mavg = history(10, '1d', 'price').mean()
for sym in data:
# sym = data.keys()[0]
# sym = data.keys()[0]
# Trading logic
if short_mavg[sym] > long_mavg[sym] and not context.invested:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(sym, 5000)
context.invested = True
elif short_mavg[sym] < long_mavg[sym] and context.invested:
order_target(sym, 0)
context.invested = False
示例7: handle_data
def handle_data(context, data):
print context.portfolio.portfolio_value
# Skip first 300 days to get full windows
context.i += 1
if context.i < 300:
return
# Compute averages
# history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = history(100, '1d', 'price').mean()
long_mavg = history(300, '1d', 'price').mean()
sym = symbol('AAPL')
# Trading logic
if short_mavg[sym] > long_mavg[sym]:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(sym, 100)
elif short_mavg[sym] < long_mavg[sym]:
order_target(sym, 0)
# Save values for later inspection
record(AAPL=data[sym].price,
short_mavg=short_mavg[sym],
long_mavg=long_mavg[sym])
示例8: handle_data_bband
def handle_data_bband(context, data):
context.i += 1
if context.i < 20:
return
buy = False
sell = False
sym = symbol(code)
count = int(100000 / data[sym].price)
prices = history(20, '1d', 'price')
upper, middle, lower = ta.BBANDS(
prices[sym].values,
timeperiod=20,
nbdevup=2,
nbdevdn=2,
matype=0)
if context.investment == False:
if lower[-1] > data[sym].price:
order_target(sym, count)
context.investment = True
context.buy_price = data[sym].price
buy = True
context.position = 1
else:
if (data[sym].price > context.buy_price + (context.buy_price * sell_point)):
order_target(sym, -count)
context.investment = False
sell = True
record(code=data[sym].price, upper=upper[-1], lower=lower[-1], makeBacktestingDataFrame=middle[-1], buy=buy, sell=sell)
示例9: handle_data
def handle_data(context, data):
# Skip first 300 days to get full windows
date = get_datetime()
context.i += 1
if context.i < 10:
return
prices = history(25, '1d', 'price')
for sym in data:
upper, middle, lower = talib.BBANDS(
np.array(prices[sym]),
timeperiod=20,
nbdevup=2,
nbdevdn=2,
matype=0
)
potential_buy = []
buy = False
sell = False
if data[sym].price > upper[-1] and context.portfolio.positions[sym].amount == 0:
# log.info('buy')
# log.info(get_datetime())
# log.info(data[sym].price)
# log.info(upper[-1])
order_target_percent(sym, 1.0, limit_price=data[sym].price)
elif data[sym].price < middle[-1] and context.portfolio.positions[sym].amount > 0:
# log.info('sell')
# log.info(get_datetime())
# log.info(data[sym].price)
# log.info(middle[-1])
order_target(sym, 0, limit_price=data[sym].price)
示例10: handle_data
def handle_data(self, data):
from zipline.api import (
order_percent,
order_target,
order_target_percent,
order_target_value,
order_value,
)
for style in [MarketOrder(), LimitOrder(10),
StopOrder(10), StopLimitOrder(10, 10)]:
with assert_raises(UnsupportedOrderParameters):
order(self.asset, 10, limit_price=10, style=style)
with assert_raises(UnsupportedOrderParameters):
order(self.asset, 10, stop_price=10, style=style)
with assert_raises(UnsupportedOrderParameters):
order_value(self.asset, 300, limit_price=10, style=style)
with assert_raises(UnsupportedOrderParameters):
order_value(self.asset, 300, stop_price=10, style=style)
with assert_raises(UnsupportedOrderParameters):
order_percent(self.asset, .1, limit_price=10, style=style)
with assert_raises(UnsupportedOrderParameters):
order_percent(self.asset, .1, stop_price=10, style=style)
with assert_raises(UnsupportedOrderParameters):
order_target(self.asset, 100, limit_price=10, style=style)
with assert_raises(UnsupportedOrderParameters):
order_target(self.asset, 100, stop_price=10, style=style)
with assert_raises(UnsupportedOrderParameters):
order_target_value(self.asset, 100,
limit_price=10,
style=style)
with assert_raises(UnsupportedOrderParameters):
order_target_value(self.asset, 100,
stop_price=10,
style=style)
with assert_raises(UnsupportedOrderParameters):
order_target_percent(self.asset, .2,
limit_price=10,
style=style)
with assert_raises(UnsupportedOrderParameters):
order_target_percent(self.asset, .2,
stop_price=10,
style=style)
示例11: handle_data
def handle_data(context, data):
context.cur_time += 1
month = get_datetime().date().month
is_january = (month == 1)
new_prices = np.array([data[symbol(symbol_name)].price for symbol_name in context.symbols], dtype='float32')
record(Prices=new_prices)
new_prices = new_prices.reshape((context.N_STOCKS, 1))
# print context.returns_history.shape
# print new_prices.shape
# print context.previous_prices.shape
context.returns_history = np.concatenate([context.returns_history, new_prices / context.previous_prices], axis=1)
context.previous_prices = new_prices
if context.month != month:
# Trading in the beginning of month
context.month_sizes.append(context.day_of_month)
context.day_of_month = 1
context.count_month += 1
context.month_sizes.append(context.day_of_month)
context.day_of_month = 1
if context.count_month > N_MONTHS:
# Deleting too old returns
if context.count_month > N_MONTHS + 1:
context.returns_history = np.delete(context.returns_history, range(context.month_sizes[-14]), axis=1)
model_input = preprocess_data_for_model(context.returns_history, context.month_sizes[-13:], context.scaler)
is_january_column = np.array([is_january] * context.N_STOCKS).reshape((context.N_STOCKS, 1))
model_input = np.concatenate([is_january_column, model_input], axis=1)
# print 'Input shape', model_input.shape
predicted_proba = context.model.predict_proba(model_input)
# print predicted_proba
'''
half_trade = len(context.symbols) * 1 / 10
args_sorted = np.argsort(predicted_proba[:, 0])
buy_args = args_sorted[:half_trade]
sell_args = args_sorted[-half_trade:]
for arg in buy_args:
order_target(symbol(context.symbols[arg]), 1)
for arg in sell_args:
order_target(symbol(context.symbols[arg]), -1)
'''
for i in range(context.N_STOCKS):
if predicted_proba[i, 0] > 0.5:
order_target(symbol(context.symbols[i]), 1)
else:
order_target(symbol(context.symbols[i]), -1)
else:
context.day_of_month += 1
context.month = month
示例12: handle_terminations
def handle_terminations(context):
idx_to_remove = []
for idx, position in enumerate(context.to_terminate):
ticker = position[0]
countdown = position[1] - 1
if countdown == 0:
order_target(ticker, 0)
idx_to_remove.append(idx)
else:
context.to_terminate[idx] = (ticker, countdown)
context.to_terminate = [
data for idx, data in enumerate(context.to_terminate) if idx not in idx_to_remove
]
示例13: handle_data
def handle_data(context, data):
context.i += 1
if context.i < 20:
return
ma5 = data.history(context.sym, 'price', 5, '1d').mean()
ma20 = data.history(context.sym, 'price', 20, '1d').mean()
if ma5 > ma20:
order_target(context.sym, 1)
else:
order_target(context.sym, -1)
record(AAPL=data.current(context.sym, "price"), ma5=ma5, ma20=ma20)
示例14: handle_data
def handle_data(context, data):
average_price = data[context.security].mavg(5)
current_price = data[context.security].price
cash = context.portfolio.cash
if current_price > 1.01*average_price and cash > current_price:
number_of_shares = int(cash/current_price)
order(context.security, +number_of_shares)
log.info("Buying %s" % (context.security.symbol))
elif current_price < average_price:
order_target(context.security, 0)
log.info("Selling %s" % (context.security.symbol))
record(stock_price=data[context.security].price)
示例15: fire_sale
def fire_sale(context, data):
# Sell everything in the portfolio, at market price
show_spacer = False
for stock in data:
if context.portfolio.positions[stock].amount != 0:
order_target(stock, 0.0)
value_of_open_orders(context, data)
availibleCash = context.portfolio.cash-context.cashCommitedToBuy-context.cashCommitedToSell
print(" * Exit {0:,d} of {1:s} at ${2:,.2f} for ${3:,.2f} / ${4:,.2f} @ {5:s}"\
.format(int(context.portfolio.positions[stock].amount),
stock,
data[stock]['price'],
data[stock]['price']*context.portfolio.positions[stock].amount,
availibleCash,
context.exchange_time))
show_spacer = True
if show_spacer:
print('') #This just gives us a space to make reading the 'daily' log sections more easily