def handle_data(context, data): # 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=100, frequency="1m").mean() long_mavg = data.history(context.asset, 'price', bar_count=300, 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(AAPL=data.current(context.asset, 'price'), short_mavg=short_mavg, long_mavg=long_mavg)
def handle_data(context, data): # The handle_data method is called by pylivetrader every minute when # new data is received. This is where we'll execute our trading logic. For # an explanation of pylivetrader function scheduling, please see here: # https://github.com/alpacahq/pylivetrader#run. # Compute averages # data.history() will return a pandas dataframe with price information. # pandas' EWM method will give us our exponential moving averages. # Calculate short-term EMA (using data from the past 12 minutes.) short_periods = 12 short_data = data.history(context.asset, 'price', bar_count=short_periods, frequency="1m") short_ema = pd.Series.ewm(short_data, span=short_periods).mean().iloc[-1] # Calculate long-term EMA (using data from the past 26 minutes.) long_periods = 26 long_data = data.history(context.asset, 'price', bar_count=long_periods, frequency="1m") long_ema = pd.Series.ewm(long_data, span=long_periods).mean().iloc[-1] macd = short_ema - long_ema # Trading logic if macd > 0: # order_target_percent allocates a specified percentage of your # portfolio to a long position in a given asset. (A value of 1 # means that 100% of your portfolio will be allocated.) order_id = order_target(context.asset, BUY_AMOUNT) if order_id: log.info("Bought {} shares of {}".format(BUY_AMOUNT, context.asset.symbol)) elif macd < 0: # You can supply a negative value to short an asset instead. order_id = order_target(context.asset, 0) if order_id: log.info("Closed position for {}".format(context.asset.symbol)) # Save values for later inspection record(AA=data.current(context.asset, 'price'), short_mavg=short_ema, long_mavg=long_ema)
def handle_data(context, data): # Morning Margin Check (UTC timezone) - LONG ONLY if get_datetime().hour == 14 and get_datetime().minute == 35: context.requiredMargin = marginRequirements(context.portfolio) * 3.0 if context.portfolio.cash < 0.: context.usedMargin = abs(context.portfolio.cash) else: context.usedMargin = 0. if context.requiredMargin < context.usedMargin: log.warn('MARGIN REQUIREMENTS EXCEEDED. ' +\ 'Used Margin = ' + str(context.usedMargin) +\ ' Allowable Margin = ' + str(context.requiredMargin)) # Liquidate if total value falls 10% or more (disable margin use after 5% loss) if 0.9 * (context.portfolio.positions_value + context.portfolio.cash) > context.trailingStopPortfolioValue: context.trailingStopPortfolioValue = 0.90 * ( context.portfolio.positions_value + context.portfolio.cash) context.disableMarginPortfolioValue = 0.95 * ( context.portfolio.positions_value + context.portfolio.cash) if (context.portfolio.positions_value + context.portfolio.cash) < context.trailingStopPortfolioValue: log.warn('*** L I Q U I D A T E ***') liquidate(context.portfolio) context.trailingStopPortfolioValue = 0.90 * ( context.portfolio.positions_value + context.portfolio.cash) if (context.portfolio.positions_value + context.portfolio.cash) < context.disableMarginPortfolioValue: log.info('*** MARGIN USE DISABLED ***') context.allowableMargin = 1. context.enableMarginPortfolioValue = 1.10 * ( context.portfolio.positions_value + context.portfolio.cash) elif (context.portfolio.positions_value + context.portfolio.cash) > context.enableMarginPortfolioValue: log.info('*** MARGIN USE ENABLED ***') context.allowableMargin = 2. # End of Day if get_datetime().hour == 20 and get_datetime().minute == 55: for stock in list(data.keys()): closeAnyOpenOrders(stock) #if loc_dt.month != context.previous_month: ### if (get_datetime() - context.lastPortfolioUpdate) >= timedelta(weeks=context.rebalanceFrequency): ### context.lastPortfolioUpdate = get_datetime() ### log.debug('Number of secruities to be considered: ' + str(len(data.keys()))) if get_datetime().hour == 14 and get_datetime().minute == 35: all_prices = history(250, '1d', 'price') daily_returns = all_prices.pct_change().dropna() dr = np.array(daily_returns) (rr, cc) = dr.shape expreturns, covars = assets_meanvar(dr, list(data.keys())) R = expreturns C = covars rf = 0.015 expreturns = np.array(expreturns) frontier_mean, frontier_var, frontier_weights = solve_frontier( R, C, rf, context) f_w = array(frontier_weights) (row_1, col_1) = f_w.shape # Choose an allocation along the efficient frontier wts = frontier_weights[context.risk_tolerance] new_weights = wts # Set leverage to 1 leverage = sum(abs(new_weights)) portfolio_value = (context.portfolio.positions_value + context.portfolio.cash) / leverage record(PV=portfolio_value) record(Cash=context.portfolio.cash) # Reweight portfolio i = 0 for sec in list(data.keys()): if wts[i] < 0.01: wts[i] = 0.0 if wts[i] < 0.01 and context.portfolio.positions[sec].amount == 0: i = i + 1 continue order_target_percent(sec, wts[i], None, None) log.info('Adjusting ' + str(sec) + ' to ' + str(wts[i] * 100.0) + '%') i = i + 1
def rebalance(context, data): order(symbol('AAPL'), 2) record(AAPL=data.current(symbol('AAPL'), 'price'))