本文整理汇总了Python中zipline.api.record函数的典型用法代码示例。如果您正苦于以下问题:Python record函数的具体用法?Python record怎么用?Python record使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了record函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: 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])
示例2: handle_data
def handle_data(context, data):
short_ema = context.short_ema_trans.handle_data(data)
long_ema = context.long_ema_trans.handle_data(data)
if short_ema is None or long_ema is None:
return
buy = False
sell = False
if (short_ema > long_ema).all() and not context.invested:
order(context.asset, 100)
context.invested = True
buy = True
elif (short_ema < long_ema).all() and context.invested:
order(context.asset, -100)
context.invested = False
sell = True
record(
AAPL=data[context.asset].price,
short_ema=short_ema[context.asset],
long_ema=long_ema[context.asset],
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: rebalance
def rebalance(context, data):
# Pipeline data will be a dataframe with boolean columns named 'longs' and
# 'shorts'.
pipeline_data = context.pipeline_data
all_assets = pipeline_data.index
longs = all_assets[pipeline_data.longs]
shorts = all_assets[pipeline_data.shorts]
record(universe_size=len(all_assets))
# Build a 2x-leveraged, equal-weight, long-short portfolio.
one_third = 1.0 / 3.0
for asset in longs:
order_target_percent(asset, one_third)
for asset in shorts:
order_target_percent(asset, -one_third)
# Remove any assets that should no longer be in our portfolio.
portfolio_assets = longs | shorts
positions = context.portfolio.positions
for asset in viewkeys(positions) - set(portfolio_assets):
# This will fail if the asset was removed from our portfolio because it
# was delisted.
if data.can_trade(asset):
order_target_percent(asset, 0)
示例5: 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)
示例6: 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])
示例7: 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)
示例8: handle_data
def handle_data(context, data):
#assert context.portfolio.cash > 0.0, "ERROR: negative context.portfolio.cash"
#assert len(context.raw_data) == context.training_data_length; "ERROR: "
# data stored as (open, high, low, close, volume, price)
feed_data = ([
data[context.security].open,
data[context.security].high,
data[context.security].low,
data[context.security].close
#data[context.security].volume,
#data[context.security].close,
])
#keep track of history.
context.raw_data.pop(0)
context.raw_data.append(feed_data)
context.normalized_data = Manager.preprocessData(context.raw_data)[:-2]
prediction = context.strategy.predict(context.normalized_data)[-1]
print "Value: $%.2f Cash: $%.2f Predict: %.5f" % (context.portfolio.portfolio_value, context.portfolio.cash, prediction[0])
# Do nothing if there are open orders:
if has_orders(context, data):
print('has open orders - doing nothing!')
# Put entire position in
elif prediction > 0.5:
order_target_percent(context.security, .95)
# Take entire position out
else:
order_target_percent(context.security, 0)
#order_target_percent(context.security, -.99)
record(BENCH=data[context.security].price)
record(SPY=data[context.benchmark].price)
示例9: 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)
示例10: 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)
示例11: handle_data
def handle_data(context, data):
print "================================="
print "New iteration"
print data
order(symbol('AAPL'), 10)
record(AAPL=data[symbol('AAPL')].price)
示例12: handle_data
def handle_data(context, data):
context.i += 1
stock_name = context.panel.axes[0][0]
if context.i == 60:
order(symbol(stock_name), 10)
if context.i == 150:
order(symbol(stock_name), -10)
record(Prices=data[symbol(stock_name)].price)
示例13: handle_data
def handle_data(context, data):
if context.prev_day_close_price:
percent_change = (data[0]["close"] - context.prev_day_close_price) * 100 / context.prev_day_close_price
open_close_percent_change = (data[0]["open"] - context.prev_day_close_price) * 100 / context.prev_day_close_price
if percent_change < 0:
context.pattern.append(-1)
else:
context.pattern.append(1)
pattern_length = len(context.buy_pattern_to_match)
if context.pattern[-pattern_length:] == context.buy_pattern_to_match:
order(context.symbol, 10, limit_price = data[0]["open"])
if context.take_profit_target and (data[0]["open"] + context.take_profit_target) <= data[0]["high"]:
target_price = data[0]["open"] + context.take_profit_target
order(context.symbol, -10, limit_price = target_price)
pnl_cents = target_price - data[0]["open"]
context.cents = context.cents + pnl_cents
print "{0}, {1}, pnl: {2}, accum.pnl: {3}".format(data[0]["dt"], "BUY", pnl_cents, context.cents)
else:
order(context.symbol, -10, limit_price = data[0]["close"])
pnl_cents = data[0]["close"] - data[0]["open"]
context.cents = context.cents + pnl_cents
print "{0}, {1}, pnl: {2}, accum.pnl: {3}".format(data[0]["dt"], "BUY", pnl_cents, context.cents)
pattern_length = len(context.sell_pattern_to_match)
if context.pattern[-pattern_length:] == context.sell_pattern_to_match:
order(context.symbol, -10, limit_price = data[0]["open"])
if context.take_profit_target and (data[0]["open"] - context.take_profit_target) >= data[0]["low"]:
target_price = data[0]["open"] - context.take_profit_target
order(context.symbol, 10, limit_price = target_price)
pnl_cents = data[0]["open"] - target_price
context.cents = context.cents + pnl_cents
print "{0}, {1}, pnl: {2}, accum.pnl: {3}".format(data[0]["dt"], "SELL", pnl_cents, context.cents)
else:
order(context.symbol, 10, limit_price = data[0]["close"])
pnl_cents = data[0]["open"] - data[0]["close"]
context.cents = context.cents + pnl_cents
print "{0}, {1}, pnl: {2}, accum.pnl: {3}".format(data[0]["dt"], "SELL", pnl_cents, context.cents)
#pattern_length = len(context.follow_uptrend_pattern_to_match)
#if context.pattern[-pattern_length:] == context.follow_uptrend_pattern_to_match:
#
# order(context.symbol, 10, limit_price = data[0]["open"])
# order(context.symbol, -10, limit_price = data[0]["close"])
#
# context.cents = context.cents + (data[0]["close"] - data[0]["open"])
# print "{0}, {1}, pnl: {2}, accum.pnl: {3}".format(data[0]["dt"], "FLW UPTREND BUY", data[0]["close"] - data[0]["open"], context.cents)
context.prev_day_close_price = data[0]["close"]
record(SMBL = data[0]["close"])
示例14: handle_data_api
def handle_data_api(context, data):
if context.incr == 0:
assert 0 not in context.portfolio.positions
else:
assert context.portfolio.positions[0]["amount"] == context.incr, "Orders not filled immediately."
assert context.portfolio.positions[0]["last_sale_price"] == data[0].price, "Orders not filled at current price."
context.incr += 1
order(0, 1)
record(incr=context.incr)
示例15: 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