def before_trading_start(context, data): log.info("RUNNING before_trading_start") # Prevent running more than once a day: # https://docs.alpaca.markets/platform-migration/zipline-to-pylivetrader/#deal-with-restart today = get_datetime().floor('1D') last_date = getattr(context, 'last_date', None) if today == last_date: log.info( "Skipping before_trading_start because it's already ran today") return context.output = pipeline_output('my_pipeline') context.stocks_worst = context.output[ context.output['stocks_worst']].index.tolist() context.MyCandidate = cycle(context.stocks_worst) # Update ages for stock in context.portfolio.positions: if stock in context.age: context.age[stock] += 1 else: log.info("Could not find %s in context.age" % stock.symbol) context.age[stock] = 1 # Remove stale ages context.age = { stock: age for stock, age in context.age.items() if stock not in context.portfolio.positions } # Track the last run context.last_date = today
def before_trading_start(context, data): # over simplistic tracking of position age if not hasattr(context, 'age') or not context.age: context.age = {} today = get_datetime().floor('1D') last_date = getattr(context, 'last_date', None) if today != last_date: # Gets our pipeline output every day. context.output = pipeline_output('my_pipeline') context.stocks_worst = context.output[ context.output['stocks_worst']].index.tolist() context.stocks_worst_weight = my_compute_weights(context) context.MyCandidate = cycle(context.stocks_worst) context.LowestPrice = context.MyLeastPrice # reset beginning of day print(len(context.portfolio.positions)) for stock in context.portfolio.positions: CurrPrice = float(data.current([stock], 'price')) if CurrPrice < context.LowestPrice: context.LowestPrice = CurrPrice if stock in context.age: context.age[stock] += 1 else: context.age[stock] = 1 for stock in context.age: if stock not in context.portfolio.positions: context.age[stock] = 0 message = 'stock.symbol: {symbol} : age: {age}' log.info( message.format(symbol=stock.symbol, age=context.age[stock])) context.last_date = today
def handle_data(context, data): t = get_datetime() print('current time', t) assets = symbols('AAPL', 'GOOG', 'MSFT', 'AMZN') safe = symbol('TLT') assets_hist = data.history(assets, 'price', 5, '1m') print(assets_hist) '''
def handle_data(context, data): today = get_datetime().floor('1D') last_date = getattr(context, 'last_ran_buy', None) if today != last_date: my_rebalance(context, data) context.last_ran_buy = today else: for stock, position in context.portfolio.positions.items(): if get_open_orders(stock): continue current_price = data.current(stock, 'price') cost_basis = position.cost_basis stop_loss = -0.05 current_loss = (current_price - cost_basis) / cost_basis if current_loss < stop_loss: log.info('selling early %s (%.2f)' % (stock.symbol, current_loss)) order_target_percent(stock, 0)
def before_trading_start(context, data): log.info("RUNNING before_trading_start") # Prevent running more than once a day: # https://docs.alpaca.markets/platform-migration/zipline-to-pylivetrader/#deal-with-restart today = get_datetime().floor('1D') last_date = getattr(context, 'last_date', None) if today == last_date: log.info("Skipping before_trading_start because it's already ran today") return pipe_results = pipeline_output('my_pipeline') log.info(pipe_results) context.longs = [] for sec in pipe_results[pipe_results['longs']].index.tolist(): context.longs.append(sec) context.shorts = [] for sec in pipe_results[pipe_results['shorts']].index.tolist(): context.shorts.append(sec) # Track the last run context.last_date = today
def clear(context, data): log.info(get_datetime()) log.info("clearing") for s in context.currently_holding: order_target_percent(s, 0) context.currently_holding = set()
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