Advertisement
SOGorman35

SPY/SH 2H

Feb 24th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. import numpy as np
  2. import pandas as pd
  3.  
  4. def initialize(context):
  5.    
  6.     set_long_only()
  7.     set_slippage(slippage.FixedSlippage(spread=0))
  8.     set_commission(commission.PerShare(cost=0, min_trade_cost=0))  
  9.     context.asset = sid(8554)
  10.     context.short = sid(32268)
  11.     context.price = 'price'
  12.     context.candle_size = '1m'
  13.     context.price_history = 1440
  14.     context.mavg = 0
  15.     context.current_price = 0
  16.    
  17.     total_minutes = 390
  18.  
  19.     for i in range(1, total_minutes):
  20.         if i == 1 or i % 120 == 0:
  21.           schedule_function(bar_close, date_rules.every_day(), time_rules.market_open(minutes=i), True)
  22.        
  23. def bar_close(context, data):
  24.        
  25.     prices = data.history(context.asset, context.price, context.price_history, context.candle_size).resample('120T').last().dropna()[-2:]
  26.     context.current_price = prices[-1]
  27.     context.mavg = prices.mean()
  28.    
  29.     if context.current_price > context.mavg:
  30.         if context.asset not in context.portfolio.positions:
  31.             if not get_open_orders():
  32.                 order_target_percent(context.asset, 1)
  33.                 order_target_percent(context.short, 0)
  34.                
  35.     elif context.current_price < context.mavg:
  36.         if context.short not in context.portfolio.positions:
  37.             if not get_open_orders():
  38.                 order_target_percent(context.asset, 0)
  39.                 order_target_percent(context.short, 1)
  40.                
  41.     record(current_price=context.current_price, mavg=context.mavg)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement