def handle_data(context, data): if context.traded: return print data order(context.stock, 10000) order(context.stock, - 10000, style=LimitOrder(data[context.stock]['close'] * 1.1)) context.traded = True
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, )
def func0(context, data): order(symbol('AAPL UW EQUITY'), 10) print 'price: ', data[symbol('AAPL UW EQUITY')].price # order(symbol('AAPL UW EQUITY'), -10) print context.portfolio.cash print context.get_datetime().date() print "==========================="
def handle_data(context, data): # Skip first 300 days to get full windows context.i += 1 if context.i < context.N: return # Compute averages # history() has to be called with the same params # from above and returns a pandas dataframe. c = history(context.N, '1d', 'close') o = history(context.N, '1d', 'open') h = history(context.N, '1d', 'high') l = history(context.N, '1d', 'low') for sym in data: # Trading logic hh = h[sym].ix[:-1].max() hc = c[sym].ix[:-1].max() lc = c[sym].ix[:-1].min() ll = l[sym].ix[:-1].min() r = max(hh-lc, hc-ll) upper = data[sym].open + context.k * r lower = data[sym].open - context.k * r 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(sym, 10000, limit_price=data[sym].price) context.invested = True elif short_mavg[sym] < long_mavg[sym] and context.invested: order(sym, -10000, limit_price=data[sym].price) context.invested = False
def handle_data(context, data): # context.i+=1 # if context.i<=5: # return # 循环每只股票 closeprice= history(5,'1d','close') for security in context.stocks: vwap=(closeprice[symbol(security)][-2]+closeprice[symbol(security)][-3]+closeprice[symbol(security)][-4])/3 price = closeprice[symbol(security)][-2] print get_datetime(),security,vwap,price # # 如果上一时间点价格小于三天平均价*0.995,并且持有该股票,卖出 if price < vwap * 0.995: # 下入卖出单 order(symbol(security),-300) print get_datetime(),("Selling %s" % (security)) # 记录这次卖出 #log.info("Selling %s" % (security)) # 如果上一时间点价格大于三天平均价*1.005,并且有现金余额,买入 elif price > vwap * 1.005: # 下入买入单 order(symbol(security),300) # 记录这次买入 print get_datetime(),("Buying %s" % (security))
def handle_data(context, data): curr_price = data[symbol('USCRWTIC INDEX')].price curr_positions = context.portfolio.positions[symbol('USCRWTIC INDEX')].amount cash = context.portfolio.cash print cash, curr_positions, curr_price # context.counter += 1 # if context.counter > 500: # print "Cancelou" # cancel_order(context.order_id) # else: # print 'ola' random_order = np.random.rand() if random_order > 0.5 and curr_positions == 0: order(symbol('USCRWTIC INDEX'), 100) elif random_order < 0.5 and curr_positions != 0: order(symbol('USCRWTIC INDEX'), -100)
def handle_data(context, data): curr_price = data[symbol('USCRWTIC INDEX')].price curr_date = data[symbol('USCRWTIC INDEX')].datetime curr_positions = context.portfolio.positions[symbol('USCRWTIC INDEX')].amount cash = context.portfolio.cash local_historical_data = context.oil_historical_data local_historical_data = local_historical_data['USCRWTIC INDEX'][['price']] df_to_forecast = local_historical_data[local_historical_data.index <= curr_date] result = forecast_ts.run(df = df_to_forecast, ts_list = None, freq = 'B', forecast_horizon = 6, start_date = curr_date.strftime('%Y-%m-%d'), method = context.method, processing_params = context.processing_params, expert_params = context.expert_params) estimated_return = result.iloc[-1].values[-1] # estimated_return = np.random.rand()-1 print cash, curr_positions, curr_price, curr_date, estimated_return if estimated_return < 0 and curr_positions == 0: order(symbol('USCRWTIC INDEX'), -100) elif estimated_return > 0 and curr_positions != 0: order(symbol('USCRWTIC INDEX'), 100)
def handle_data(context, data): hist = data.history(context.smb, bar_count=5, frequency='1m', fields='open') if not context.ordered: print("ordering") order(context.smb, 100, limit_price=5.00) context.ordered = True cancle_open_orders(context,data) print(hist)
def handle_data(context, data): print "=================================" print "New iteration" print data order(symbol('AAPL'), 10) record(AAPL=data[symbol('AAPL')].price)
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)
def _handle_data(self, context, data): for movimiento in context.movimientos: clave_emisora = movimiento.emisora fecha_movimiento = movimiento.fecha fecha = data[symbol(clave_emisora)].dt delta = fecha_movimiento - fecha.replace(tzinfo=None) num_acciones = movimiento.num_acciones if(delta.days == 0): order(symbol(clave_emisora), num_acciones)
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)
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)
def handle_data(context, data): for stock in data: print stock, sid(stock) if not context.has_ordered: for stock in data: print stock order(sid(stock), 100) context.has_ordered = True print "==================="
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.current( sid(0), "price" ), "Orders not filled at current price." context.incr += 1 order(sid(0), 1) record(incr=context.incr)
def handle_data(context, data): context.panel # Here we have access to training data also. # Make solution using the result of learning: if not int(data[symbol('AAPL')].price) % context.result: order(symbol('AAPL'), 10) # Record some values for analysis in 'analyze()'. sids = context.panel.axes[0].values prices = [data[symbol(sid)].price for sid in sids] record(Prices=prices) record(Prediction=3 * data[symbol('AAPL')].price - 2.2 * context.previous) # Record current price to use it in future. context.previous = data[symbol('AAPL')].price
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)
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_date == context.get_datetime() ), "Orders not filled at current datetime." context.incr += 1 order(sid(0), 1) record(incr=context.incr)
def handle_data(context, data): stock_name = context.panel.axes[0][0] def normalize(price): return 1 / (1 + np.exp((context.mean - price) / context.scale)) def unnormalize(prediction): return context.mean - context.scale * (np.log((1 / prediction) - 1)) context.current_day += 1 context.trash_days_counter += 1 current_price = data[symbol(stock_name)].price context.history.push(current_price) current_mean = context.history.get_mean() X = normalize(current_price) X_2 = context.history.get_norm_mean() input_ = np.array([[X, X_2]]).astype(theano.config.floatX).reshape(1, 1, 2) prediction = context.get_output(input_)[0][0] next_day_norm_price = context.history.calc_next_day_norm_price(prediction) unnorm_prediction = unnormalize(prediction) day2_input_ = np.array([[next_day_norm_price, prediction]]) day2_input_ = day2_input_.astype(theano.config.floatX).reshape(1, 1, 2) prediction_2_day = context.get_output(day2_input_)[0][0] day2_norm_price = prediction_2_day * 5 - \ sum(context.history.norm_queue[2:]) - \ next_day_norm_price if context.current_day % 14 == 0: if max(context.history.norm_queue) < next_day_norm_price - 0.08: # print('buy',day2_norm_price, next_day_norm_price, # max(context.history.norm_queue)) order(symbol(stock_name), int(10000 * (next_day_norm_price - max(context.history.norm_queue)))) elif next_day_norm_price + 0.08 < min(context.history.norm_queue): # print('sell', day2_norm_price, next_day_norm_price, # min(context.history.norm_queue)) order(symbol(stock_name), int(10000 * (next_day_norm_price - min(context.history.norm_queue)))) record(normPrediction=prediction) record(normPrices=X_2) record(Prediction=unnorm_prediction) record(Prices=current_mean)
def handle_data(context, data): context.cnt += 1 new_prices = np.array([data[symbol(asset_name)].price for asset_name in context.panel.axes[0]], dtype='float32') # print new_prices if context.check == 0: context.check = 1 context.old_prices = new_prices return price_diffs = new_prices - context.old_prices normed_price_diffs = price_diffs / context.old_prices # print context.portfolio['portfolio_value'] # new_portf = context.action # new_portf = calc_portfolio(normed_price_diffs, context) new_portf = context.pred[context.cnt] for i in np.arange(len(new_portf)): name = symbol(context.panel.axes[0][i]) num = new_portf[i] - context.portf[i] order(name, num * 100) context.portf = new_portf context.old_prices = new_prices
def rebalance_portfolio(context, data, weights): desired_amount = np.zeros(np.shape(weights)) current_amount = np.zeros(np.shape(weights)) prices = np.zeros(np.shape(weights)) if context.init: positions_value = context.portfolio.starting_cash else: #total cash positions_value = context.portfolio.positions_value + context.portfolio.cash for i, stock in enumerate(context.stocks): current_amount[i] = context.portfolio.positions[stock].amount #shares prices[i] = data[stock]['price'] #share price context.prev_weights = weights desired_amount = np.round(weights * positions_value / prices) #shares diff_amount = desired_amount - current_amount #pdb.set_trace() for i, sid in enumerate(context.sids): order(sid, +diff_amount[i])
def handle_data(context, data): global sell_status, buy_status can_trade = data.can_trade(context.smb) current = data.current(symbol('002450'), 'price') print(current) # hist = data.history(symbol('600496'), bar_count=20, frequency='1m', fields='open') # print(hist) print(datetime.datetime.now()) print(context.portfolio) print(context.portfolio.positions) orders = context.get_open_orders() if orders and len(orders) > 0: real_order = six.next(six.itervalues(orders))[0] cancel_order(real_order) if not sell_status: order(symbol('002450'), -200, limit_price=current - 0.01) sell_status = True if not buy_status: buy_price = current - 0.1 if buy_price * 100 <= context.portfolio.cash: order(symbol('002450'), 300, limit_price=buy_price) buy_status = True
def handle_data(context, data): short_ema = context.short_ema_trans.handle_data(data) long_ema = context.long_ema_trans.handle_data(data) # long_array = ta.MA(short_ema.values, timeperiod=20,matype=1) # long_ema = Series(long_array,index=short_ema.index) 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(yygf=data[context.asset].price, short_ema=short_ema[context.asset], long_ema=long_ema[context.asset], buy=buy, sell=sell)
def handle_data(context, data): trailing_window = data.history(context.asset, 'price', 40, '1d') if trailing_window.isnull().values.any(): return short_ema = EMA(trailing_window.values, timeperiod=20) long_ema = EMA(trailing_window.values, timeperiod=40) buy = False sell = False if (short_ema[-1] > long_ema[-1]) and not context.invested: order(context.asset, 100) context.invested = True buy = True elif (short_ema[-1] < long_ema[-1]) and context.invested: order(context.asset, -100) context.invested = False sell = True record(AAPL=data.current(context.asset, "price"), short_ema=short_ema[-1], long_ema=long_ema[-1], buy=buy, sell=sell)
def handle_data(context, data): order(symbol('AAPL'), 10) record(AAPL=data.current(symbol('AAPL'), 'price'))
def handle_data(context, data): while True: order(symbol('AAPL'), 10) record(AAPL=data.current(symbol('AAPL'), 'price')) time.sleep(5)
def handle_date(context, data): order('AAPL', 10) print(context.test)
def handle_data(context, data): order(symbol('AAPL'), 10) record(AAPL=data[symbol('AAPL')].price)
def handle_data(context, data): if not context.has_ordered: for stock in context.symbols: order(symbol('AAPL'), 1000) context.has_ordered = True
def handle_data(context,data): order(symbol('AAPL'),1)
def handle_data(context, data): if not context.has_ordered: for stock in data: order(sid(stock), 100) context.has_ordered = True
def handleData(context, data): stock = symbol('AAPL') order(stock, 10) record(AAPL=data.current(stock, 'price'))
def handle_data(contex, data): order(symbol("PETR4"), 10) record(PETR4=data.current(symbol("PETR4"), "price"))
def handle_data(context, dat): order(symbol("078930.KS"), 1)
def handle_data(context, data): for symb in map(symbol, context.panel.axes[0].values): if context.i == 0: order(symb, -10) context.i = 1
def handle_data(context, data): if not context.has_ordered: for stock in context.stocks: order(symbol(stock), 100) context.has_ordered = True
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"])
def handle_data(context, data): sym = symbol('sh600036') order(sym, 100)
def handle_data(context, data): order(context.asset, 10) record(AAPL=data.current(context.asset, 'price'))
def handle_data(context, data): order(context.asset, 10) record(AAPL=data.current(context.asset, "price"))
def handle_data(context, data): asset_value = context.portfolio.cash for key in list(context.portfolio.positions): asset_value += context.portfolio.positions[key].amount * data.current(key, 'price'); for algo in algo_config: print("ALGO: " + str(algo)) should_act = False # CONDITION COMMAND CENTER logic = algo['condition']['logic'] for i in range(0, len(logic), 2): conditional_truth = test_conditional(logic[i], context, data) if len(logic) - 1 > i: if logic[i + 1] == 'or': if conditional_truth: should_act = True break else: continue elif logic[i + 1] == 'and': if conditional_truth: continue else: should_act = False break else: should_act = conditional_truth break # ACTION COMMAND CENTER if should_act: ticker = algo['action']['ticker'] ticker_symbol = symbol(ticker) target_change = algo['action']['amount'] unit = algo['action']['amount_unit'] # current_share_count current_amount = context.portfolio.positions[ticker_symbol].amount price = data.current(ticker_symbol, 'price') long = algo['action']['position'] == 'long' if target_change > 0: if long: if current_amount < 0: # if currently shorting, get rid of short shares order(ticker_symbol, abs(current_amount)) asset_value += abs(current_amount) * price else: if current_amount > 0: # if currently longing, sell long shares order(-current_amount) asset_value += current_amount * price if asset_value > 0: if unit == 'dollars': val = target_change / price if target_change < asset_value else asset_value / price elif unit == 'shares': val = target_change if target_change * price < asset_value else asset_value / price elif unit == 'percent_assets': val = target_change * asset_value / price if target_change < 1 else asset_value / price elif unit == 'percent_ownership': val = abs(current_amount) * target_change if abs(current_amount) * target_change * price < asset_value else asset_value / price order(ticker_symbol, val if long else -val) asset_value -= val * price else: if (long and current_amount > 0) or (not long and current_amount < 0): if unit == 'dollars': val = target_change / price if abs(target_change) / price < abs(current_amount) else -abs(current_amount) elif unit == 'shares': val = target_change if abs(target_change) < abs(current_amount) else -abs(current_amount) elif unit == 'percent_assets': val = 0 if asset_value > 0: val = target_change * asset_value / price if target_change > -1 and asset_value * abs(target_change) < abs(current_amount) * price else -abs(current_amount) elif unit == 'percent_ownership': val = abs(current_amount) * target_change if target_change > -1 else -abs(current_amount) order(ticker_symbol, val if long else -val) asset_value -= val * price