def handle_data(context, data): # Request history for the stock equities_hist = data.history(context.stock, "close", context.index_average_window, "1d") # Compute averages short_mavg = data.history(context.stock, 'price', bar_count=20, frequency="1d").mean() long_mavg = data.history(context.stock, 'price', bar_count=50, frequency="1d").mean() # Trading logic if short_mavg > long_mavg: order_target(context.stock, 100) elif short_mavg < long_mavg: order_target(context.stock, 0) # Save values for later inspection record(AAPL=data.current(context.stock, 'price'), short_mavg=short_mavg, long_mavg=long_mavg)
def handle_data(context, data): #order((symbol('AAPL'), 10)) #record(AAPL=data.current(symbol('AAPL'), 'price')) 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('AAPL')].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)
def handle_data(context, data): context.i += 1 if context.i < 20: return buy = False sell = False # 5일 이동평균선과 20일 이동평균선 구함 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, 1) context.hold = True buy = True # 주식을 보유한 상태에서 데드크로스가 발생하면 100주를 매도 elif ma5 < ma20 and context.hold == True: order_target(context.sym, -1) 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): 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): # 100주 매수 order_target(context.sym, 100) context.hold = True elif (ma5 < ma20 and context.hold == True): # 100주 매도 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): context.i += 1 if context.i < 20: return ma5 = history(5, '1d', 'price').mean() ma20 = history(20, '1d', 'price').mean() buy = False sell = False sym = symbol('HMD') if ma5[sym] > ma20[sym] and context.investment == False: order_target(sym, 1) context.investment = True buy = True elif ma5[sym] < ma20[sym] and context.investment == True: order_target(sym, -1) context.investment = False sell = True record(HMD=data[sym].price, ma5=ma5[sym], ma20=ma20[sym], 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): 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): context.i += 1 if context.i < 20: return buy = False sell = False ma5 = data.history(context.asset, 'close', 5, '1d').mean() ma20 = data.history(context.asset, 'close', 20, '1d').mean() ''' 수정 이전의 이동평균선 전략 if ma5 > ma20: order_target(context.asset, 1) else: order_target(context.asset, -1) ''' #수정 이후의 이동평균선 전략 # 구현한 전략과의 차이는 매수/매도가 일정 "구간" 동안 이뤄지는 것이 # 아니라 골든크로스/데드크로스 시점에서만 발생한다는 것입니다. if ma5 > ma20 and context.hold == False: order_target(context.asset, 10) context.hold = True elif ma5 < ma20 and context.hold == True: order_target(context.asset, -10) context.hold = False record(BTC=data.current(context.asset, "close"), ma5=ma5, ma20=ma20)
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): # Skip first 300 days to get full windows 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 dataframe. ma100 = data.history(context.asset, 'price', bar_count=100, frequency="1d").mean() ma300 = data.history(context.asset, 'price', bar_count=300, frequency="1d").mean() # Trading logic if ma100 > ma300: # order_target orders as many shares as needed to # achieve the desired number of shares. order_target(context.asset, 100) elif ma100 < ma300: order_target(context.asset, 0) # Save values for later inspection record(mydata=data.current(context.asset, 'price'), ma100=ma100, ma300=ma300)
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 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(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)
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 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 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, panel): #calculating moving average MA1 = panel[context.security].mavg(50) MA2 = panel[context.security].mavg(100) date = str(panel[context.security].datetime)[:10] #calculating price, pnl, portfolio value current_price = panel[context.security].price current_positions = context.portfolio.positions[symbol('SPY')].amount cash = context.portfolio.cash value = context.portfolio.portfolio_value current_pnl = context.portfolio.pnl #to buy stock if (MA1 > MA2) and current_positions == 0: number_of_shares = int(cash / current_price) order(context.security, number_of_shares) #recording the data record(date=date,MA1 = MA1, MA2 = MA2, Price= current_price,status="buy",shares=number_of_shares,\ PnL=current_pnl,cash=cash,value=value) csv_data.append([date,format(MA1, '.2f'),format(MA2, '.2f'),format(current_price, '.2f'),\ "buy",number_of_shares,format(current_pnl, '.2f'),format(cash, '.2f'),format(value, '.2f')]) #to sell stocks 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) csv_data.append([date,format(MA1, '.2f'),format(MA2, '.2f'),format(current_price, '.2f'),\ "sell","--",format(current_pnl, '.2f'),format(cash, '.2f'),format(value, '.2f')]) #do nothing just record the data else: record(date=date,MA1 = MA1, MA2 = MA2, Price= current_price,status="--",shares="--",\ PnL=current_pnl,cash=cash,value=value) csv_data.append([date,format(MA1, '.2f'),format(MA2, '.2f'),format(current_price, '.2f'),\ "--","--",format(current_pnl, '.2f'),format(cash, '.2f'),format(value, '.2f')])
def rebalance(context, data): """ Execute orders according to our schedule_function() timing. """ predictions = context.predicted_returns # Drop stocks that can not be traded predictions = predictions.loc[data.can_trade(predictions.index)] longs = (predictions[predictions > 0] .sort_values(ascending=False)[:N_LONGS] .index .tolist()) shorts = (predictions[predictions < 0] .sort_values()[:N_SHORTS] .index .tolist()) targets = set(longs + shorts) for position in context.portfolio.positions: if position not in targets: order_target(position, 0) n_longs, n_shorts = len(longs), len(shorts) if n_longs > MIN_POSITIONS and n_shorts > MIN_POSITIONS: for stock in longs: order_target_percent(stock, target=1/n_longs) for stock in shorts: order_target_percent(stock, target=-1/n_shorts) else: for stock in targets: if stock in context.portfolio.positions: order_target(stock, 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 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
def portfolio_logic(context): longs_to_remove = [] for asset in context.longs_portfolio: # search portfolio for positions to close out if asset not in context.longs.index: longs_to_remove.append(asset) order_target(asset, 0) for asset in context.longs.index: # search context.longs for stocks to add to portfolio order_target_percent(asset, .00025) if asset not in context.longs_portfolio: context.longs_portfolio[asset] = True for key in longs_to_remove: context.longs_portfolio.pop(key) shorts_to_remove = [] for asset in context.shorts_portfolio: # search portfolio for positions to close out if asset not in context.shorts.index: shorts_to_remove.append(asset) order_target(asset, 0) for asset in context.shorts.index: # search context.shorts for stocks to add to portfolio if asset not in context.shorts_portfolio: context.shorts_portfolio[asset] = True order_target_percent(asset, -0.00025) for key in shorts_to_remove: context.shorts_portfolio.pop(key)
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 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): # 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 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(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(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 handle_data(context, data): # Historical data prices = data.history(context.stocks, 'price', bar_count=20, frequency='1d') rsis = {} # Loop thru the stocks and determine when to buy and sell them for stock in context.stocks: rsi = ta.RSI(prices[stock], timeperiod=14)[-1] rsis[stock] = rsi current_position = context.portfolio.positions[stock].amount if rsi > context.high_rsi and current_position > 0 and data.can_trade(stock): order_target(stock, 0) elif rsi < context.low_rsi and current_position == 0 and data.can_trade(stock): order_target_percent(stock, context.target_pct_per_stock) 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): # 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 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 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 close_positions(context, data): """ This function is called before market close everyday and closes all open positions. """ for position in context.portfolio.positions.itervalues(): log.debug('Closing position for ' + str(position.sid) + ', amount: ' + str(position.amount) + ', cost: ' + str(position.cost_basis)) order_target(position.sid, 0) context.my_record_vars(context, data)
def handle_data(context, data): if context.live_trading is True: for symbol, position in context.portfolio.positions.items(): data.current(symbol, 'price') time.sleep(60) positions = list(context.portfolio.positions.values()) stop_list = context.stop_loss_list # update stop loss list for i1, s1 in stop_list.items(): stop_list = stop_list.drop(index=[i1]) s1 -= 1 if s1 > 0: stop_list = stop_list.append(pd.Series([s1], index=[i1])) benchmark_dma = get_dma_returns(context, 70, data.current_dt) if benchmark_dma < 0: sell_all(positions, context) return # Sell logic position_list = [] for position in positions: position_list.append(position.asset) if not position.amount > 0: continue if position.last_sale_price == 0: last_price = data.history(position.asset, 'close', 1, '1d')[0] else: last_price = position.last_sale_price # sell at stop loss net_gain_loss = float("{0:.2f}".format( (last_price - position.cost_basis) * 100 / position.cost_basis)) if net_gain_loss < -3: order_target(position.asset, 0) strategy.SendMessage( 'Sell Order', 'Buy all shares of {}'.format(str(position.asset.symbol))) context.turnover_count += 1 try: context.sector_stocks[context.pipeline_data.loc[ position.asset].sector].remove(position.asset) print("Stop loss triggered for: " + position.asset.symbol) # add to stop loss list to prevent re-buy stop_loss = pd.Series([stop_loss_prevention_days], index=[position.asset]) stop_list = stop_list.append(stop_loss) except Exception as e: print(e) context.stop_loss_list = stop_list print("Daily handle data processed for {}".format( data.current_dt.strftime('%d/%m/%Y')))
def core_logic(context, data): if context.live_trading is True: for symbol, position in context.portfolio.positions.items(): data.current(symbol, 'price') time.sleep(60) stop_list = context.stop_loss_list # update stop loss list for i1, s1 in stop_list.items(): stop_list = stop_list.drop(labels=[i1]) s1 -= 1 if s1 > 0: stop_list = stop_list.append(pd.Series([s1], index=[i1])) positions = list(context.portfolio.positions.values()) benchmark_dma = get_dma_returns(context, 200, data.current_dt) if benchmark_dma < 0: sell_all(positions, context) return elif context.shorting_on and benchmark_dma > 1: sell_all_etfs(positions, context) rebalance(context, data) # The day dma turns positive and etfs are sold, there aren't any stocks left in portfolio, hence return return position_list = [] # Sell logic for position in positions: position_list.append(position.asset) if not position.amount > 0: continue if position.last_sale_price == 0: last_price = data.history(position.asset, 'close', 1, '1d')[0] else: last_price = position.last_sale_price if last_price == 0: raise ValueError("Prices not available") net_gain_loss = float("{0:.2f}".format((last_price - position.cost_basis) * 100 / position.cost_basis)) if net_gain_loss < -3: order_target(position.asset, 0) strategy.SendMessage('Stop loss Sell Order', 'Sell all shares of {}'.format(str(position.asset.symbol))) context.turnover_count += 1 try: context.sector_stocks[context.pipeline_data.loc[position.asset].sector].remove(position.asset) print("Stop loss triggered for: {} on {}".format(position.asset.symbol, data.current_dt.strftime('%d/%m/%Y'))) stop_loss = pd.Series([stop_loss_prevention_days], index=[position.asset]) stop_list = stop_list.append(stop_loss) except Exception as e: print(e) context.stop_loss_list = stop_list print("Daily handle data processed for {}".format(data.current_dt.strftime('%d/%m/%Y')))
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): lookback = 200 percent_baseline = 0.5 # RSI retracement amount low = 30 # RSI low value RSI_time_period = 3 divergence_strength = 0 context.days_traded += 1 prices_close = data.history(assets=context.stock, bar_count=lookback, frequency='1d', fields='price') prices = data.history(assets=context.stock, bar_count=lookback, frequency='1d', fields='price') rsi = RSI(prices, RSI_time_period) rsi_prices = create_rsi_price_array(rsi, prices_close) global num_shares try: num_shares = math.floor(context.max_notional / data[context.stock].close_price) except ValueError: num_shares = 0 if num_shares > 0: set_trailing_stop(context, data) if data[context.stock].price < context.stop_price: order_target(context.stock, 0) # Sell all the stock ws.send(msg_placeholder % ("Sold because Price: %s is less than Stop Price: %s" % (data[context.stock].price, context.stop_price))) context.stop_price = 0 current_shares = context.portfolio.positions[context.stock].amount divergence = bullish_divergence(rsi_prices, percent_baseline, low) if divergence is not None and divergence[1] > 1 and current_shares == 0: troughs = divergence[0] trough_diff = troughs[1] - troughs[0] # strength of divergence if trough_diff > divergence_strength: order_target_percent(context.stock, 1.0) ws.send(msg_placeholder % ( "Bought because Divergence Strength: %s is greater than %s" % (trough_diff, divergence_strength)))
def close_all(context, data, exclude=[], log=None): """ Close all positions, except those in the exclude list """ if log: print_portfolio(log, context) for stock in context.portfolio.positions: if stock in exclude: continue if data.can_trade(stock): order_target(stock, 0)
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_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 ]
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 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(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 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
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): # 获取股票的收盘价 close_data = history(12,'1d','close') # 取得过去五天的平均价格 ma5 = close_data[-6:-2].mean() # 取得过去10天的平均价格 ma10 = close_data[-11:-2].mean() # 取得当前的现金 print get_datetime(),ma5,ma10 cash = context.portfolio.cash #print ma5[sid(symbol(context.security))],ma10[sid(stock)],cash,symbol(context.security) #如果当前有余额,并且五日均线大于十日均线 if ma5[sid(symbol(context.security))] > ma10[sid(symbol(context.security))]: order_value(symbol(context.security), cash) # 如果五日均线小于十日均线,并且目前有头寸 elif ma5[sid(symbol(context.security))] < ma10[sid(symbol(context.security))]: # 全部卖出 order_target(symbol(context.security), 0)
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)
def handle_data(context, data): # Skip first 300 days to get full windows #print data['Close'].dt #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. sym = symbol('Close') if data['short_mavg'].price > data['long_mavg'].price: # order_target orders as many shares as needed to # achieve the desired number of shares. order_target(context.sym, 1000) elif data['short_mavg'].price < data['long_mavg'].price: order_target(context.sym, 0) # Save values for later inspection record(Close=data[context.sym].price, short_mavg=data['short_mavg'].price, long_mavg=data['long_mavg'].price)
def handle_data(context, data): context.i += 1 if context.i < 20: return ma5 = history(5,'1d','price').mean() ma20 = history(20, '1d', 'price').mean() buy = False sell = False sym = symbol('HMD') if ma5[sym] > ma20[sym] and context.investment == False: order_target(sym, 1) context.investment = True buy = True elif ma5[sym] < ma20[sym] and context.investment == True: order_target(sym, -1) context.investment = False sell = True record(HMD=data[sym].price, ma5=ma5[sym], ma20=ma20[sym], buy=buy, sell=sell)
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 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): # Skip first 300 days to get full windows context.n += 1 if context.n < 359: return context.day += 1 if context.day < 7: return # Compute averages # history() has to be called with the same params # from above and returns a pandas dataframe. historical_data =history(365, '1d', 'price') pastReturns = (historical_data - historical_data.shift(-1)) / historical_data.shift(-1) short_mavg = history(42, '1d', 'price').mean() long_mavg = history(84, '1d', 'price').mean() diff = short_mavg / long_mavg - 1 diff = diff.dropna() diff.sort() buys = diff [diff > 0.03] sells = diff[diff < -0.03] buy_length = min(context.stocks_to_long, len(buys)) short_length = min(context.stocks_to_short, len(sells)) buy_weight = 1.0/buy_length if buy_length != 0 else 0 short_weight = -1.0/short_length if short_length != 0 else 0 buys.sort(ascending=False) sells.sort() buys = buys.iloc[:buy_length] if buy_weight != 0 else None sells = sells.iloc[:short_length] if short_weight != 0 else None stops = historical_data.iloc[-1] * 0.05 for i in range(len(context.syms)): #: If the security exists in our sells.index then sell if sells is not None and context.syms[i] in sells.index: #print ('SHORT: %s'%context.syms[i]) order_target_percent(context.syms[i], short_weight) #print 'sell' #: If the security instead, exists in our buys index, buy elif buys is not None and context.syms[i] in buys.index: # print ('BUYS: %s'%context.syms[i]) order_target_percent(context.syms[i], buy_weight) #print 'nothing' #: If the security is in neither list, exit any positions we might have in that security else: order_target(context.syms[i], 0) context.day = 0 # Keep track of the number of long and short positions in the portfolio longs = shorts = 0 for position in context.portfolio.positions.itervalues(): if position.amount > 0: longs += 1 if position.amount < 0: shorts += 1 record(short_mavg=short_mavg[context.syms[1]], long_mavg=long_mavg[context.syms[1]], portfoliovalue = (context.portfolio.returns), long_count=longs, short_count=shorts)
def handle_data(context, data): order_target(context.sym, 1)