def submit_sell(stock, context, data): if get_open_orders(stock): return # We bought a stock but don't know it's age yet if stock not in context.age: context.age[stock] = 0 # Don't sell stuff that's less than 1 day old if stock in context.age and context.age[stock] < 1: return shares = context.portfolio.positions[stock].amount current_price = float(data.current([stock], 'price')) two_week_price_history = data.history([stock], 'price', 10, '1d') average_two_week_price = float(two_week_price_history.mean()) current_price = float(data.current([stock], 'price')) context.stocks = [ symbol('UGAZ'), symbol('DGAZ') ] if (context.age[stock] >= context.MyFireSaleAge and (current_price < float(0.8 * average_two_week_price))): log.info("First sell function is working!" % stock.symbol) if (context.age[stock] >= context.MyFireSaleAge and (current_price > average_two_week_price)): log.info("Second sell function is working!" % stock.symbol) order(context.stock, -shares)
def submit_sell(stock, context, data): if get_open_orders(stock): return # We bought a stock but don't know it's age yet if stock not in context.age: context.age[stock] = 0 # Don't sell stuff that's less than 1 day old if stock in context.age and context.age[stock] < 1: return shares = context.portfolio.positions[stock].amount current_price = float(data.current([stock], 'price')) cost_basis = float(context.portfolio.positions[stock].cost_basis) if (context.age[stock] >= context.MyFireSaleAge and (current_price < context.MyFireSalePrice or current_price < cost_basis)): log.info("%s is in fire sale!" % stock.symbol) sell_price = float(make_div_by_05(.95 * current_price, buy=False)) order(stock, -shares, style=LimitOrder(sell_price)) else: sell_price = float( make_div_by_05(cost_basis * context.sell_factor, buy=False)) order(stock, -shares, style=LimitOrder(sell_price))
def my_rebalance(context, data): BuyFactor = .99 SellFactor = 1.1 cash = context.portfolio.cash cancel_open_buy_orders(context, data) log.info("My Rebalance: ") WeightThisBuyOrder = float(1.00 / context.MaxBuyOrdersAtOnce) for ThisBuyOrder in range(context.MaxBuyOrdersAtOnce): stock = next(context.MyCandidate) PH = data.history([stock], 'price', 20, '1d') PH_Avg = float(PH.mean()) CurrPrice = float(data.current([stock], 'price')) if np.isnan(CurrPrice): pass # probably best to wait until nan goes away else: if CurrPrice > float(1.25 * PH_Avg): BuyPrice = float(CurrPrice) else: BuyPrice = float(CurrPrice * BuyFactor) BuyPrice = float(make_div_by_05(BuyPrice, buy=True)) StockShares = int(WeightThisBuyOrder * cash / BuyPrice) order(stock, StockShares, style=LimitOrder(BuyPrice) ) place_sells(context,data)
def liquidate(portfolio): for stock in portfolio.positions: closeAnyOpenOrders(stock) if portfolio.positions[stock].amount > 0: order(stock, -portfolio.positions[stock].amount, None, None) log.info('Sold stake in ' + str(stock) + ' @ $' + str(portfolio.positions[stock].last_sale_price) + ' Cost Basis: ' + str(portfolio.positions[stock].cost_basis))
def rebalance(context, data): """Rebalance the portfolio based on context.stocks""" cancel_all_orders(context, data) sell_stocks_not_in_portfolio(context, data) LOG.info("rebalancing") LOG.info(context.stocks) totals = calculate_totals(context, data) LOG.info("totals calculated: %s" % totals) for stock, info in totals.items(): order(stock, info["total"], style=LimitOrder(info["price"]))
def my_rebalance(context, data): BuyFactor = .99 SellFactor = 1.01 cash = context.portfolio.cash cancel_open_buy_orders(context, data) log.info("My Rebalance.") # Order sell at profit target in hope that somebody actually buys it open_orders = get_open_orders() for stock in context.portfolio.positions: print(stock.sid) print(get_open_orders(stock.sid)) if stock in open_orders: pass else: print("no orders") StockShares = context.portfolio.positions[stock].amount CurrPrice = float(data.current([stock], 'price')) CostBasis = float(context.portfolio.positions[stock].cost_basis) SellPrice = float(make_div_by_05(CostBasis * SellFactor, buy=False)) if np.isnan(SellPrice): log.info("My Rebalance: NaN") pass # probably best to wait until nan goes away elif (stock in context.age and context.age[stock] == 0): log.info("My Rebalance: Age") pass elif (stock in context.age and context.MyFireSaleAge <= context.age[stock] and (context.MyFireSalePrice > CurrPrice or CostBasis > CurrPrice)): log.info("My Rebalance: Losing") if (stock in context.age and context.age[stock] < 2): pass elif stock not in context.age: context.age[stock] = 1 else: SellPrice = float( make_div_by_05(.95 * CurrPrice, buy=False)) order(stock, -StockShares, style=LimitOrder(SellPrice)) else: if (stock in context.age and context.age[stock] < 1): log.info("My Rebalance: too young") pass elif stock not in context.age: log.info("My Rebalance: no age") context.age[stock] = 1 else: log.info("My Rebalance: Place order") order(stock, -StockShares, style=LimitOrder(SellPrice))
def submit_buy(stock, context, data, weight): cash = min(investment_limits(context)['remaining_to_invest'], context.portfolio.cash) two_week_price_history = data.history([stock], 'price', 10, '1d') one_week_price_history = data.history([stock], 'price', 5, '1d') average_two_week_price = float(two_week_price_history.mean()) average_one_week_price = float(one_week_price_history.mean()) current_price = float(data.current([stock], 'price')) context.stock = [ symbol('UGAZ'), symbol('DGAZ') ] if np.isnan(current_price): pass # probably best to wait until nan goes away if current_price >= float(1.1 * average_two_week_price): # if the price is 10% greater than or equal to the 10d avg buy_price = float(current_price) if current_price >= float(1.15 * average_two_week_price): # if the price is 15% above the 10d avg buy_price = float(current_price) if current_price < float(0.95 * average_one_week_price): # if the price is 5% below the 5d avg buy_price = float(current_price) else: buy_price = float(current_price * context.buy_factor) shares_to_buy = int(weight * cash / buy_price) # This cancels open sales that would prevent these buys from being submitted if running # up against the PDT rule open_orders = get_open_orders() if stock in open_orders: for open_order in open_orders[stock]: cancel_order(open_order) order(context.stock, shares_to_buy)
def my_rebalance(context, data): log.info("my_rebalance") BuyFactor = .99 SellFactor = 1.01 cash = context.portfolio.cash log.info(cash) cancel_open_buy_orders(context, data) # Order sell at profit target in hope that somebody actually buys it for stock in context.portfolio.positions: if not get_open_orders(stock): StockShares = context.portfolio.positions[stock].amount CurrPrice = float(data.current([stock], 'price')) CostBasis = float(context.portfolio.positions[stock].cost_basis) SellPrice = float(make_div_by_05(CostBasis * SellFactor, buy=False)) if np.isnan(SellPrice): pass # probably best to wait until nan goes away elif (stock in context.age and context.age[stock] == 1): pass elif (stock in context.age and context.MyFireSaleAge <= context.age[stock] and (context.MyFireSalePrice > CurrPrice or CostBasis > CurrPrice)): if (stock in context.age and context.age[stock] < 2): pass elif stock not in context.age: context.age[stock] = 1 else: SellPrice = float( make_div_by_05(.95 * CurrPrice, buy=False)) order(stock, -StockShares, style=LimitOrder(SellPrice)) else: if (stock in context.age and context.age[stock] < 2): pass elif stock not in context.age: context.age[stock] = 1 else: order(stock, -StockShares, style=LimitOrder(SellPrice)) WeightThisBuyOrder = float(1.00 / context.MaxBuyOrdersAtOnce) for ThisBuyOrder in range(context.MaxBuyOrdersAtOnce): stock = next(context.MyCandidate) PH = data.history([stock], 'price', 20, '1d') PH_Avg = float(PH.mean()) CurrPrice = float(data.current([stock], 'price')) if np.isnan(CurrPrice): pass # probably best to wait until nan goes away else: if CurrPrice > float(1.25 * PH_Avg): BuyPrice = float(CurrPrice) else: BuyPrice = float(CurrPrice * BuyFactor) BuyPrice = float(make_div_by_05(BuyPrice, buy=True)) StockShares = int(WeightThisBuyOrder * cash / BuyPrice) order(stock, StockShares, style=LimitOrder(BuyPrice))
def submit_buy(stock, context, data, weight): cash = min( investment_limits(context)['remaining_to_invest'], context.portfolio.cash) price_history = data.history([stock], 'price', 20, '1d') average_price = float(price_history.mean()) current_price = float(data.current([stock], 'price')) if np.isnan(current_price): pass # probably best to wait until nan goes away else: if current_price > float( 1.25 * average_price): # if the price is 25% above the 20d avg buy_price = float(current_price) else: # Otherwise buy at a discount buy_price = float(current_price * context.buy_factor) buy_price = float(make_div_by_05(buy_price, buy=True)) shares_to_buy = int(weight * cash / buy_price) max_exposure = int(weight * context.portfolio.portfolio_value / buy_price) # Prevent over exposing to a particular stock, never own more than 1/max_buy_orders # of our account value positions = context.portfolio.positions if stock in positions and positions[stock].amount >= max_exposure: return # This cancels open sales that would prevent these buys from being submitted if running # up against the PDT rule open_orders = get_open_orders() if stock in open_orders: for open_order in open_orders[stock]: cancel_order(open_order) order(stock, shares_to_buy, style=LimitOrder(buy_price))
def enter_sells(context, data): # get the current prices and calculate order values and shares update_stock_data(context, context.output, data) # If order shares is negative (ie a sell) and value is greater than our min adjust threshold rules = 'order_shares < 0 and order_value > @MIN_ADJUST_AMT' sells = context.output.query(rules).index.tolist() for stock in sells: order_id = order(stock, context.output.get_value(stock, 'order_shares'), style=LimitOrder(context.output.get_value(stock, 'latest_price')) ) # store the order id in case we need to retry the order context.todays_orders.append(order_id)
def enter_buys(context, data): # get the current prices and calculate order values and shares update_stock_data(context, context.output, data) adjust_buy_orders_per_available_cash(context, data) # Order shares is positive (ie a buy) and value greater than our min adjust threshold rules = 'order_shares > 0 and order_value > @MIN_ADJUST_AMT' buys = context.output.query(rules).index.tolist() for stock in buys: order_id = order(stock, context.output.get_value(stock, 'order_shares'), style=LimitOrder(context.output.get_value(stock, 'latest_price')) ) # store the order id in case we need to retry the order context.todays_orders.append(order_id)
def retry_cancelled_order(context, data): ''' Every once in awhile Robinhood orders get mysteriously cancelled. This checks the order status and re-submits any cancelled orders. ''' for order_id in context.todays_orders[:]: original_order = get_order(order_id) if original_order and original_order.status == 2 : # The order was somehow cancelled so retry retry_id = order( original_order.sid, original_order.amount, style=LimitOrder(original_order.limit) ) log.info('order for %i shares of %s cancelled - retrying' % (original_order.amount, original_order.sid)) # Remove the original order (typically can't do but note the [:]) and store the new order context.todays_orders.remove(original_order) context.todays_orders.append(retry_id)
def place_sells(context, data): SellFactor = 1.1 cash = context.portfolio.cash open_orders = get_open_orders() place_sell_orders = 1 # exit if we have open sell orders if len(open_orders) != 0: for stock, orders in open_orders.items(): for o in orders: if 0 > o.amount: # it is a sell order place_sell_orders = 0 if place_sell_orders == 1: log.info("Place sells") # Order sell at profit target in hope that somebody actually buys it for stock in context.portfolio.positions: if stock in open_orders: pass else: StockShares = context.portfolio.positions[stock].amount CurrPrice = float(data.current([stock], 'price')) CostBasis = float(context.portfolio.positions[stock].cost_basis) SellPrice = float( make_div_by_05( CostBasis * SellFactor, buy=False)) print(stock) print(StockShares) if np.isnan(SellPrice): pass # probably best to wait until nan goes away elif (stock in context.age and context.age[stock] < 1): print("age < 1.0") pass elif ( stock in context.age and context.MyFireSaleAge <= context.age[stock] and ( context.MyFireSalePrice > CurrPrice or CostBasis > CurrPrice ) ): if (stock in context.age and context.age[stock] < 1): print("age < 1.1") pass elif stock not in context.age: print("age = 1") context.age[stock] = 1 else: print("sell loss") SellPrice = float( make_div_by_05(.95 * CurrPrice, buy=False)) order(stock, -StockShares, style=LimitOrder(SellPrice) ) else: if (stock in context.age and context.age[stock] < 1): print("age < 1") pass elif stock not in context.age: print("age = 0") context.age[stock] = 1 else: print("sell win") order(stock, -StockShares, style=LimitOrder(SellPrice) )
def rebalance(context, data): order(symbol('AAPL'), 2) record(AAPL=data.current(symbol('AAPL'), 'price'))