Guest User

stoploss-stocko

a guest
May 13th, 2016
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.78 KB | None | 0 0
  1. """
  2.  
  3. Stop loss simulator strategy
  4.  
  5. - buys all stocks in universe that would not have been sold by a stop loss
  6.  anchored on the worst possible entry price (aka trailing stop)
  7.  
  8. """
  9. import datetime
  10. import sqlalchemy
  11.  
  12. def initialize(context):
  13.     """
  14.    Called once at the start of the algorithm.
  15.    """
  16.     # parameters
  17.     context.lookback_days = 251 # 1 year in trading days
  18.     context.cutoff = 0.8 # -20% trail stop
  19.    
  20.     # state
  21.     context.longs = []
  22.    
  23.     # Rebalance every day, 1 hour after market open.
  24.     schedule_function(rebalance, date_rules.month_start()) #.week_start
  25.  
  26. def rebalance(context, data):
  27.     """
  28.    Buy stocks with drawdown within lookback period less than VIX
  29.    """
  30.     # prices: timestamps rows * stock columns
  31.     prices = data.history(context.stocks, 'price', context.lookback_days, '1d')
  32.    
  33.     # compute drawdown
  34.     lastday = prices.index.max()
  35.     lastprices = prices[lastday:lastday].max() # better way to extract a row?
  36.     change_from_max = lastprices / prices.max()
  37.    
  38.     # keep things that would not be taken out by a stop loss
  39.     winners = change_from_max[change_from_max > context.cutoff]
  40.     context.longs = winners.index
  41.    
  42.     # and buy them all
  43.     lotpc = 1.0 / len(context.longs)
  44.    
  45.     # sell stuff we don't want anymore
  46.     assert len(get_open_orders()) == 0
  47.     leavers = set(context.portfolio.positions) - set(context.longs)
  48.     log.info('Rebalance {} stocks in, {} sold, out of {}'.format(len(context.longs), len(leavers), len(context.stocks)))
  49.     for stock in leavers:
  50.         order_target_value(stock, 0)
  51.     # buy new stuff
  52.     for stock in context.longs:
  53.         assert data.can_trade(stock)
  54.         order_target_percent(stock, lotpc)
  55.        
  56.     record(winners=len(winners), leavers=len(leavers))
  57.  
  58. def before_trading_start(context, data):
  59.     """
  60.    Called every day before market open.
  61.    """
  62.     context.stocks = top_stocks()
  63.  
  64. def top_stocks(count=500):
  65.     """
  66.    Find the top 'count' US stocks by market cap, approximating large cap indices
  67.    """
  68.     fundies_exchange = fundamentals.company_reference.primary_exchange_id
  69.     stocks = get_fundamentals(
  70.                         query(fundamentals.valuation.market_cap)
  71.                         .filter(fundamentals.valuation.market_cap > 1e8) # 100m
  72.                         .filter(fundamentals.share_class_reference.is_primary_share == True)
  73.                         .filter(fundamentals.company_reference.country_id == "USA")
  74.                         .filter(sqlalchemy.or_(fundies_exchange == "NAS", fundies_exchange == "NYS"))
  75.                         .order_by(fundamentals.valuation.market_cap.desc())
  76.                         .limit(count),
  77.                         datetime.date.today())
  78.     return stocks.transpose().index
Advertisement
Add Comment
Please, Sign In to add comment