def handle_data(context, data): trailing_window = data.history(context.asset, 'price', 40, '1d') if trailing_window.isnull().values.any(): return short_ema = data.history(context.asset, 'price', bar_count=20, frequency="1d").mean() long_ema = data.history(context.asset, 'price', bar_count=40, frequency="1d").mean() # 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 rebalance(context, data): log.info("rebalance) " + str(normalize_date(get_datetime()))) # Pipeline data will be a dataframe with boolean columns named 'longs' and # 'shorts'. pipeline_data = context.pipeline_data.dropna() log.info(pipeline_data.head()) 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)
def rebalance(context, data): history = data.history(assets=context.asset, fields=['close'], bar_count=context.tema_window * 4, frequency='1d') date = history.index.values[-1] close = history['close'].values tema = ta.TEMA(close, timeperiod=context.tema_window) current_price = data[context.asset].price record(price=current_price) buy_signal_triggered = False sell_signal_triggered = False if current_price > tema[-1]: buy_signal_triggered = True elif current_price < tema[-1]: sell_signal_triggered = True current_position = context.portfolio.positions[context.asset].amount if buy_signal_triggered and current_position == 0: print(str(date) + '==>Buy') order_target_percent(context.asset, 1.0) elif sell_signal_triggered and current_position > 0: print(str(date) + '==>Sell') order_target_percent(context.asset, 0.0) else: print("No trading")
def rebalance(context, data): history = data.history(assets=context.asset, fields=['open', 'high', 'low', 'close'], bar_count=context.cci_window + 1, frequency='1d') date = history.index.values[-1] high = history['high'].values low = history['low'].values close = history['close'].values # 计算CCI指标 cci = ta.CCI(high, low, close, timeperiod=context.cci_window) current_price = data[context.asset].price record(price=current_price) buy_signal_triggered = False sell_signal_triggered = False if cci[-1] > -100 >= cci[-2]: buy_signal_triggered = True elif cci[-1] < 100 <= cci[-2]: sell_signal_triggered = True current_position = context.portfolio.positions[context.asset].amount if buy_signal_triggered and current_position == 0: print(str(date) + '==>Buy') order_target_percent(context.asset, 0.5) elif sell_signal_triggered and current_position > 0: print(str(date) + '==>Sell') order_target_percent(context.asset, 0.0) else: print("No trading")
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() 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])
def etfDataLog(self, etf_prices: np.array, etf_weights: np.array): """Function to log ETF data, specifically ETF prices and corresponding portfolio weights. Arguments: etf_prices {np.array} -- ETF prices. etf_weights {np.array} -- Portfolio ETF weights. """ # Building log object log_dict = dict() # Building labels for dictionary etf_price_labels = [ '_'.join(['etf', i]) for i in config.sector_universe.getSectorLabels() ] port_weights_label = [ '_'.join(['etf_weight', i]) for i in config.sector_universe.getSectorLabels() ] # Adding to dictionary log_dict.update(zip(etf_price_labels, etf_prices)) log_dict.update(zip(port_weights_label, etf_weights)) # Adding to zipline record record(**log_dict)
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 handle_data(context, data): # MA1 = data[context.security].mavg(50) # MA2 = data[context.security].mavg(100) # date = str(data[context.security].datetime)[:10] # current_price = data[context.security].price # current_positions = context.portfolio.positions[symbol('600000')].amount # cash = context.portfolio.cash # value = context.portfolio.portfolio_value # current_pnl = context.portfolio.pnl # # # code (this will come under handle_data function only) # if (MA1 > MA2) and current_positions == 0: # number_of_shares = int(cash / current_price) # order(context.security, number_of_shares) # record(date=date, MA1=MA1, MA2=MA2, Price=current_price, status="buy", shares=number_of_shares, PnL=current_pnl, # cash=cash, value=value) # elif (MA1 < MA2) and current_positions != 0: # order_target(context.security, 0) # record(date=date, MA1=MA1, MA2=MA2, Price=current_price, status="sell", shares="--", PnL=current_pnl, cash=cash, # value=value) # else: # record(date=date, MA1=MA1, MA2=MA2, Price=current_price, status="--", shares="--", PnL=current_pnl, cash=cash, # value=value) order(symbol('600000'), 10) record(Close=data['Close'])
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])
def daily_check(context, data): c = context #global c.BULL, c.COUNT, OUT_DAY vola = data.history(c.MKT, 'price', c.VOLA + 1, '1d').pct_change().std() * np.sqrt(252) WAIT_DAYS = int(vola * c.RET_INITIAL) RET = int((1.0 - vola) * c.RET_INITIAL) P = data.history([c.A, c.B, c.C, c.D], 'price', RET + 2, '1d').iloc[:-1].dropna() ratio_ab = (P[c.A].iloc[-1] / P[c.A].iloc[0]) / (P[c.B].iloc[-1] / P[c.B].iloc[0]) ratio_cd = (P[c.C].iloc[-1] / P[c.C].iloc[0]) / (P[c.D].iloc[-1] / P[c.D].iloc[0]) exit = ratio_ab < c.LB and ratio_cd < c.LB if exit: c.BULL = 0 c.OUT_DAY = c.COUNT elif (c.COUNT >= c.OUT_DAY + WAIT_DAYS): c.BULL = 1 c.COUNT += 1 wt_stk = c.LEV if c.BULL else 0 wt_bnd = 0 if c.BULL else c.LEV for sec in c.STOCKS: c.wt[sec] = wt_stk / len(c.STOCKS) for sec in c.BONDS: c.wt[sec] = wt_bnd / len(c.BONDS) for sec, weight in c.wt.items(): order_target_percent(sec, weight) record(wt_bnd=wt_bnd, wt_stk=wt_stk)
def rebalance(context, data): history = data.history(assets=context.asset, fields=['close'], bar_count=context.cmo_window + 1, frequency='1d') date = history.index.values[-1] close = history['close'].values # 计算CMO指标 cmo = ta.CMO(close, timeperiod=context.cmo_window) print(cmo[-1]) current_price = data[context.asset].price record(price=current_price) buy_signal_triggered = False sell_signal_triggered = False if cmo[-1] < context.over_sell: buy_signal_triggered = True elif cmo[-1] > context.over_buy: sell_signal_triggered = True current_position = context.portfolio.positions[context.asset].amount if buy_signal_triggered and current_position == 0: print(str(date) + '==>Buy') order_target_percent(context.asset, 1.0) elif sell_signal_triggered and current_position > 0: print(str(date) + '==>Sell') order_target_percent(context.asset, 0.0) else: print("No trading")
def record_vars(context, data): """ Plot variables at the end of each day. """ record(leverage=context.account.leverage, longs=context.longs, shorts=context.shorts)
def rebalance(context, data): history = data.history(context.asset, ['close'], 40, '1d') close = history['close'].values date = history.index.values[-1] current_position = context.portfolio.positions[context.asset].amount print("当前持仓==>%d" % current_position) price = data[context.asset].price record(price=price) # 计算指标 sma_data = talib.SMA(close)[-1] wma_data = talib.WMA(close)[-1] mom_data = talib.MOM(close)[-1] # 添加今日的特征 features = [] x = [] features.append(sma_data) features.append(wma_data) features.append(mom_data) x.append(features) flag = context.svm_module.predict(x) # 预测的涨跌结果 if bool(flag) and current_position == 0: order_target_percent(context.asset, 0.5) print(str(date) + "==>买入信号") elif bool(flag) is False and current_position > 0: order_target_percent(context.asset, 0.0) print(str(date) + "==>卖出信号") else: print(str(date) + "==>无交易信号")
def handle_data(context, data): context.i += 1 if context.i < 20: return buy = False sell = False ma5 = data.history(context.sym, 'price', 5, '1d').mean() ma20 = data.history(context.sym, 'price', 20, '1d').mean() if ma5 > ma20 and context.hold == False: order_target(context.sym, 100) context.hold = True buy = True elif ma5 < ma20 and context.hold == True: order_target(context.sym, -100) context.hold = False sell = True record(LKTB=data.current(context.sym, "price"), ma5=ma5, ma20=ma20, buy=buy, sell=sell)
def handle_data(context, data): # Load historical pricing data for the stocks, using daily frequncy and a rolling 20 days prices = data.history(context.stocks, 'price', bar_count=20, frequency="1d") rsis = {} # Loop through our list of stocks for stock in context.stocks: # Get the rsi of this stock. rsi = talib.RSI(prices[stock], timeperiod=14)[-1] rsis[stock] = rsi current_position = context.portfolio.positions[stock].amount # RSI is above 70 and we own shares, time to sell if rsi > context.HIGH_RSI and current_position > 0 and data.can_trade(stock): order_target(stock, 0) # RSI is below 30 and we don't have any shares, time to buy elif rsi < context.LOW_RSI and current_position == 0 and data.can_trade(stock): order_target_percent(stock, context.target_pct_per_stock) # record the current RSI values of each stock for later ispection record(fb_rsi=rsis[symbol('FB')], amzn_rsi=rsis[symbol('AMZN')], aapl_rsi=rsis[symbol('AAPL')], nflx_rsi=rsis[symbol('NFLX')], googl_rsi=rsis[symbol('GOOGL')])
def handle_data(context, data): #print('handle data') prices = data.history(context.asset, 'price', argcount, '1d') normalizedPrices = (np.divide(prices, np.mean(prices))) scaledPrice = np.divide( (normalizedPrices - np.min(normalizedPrices)), (np.max(normalizedPrices) - np.min(normalizedPrices))) dp = tradingRule( *scaledPrice ) #[0],scaledPrice[1],scaledPrice[2],scaledPrice[3],scaledPrice[4],scaledPrice[5]) # print(dp) # dpList.append(dp) if dp < 0: desiredPosition = max(-1, dp) else: desiredPosition = min(1, dp) # if desired position varies from previous desired position by more than 10%, order to target percentage currentPosition = np.divide( (context.portfolio.positions[context.asset].amount) * (context.portfolio.positions[context.asset].cost_basis ), context.portfolio.portfolio_value) if np.abs(desiredPosition - currentPosition) > 0.1: order_target_percent(context.asset, desiredPosition) context.tradeCount += 1 context.dayCount += 1 record(Asset=data.current(context.asset, 'price'))
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 = data.history(context.sym, "price", 100, "1d").mean() long_mavg = data.history(context.sym, "price", 300, "1d").mean() # Trading logic if short_mavg > long_mavg: # order_target orders as many shares as needed to # achieve the desired number of shares. order_target(context.sym, 100) elif short_mavg < long_mavg: order_target(context.sym, 0) # Save values for later inspection record( AAPL=data.current(context.sym, "price"), short_mavg=short_mavg, long_mavg=long_mavg, )
def handle_data(context, data): logging.debug('enter handle_data') context.i += 1 if context.i < context.rsi_window: return # get the last RSI value prices = history(context.rsi_window, '1d', 'price') sec_rsi = talib.RSI(prices[context.security].values, timeperiod=context.rsi_window - 1) # buy and sell flags buy = False sell = False if sec_rsi[-1] < context.LOW_RSI and not context.invested: # RSI under 30 indicates oversold, time to buy order_target(context.security, 1000) logging.debug('Buying {}'.format(context.security)) context.invested = True buy = True elif sec_rsi[-1] > context.HIGH_RSI and context.invested: # RSI over 70 indicates overbought, sell everything order_target(context.security, 0) logging.debug('Selling {}'.format(context.security)) context.invested = False sell = True # record data for each time increment record(secRSI=sec_rsi[-1], price=data[context.security].price, buy=buy, sell=sell) logging.info(context.portfolio.cash)
def my_func(context, data): # Order 100 shares of AAPL. # order_target(context.asset, 1000) close = data.current(context.asset, "close") uplimit = data.current(context.asset, "up_limit") / 1000 # print(context.asset, "价格限制", 'close', close, 'uplimit', uplimit) if (close >= uplimit): print(context.asset, "价格限制", 'close', close, 'uplimit', uplimit) else: order(context.asset, 1000) # Retrieve all open orders. open_orders = get_open_orders() # If there are any open orders. if open_orders: # open_orders is a dictionary keyed by sid, with values that are lists of orders. Iterate over the dictionary for security, orders in open_orders.items(): # Iterate over the orders and log the total open amount # for each order. for oo in orders: message = 'Open order for {amount} shares in {stock}' message = message.format(amount=oo.amount, stock=security) log.info(message) record(AAPL=data.current(context.asset, 'price'))
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)
def rebalance(context, data): month = context.get_datetime().month if month in [2, 5, 8, 11] and context.reb_flag: # 原始持仓权重 weight_old = get_weight(context) # 目标持仓权重 print context.rank_score h = np.nanpercentile(context.rank_score, 100 - context.percent, interpolation='higher') fund_pool = context.rank_score[context.rank_score >= h] # 过滤年轻基金 longevit = 252 * 1 fund_data = data.history(fund_pool.index, 'close', longevit, '1d') selected = fund_pool[fund_data.dropna(how='any', axis=0).columns] print selected weight_new = pd.Series(0.98 / len(selected), index=selected.index) # 仓位变动百分比计算 change = {} for stock in weight_new.keys(): if stock not in weight_old.keys(): change[stock] = weight_new[stock] else: change[stock] = weight_new[stock] - weight_old[stock] # 下订单 for stock in sorted(change, key=change.get): order_percent(stock, change[stock]) # 残余头寸清仓处理 for stock in weight_old.keys(): if stock not in weight_new.keys(): order_target_percent(stock, 0) record(weights=weight_new) print '调仓了:' print weight_new
def handle_data(context, data): # Определить окна для скользящих средних short_window = 40 long_window = 100 # Пропустить первые 100 элементов, чтобы получить полное окно context.i += 1 if context.i < long_window: return # Вычислим средние скользящие short_mavg = data.history(context.asset, 'close', short_window, '1m').mean() long_mavg = data.history(context.asset, 'close', long_window, '1m').mean() #Мы проверяем, какова наша позиция в нашем портфеле и соответственно portfolio = context.portfolio # Логика стратегии if short_mavg > long_mavg: # Покупаеи акцивы в размере 10 order_target(context.asset, 10) elif short_mavg < long_mavg: order_target(context.asset, 0) # Сохранить значения для последующей визуализации record(XBTUSD=data.current(context.asset, 'close'), cash=context.portfolio.cash, portfolio_value=context.portfolio.portfolio_value, positions=context.portfolio.positions, short_mavg=short_mavg, long_mavg=long_mavg)
def handle_data(self, context, data): if not context.has_ordered: for stock in context.stocks: order(symbol(stock), 100) context.has_ordered = True record(AAPL=data.current(context.asset, 'price'))
def handle_data(context, data): context.i += 1 if context.i < 20: return buy = False sell = False ma5 = data.history(context.sym, 'price', 5, '1d').mean() #5-day simple moving average ma20 = data.history(context.sym, 'price', 20, '1d').mean() #20-day simple moving average if ma5 > ma20 and context.hold == False: #Golden-cross order_target(context.sym, 100) context.hold = True buy = True elif ma5 < ma20 and context.hold == True: #Dead-cross order_target(context.sym, -100) context.hold = False sell = True record(AAPL=data.current(context.sym, "price"), ma5=ma5, ma20=ma20, buy=buy, sell=sell)
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)
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)
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)
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)
def handle_data(context, data): # Skip first 60 mins to get full windows context.i += 1 if context.i < 60: return # Compute averages # data.history() has to be called with the same params # from above and returns a pandas dataframe. short_mavg = data.history(context.asset, 'price', bar_count=30, frequency="1m").mean() long_mavg = data.history(context.asset, 'price', bar_count=60, frequency="1m").mean() # Trading logic if short_mavg > long_mavg: # order_target orders as many shares as needed to # achieve the desired number of shares. order_target(context.asset, 100) elif short_mavg < long_mavg: order_target(context.asset, 0) # Save values for later inspection record(MDJT=data.current(context.asset, 'price'), short_mavg=short_mavg, long_mavg=long_mavg)
def handle_data(context, data): context.i += 1 if context.i < 20: return buy = False # 해당 거래일 매수 여부 sell = False # 해당 거래일 매도 여부 ma5 = data.history(context.sym, 'price', 5, '1d').mean() ma20 = data.history(context.sym, 'price', 20, '1d').mean() # 골든크로스 발생 시 100주 매수 if ma5 > ma20 and context.hold == False: order_target(context.sym, 100) context.hold = True buy = True # 데드크로스 발생 시 100주 매도 elif ma5 < ma20 and context.hold == True: order_target(context.sym, -100) context.hold = False sell = True record(AAPL=data.current(context.sym, "price"), ma5=ma5, ma20=ma20, buy=buy, sell=sell)
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])
def handle_data(context, data): # Skip first 200 days to get full windows context.i += 1 if context.i < 200: return # Compute averages short_mavg = data.history(context.asset, 'price', bar_count=50, frequency="1d").mean() long_mavg = data.history(context.asset, 'price', bar_count=200, frequency="1d").mean() # Trading logic open_orders = get_open_orders() if context.asset not in open_orders: if short_mavg > long_mavg: # order_target orders as many shares as needed to # achieve the desired number of shares. order_target_percent(context.asset, 1.0) elif short_mavg < long_mavg: order_target_percent(context.asset, 0.0) # Save values for later inspection record(AAPL=data.current(context.asset, 'price'), short_mavg=short_mavg, long_mavg=long_mavg)
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])
def rebalanceLog(self, old_weights: np.array, new_weights: np.array, new_prices: np.array): """Function to log portfolio data during a rebalancing process. Records dollar value turnover (i.e. the trades) to rebalance the portfolio, and total rebalancing turnover for the portfolio. Arguments: old_weights {np.array} -- Old ETF weights (last rebalance). new_weights {np.array} -- New ETF weights (current rebalance). new_prices {np.array} -- New ETF prices (current rebalance). """ # Computing absolute weights delta abs_weights_delta = np.abs(new_weights - old_weights) # Computing portfolio turnover (dollar value) for each of the ETFs, # using current asset prices port_rebal_turnover = np.multiply(abs_weights_delta, new_prices) # Computing total turnover port_rebal_total_turnover = np.sum(port_rebal_turnover) # Building log object log_dict = dict() # Adding to dictionary log_dict.update( zip(self.port_rebal_turnover_labels, port_rebal_turnover)) # Total turnover log_dict[self.total_port_rebal_turnover_label[0]] = \ port_rebal_total_turnover # Adding to zipline record record(**log_dict)
def handle_data(context, data): #skip first 300 days to get full windos context.i += 1 if context.i < 300: return # compute averages # data.history() has to be called with the same params # from above and returns a pandas data frame short_mavg = data.history(context.asset, 'price', bar_count=100, frequency='1d').mean() long_mavg = data.history(context.asset, 'price', bar_count=300, frequency='1d').mean() #trading logic if short_mavg > long_mavg: #order_targer orders as many shares as needed to # achieve the desired number of shares. order_target(context.asset, 100) elif short_mavg < long_mavg: order_target(context.asset, 0) # save values for later inspection record(AAPL=data.current(context.asset, 'price'), short_mavg=short_mavg, long_mavg=long_mavg)
def stop_loss(context, stock_to_sell, data): # 止损: 将 stock 仓位降低为0,并调入货币基金 # replace_stock: 调入的货币基金, 目前使用OF110006 # stock: 将要进行止损的基金 # flag: 判断 replace_stock 是否存在于原有仓位中 # weight 原有仓位权重 # stop_weight: 止损仓位,等于原始仓位重stock 的权重 flag = False #初始值为货币基金不在持仓当中 replace_stock = "110006.OF" weight = get_weight(context) stop_weight = weight[stock_to_sell] stocks = get_weight(context).keys() for stock in stocks: if stock.symbol == replace_stock: flag = True # 记录仓位及价格变动 weight = weight.drop(stock_to_sell) if flag: weight[symbol( replace_stock)] = stop_weight + weight[symbol(replace_stock)] else: weight[symbol(replace_stock)] = stop_weight weight = weight / np.sum(weight) # 更新 调入货币基金 的成本价格 context.init_value[symbol(replace_stock)] = data[symbol( replace_stock)]["price"] record(weights=weight) record(rebalance_reason=STOPLOSS) # 止损+调入货币基金下单 order_target_percent(stock_to_sell, 0) order_percent(symbol(replace_stock), stop_weight)
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)
def rebalance(context, data): history = data.history(assets=context.asset, fields=['close'], bar_count=context.bar_window, frequency='1d') date = history.index.values[-1] close = history['close'].values current_position = context.portfolio.positions[context.asset].amount current_price = data[context.asset].price record(price=current_price) print("持仓数==>%d" % current_position) short_value = ta.SMA(close, timeperiod=5) long_value = ta.SMA(close, timeperiod=15) buy_signal_triggered = False sell_signal_triggered = False if short_value[-1] >= long_value[-1] and short_value[-2] < long_value[-2]: buy_signal_triggered = True elif short_value[-1] <= long_value[-1] and short_value[-2] > long_value[-2]: sell_signal_triggered = True if buy_signal_triggered and current_position == 0: print(str(date) + '==>买入信号') order_target_percent(context.asset, 1.0) elif sell_signal_triggered and current_position > 0: print(str(date) + '==>卖出信号') order_target_percent(context.asset, 0.0) else: print(str(date) + '==>无交易信号')
def rebalance(context, data): print(data.current_dt) # Pipeline data will be a dataframe with boolean columns named 'longs' and # 'shorts'. pipeline_data = context.pipeline_data print(pipeline_data.head()) 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. 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)
def handle_data(context, data): context.i += 1 avg_days = 20 if context.i < avg_days: record(data=data, context=context) return short_mavg = data.history(context.asset, 'price', bar_count=avg_days, frequency="1d") Mean = short_mavg.mean() Std = short_mavg.std() bollinger_high = Mean + Std * 2 bollinger_low = Mean - Std * 2 curr_price = data.history(context.asset, 'price', bar_count=1, frequency="1d").mean() open_orders = get_open_orders() if context.asset not in open_orders: if curr_price > bollinger_high: order(context.asset, -1) #-1 indicates selling 1 stock elif curr_price < bollinger_low: order(context.asset, 1) record(price=data.current(symbol(stock), 'price'), short_mavg=short_mavg, data=data, context=context)
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(context, data): print "=================================" print "New iteration" print data order(symbol('AAPL'), 10) record(AAPL=data[symbol('AAPL')].price)
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_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_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.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
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): #On-Line Moving Average Reversal (OLMAR) context.days += 1 if context.days < context.window_length: return if context.init: rebalance_portfolio(context, data, context.b_t) context.init=False return m = context.m #num assets x_tilde = np.zeros(m) #relative mean deviation b = np.zeros(m) #weights #compute moving average price for each asset mavgs = history(context.window_length, '1d', 'price').mean() #mavgs = data.history(context.sids, 'price', context.window_length, '1d').mean() for i, stock in enumerate(context.stocks): price = data[stock]['price'] x_tilde[i] = mavgs[i] / price x_bar = x_tilde.mean() market_rel_dev = x_tilde - x_bar #relative deviation exp_return = np.dot(context.b_t, x_tilde) weight = context.eps - exp_return variability = (np.linalg.norm(market_rel_dev))**2 if variability == 0.0: step_size = 0 else: step_size = np.max((0, weight/variability)) b = context.b_t + step_size * market_rel_dev b_norm = simplex_projection(b) rebalance_portfolio(context, data, b_norm) context.b_t = b_norm #save values for plotting record(AAPL = data[symbol('AAPL')].price, MSFT = data[symbol('MSFT')].price, step_size = step_size, variability = variability )
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)
def deallocate_(context): # order_target_percent(symbol(REFERENCE_GROUP_SYMBOL['Cash']), 1.0) for symbol_ in context.active_orders: order_target_percent(symbol(symbol_), 0.0) # order_target(symbol(symbol_), 0.0) context.active_orders = [] if context.verbose: print "Record Variables for Performance Analysis." out_dict = {} for symbol_ in context.symbols: out_dict[symbol_] = 0.0 if context.verbose: print "Recording weight %s for symbol %s." %(0.0, symbol_) record(allocation = out_dict)
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): # order(symbol('035720'), 1) context.i += 1 if context.i < 20: return ma5 = history(5, '1d', 'price').mean() ma20 = history(20, '1d', 'price').mean() sym = symbol(context.stockCd) record(kakao=data[sym].price, ma5=ma5[sym], ma20=ma20[sym]) if ma5[sym] > ma20[sym]: order_target(sym, 1) else: order_target(sym, -1)
def handle_data(context, data): #print "Cash: $" + str(context.portfolio.cash), "Data: ", str(len(context.training_data)) #assert context.portfolio.cash > 0.0, "ERROR: negative context.portfolio.cash" assert len(context.training_data) == context.training_data_length; "ERROR: " context.security = symbol(BACKTEST_STOCK) # data stored as (open, high, low, close, volume, price) if IS_NORMALIZE: feed_data = ([ data[context.security].open - data[context.security].open, data[context.security].high - data[context.security].open, data[context.security].low - data[context.security].open, data[context.security].close - data[context.security].open #data[context.security].volume, #data[context.security].close, ]) else: 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.training_data.pop(0) context.training_data.append(feed_data) context.normalized_data = Manager.normalize(context.training_data) # will have to redo every time step #print len(context.training_data), len(context.normalized_data), len(context.normalized_data[0]) prediction = context.strategy.predict(context.training_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, .98) # 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)
def handle_data(context, data): context.day_count += 1 if context.day_count < 100: return prices = history(950, '1d', 'price').dropna() security_index = 0; daily_returns = np.zeros((len(context.stocks), 950)) for security in context.stocks: if data.has_key(security): for day in range(0, 99): day_of = prices[security][day] day_before = prices[security][day - 1] daily_returns[security_index][day] = (day_of - day_before) / day_before security_index = security_index + 1 covars = cov(daily_returns) covars = covars * 250 ########################################################### returns = prices.pct_change().dropna() bnds = ((0,1),(0,1),(0,1),(0,1),(0,1),(0,1),(0,1),(0,1),(0,1),(0,1)) cons = ({'type': 'eq', 'fun': lambda x: np.sum(x)-1.0}) res = scipy.optimize.minimize(compute_var, context.x0, cov(daily_returns)*255, method='SLSQP', constraints=cons, bounds=bnds) allocation = res.x allocation[allocation < 0] = 0 # jamais de vente, que des achats denom = np.sum(allocation) if denom != 0: allocation = allocation/denom context.x0 = allocation record(stocks=np.sum(allocation[0:-1])) record(bonds=allocation[-1]) for i, stock in enumerate(context.stocks): order_target_percent(stock, allocation[i])
def handle_data(context, data): # Record and plot the leverage of our portfolio over time. record(leverage = context.account.leverage) context.base_counter += 1 context.base_prices = add_prices(context, data) # 1. Add prices and determine the weight of stationary portfolio on X freq if context.freq_counter <= context.lookback: if context.base_counter % context.freq == 0: print 'Pre_trade freq_counter: %d' %context.freq_counter context.freq_counter += 1 pct_allocation = pre_trade(context, data) if pct_allocation: context.pct_allocation = pct_allocation return else: return # 2. Trade using the weights trained earlier if (context.freq_counter >= context.lookback and context.freq_counter < context.lookback + context.trade_bars): if context.base_counter % context.freq == 0: print 'Go2_trade freq_counter: %d' %context.freq_counter context.freq_counter += 1 pct_allocation = context.pct_allocation else: return else: context.freq_counter = context.lookback context.base_counter = 0 return # Last check before placing order if pct_allocation is None: return # Place orders. print '-'*10, 'Trade' for stock, j in zip(data, range(0,len(data))): price = data[stock].price record(stock, price) print stock log.info(pct_allocation[j]) order_target_percent(stock, pct_allocation[j])
def handle_data(context, data): # Save price to window context.short_window.append(data[symbol('AAPL')].price) context.long_window.append(data[symbol('AAPL')].price) # Compute averages short_mavg = np.mean(context.short_window) long_mavg = np.mean(context.long_window) # Trading logic if short_mavg > long_mavg: order_target(symbol('AAPL'), 100) elif short_mavg < long_mavg: order_target(symbol('AAPL'), 0) # Save values for later inspection record(AAPL=data[symbol('AAPL')].price, short_mavg=short_mavg, long_mavg=long_mavg)
def handle_data(context, data): #print context.portfolio.cash context.day += 1 i = context.day s = context.maShort[i] l = context.maLong[i] pres = s prel = l if i!=0: pres = context.maShort[i-1] prel = context.maLong[i-1] if i>=longWin-1: if s>l and pres<=prel and not context.invested: order_percent(symbol(code), 1.0) context.invested = True elif s<l and context.invested: order_percent(symbol(code), -1.0) context.invested = False record(maShort=s, maLong=l) pass
def handle_data(context, data): context.recent_prices.append(data[context.security].price) # Update the recent prices if len(context.recent_prices) == context.window_length+2: # If there's enough recent price data # Make a list of 1's and 0's, 1 when the price increased from the prior bar changes = np.diff(context.recent_prices) > 0 context.X.append(changes[:-1]) # Add independent variables, the prior changes context.Y.append(changes[-1]) # Add dependent variable, the final change if len(context.Y) >= 100: # There needs to be enough data points to make a good model context.classifier.fit(context.X, context.Y) # Generate the model context.prediction = context.classifier.predict(changes[1:]) # Predict # If prediction = 1, buy all shares affordable, if 0 sell all shares order_target_percent(context.security, context.prediction) record(prediction=int(context.prediction))
def handle_data(context, data): context.i += 1 if context.i < 20: return buy = False sell = False ma5 = data.history(context.sym, 'price', 5, '1d').mean() ma20 = data.history(context.sym, 'price', 20, '1d').mean() if ma5 > ma20 and context.hold == False: order_target(context.sym, 100) context.hold = True buy = True elif ma5 < ma20 and context.hold == True: order_target(context.sym, -100) context.hold = False sell = True record(AAPL=data.current(context.sym, "price"), ma5=ma5, ma20=ma20, buy=buy, sell=sell)