Ejemplo n.º 1
0
def initialize(context):

    context.MaxCandidates = 100
    context.MaxBuyOrdersAtOnce = 30
    context.MyLeastPrice = 3.00
    context.MyMostPrice = 25.00
    context.MyFireSalePrice = context.MyLeastPrice
    context.MyFireSaleAge = 6

    print(len(context.portfolio.positions))

    # Rebalance
    EveryThisManyMinutes = 10
    TradingDayHours = 6.5
    TradingDayMinutes = int(TradingDayHours * 60)
    for minutez in range(1, TradingDayMinutes, EveryThisManyMinutes):
        schedule_function(my_rebalance, date_rules.every_day(),
                          time_rules.market_open(minutes=minutez))

    # Prevent excessive logging of canceled orders at market close.
    schedule_function(cancel_open_orders, date_rules.every_day(),
                      time_rules.market_close(hours=0, minutes=1))

    # Record variables at the end of each day.
    schedule_function(my_record_vars, date_rules.every_day(),
                      time_rules.market_close())

    # Create our pipeline and attach it to our algorithm.
    my_pipe = make_pipeline(context)
    attach_pipeline(my_pipe, 'my_pipeline')
Ejemplo n.º 2
0
def initialize(context):
    context.MaxCandidates = 100
    context.MaxBuyOrdersAtOnce = 50
    context.MyLeastPrice = 3.00
    context.MyMostPrice = 25.00
    context.MyFireSalePrice = context.MyLeastPrice
    context.MyFireSaleAge = 6
    context.buy_factor = .99
    context.sell_factor = 1.01

    context.MaxInvestment = 150000

    # over simplistic tracking of position age
    if not hasattr(context, 'age') or not context.age:
        context.age = {}

    # Rebalance
    minutes = 10
    trading_hours = 6.5
    trading_minutes = int(trading_hours * 60)
    for minutez in range(1, trading_minutes, minutes):
        schedule_function(my_rebalance, date_rules.every_day(),
                          time_rules.market_open(minutes=minutez))

    # Prevent excessive logging of canceled orders at market close.
    schedule_function(cancel_open_orders, date_rules.every_day(),
                      time_rules.market_close(hours=0, minutes=1))

    # Record variables at the end of each day.
    schedule_function(my_record_vars, date_rules.every_day(),
                      time_rules.market_close())

    # Create our pipeline and attach it to our algorithm.
    my_pipe = make_pipeline(context)
    attach_pipeline(my_pipe, 'my_pipeline')
Ejemplo n.º 3
0
def initialize(context):
    context.MaxBuyOrdersAtOnce = 50
    context.MyFireSaleAge = 6

    context.MaxInvestment = 150000

    # over simplistic tracking of position age
    if not hasattr(context, 'age') or not context.age:
        context.age = {}

    # Rebalance
    minutes = 10
    trading_hours = 6.5
    trading_minutes = int(trading_hours * 60)
    for minutez in range(1, trading_minutes, minutes):
        schedule_function(
				rebalance,
                date_rules.every_day(),
                time_rules.market_open(
                    minutes=minutez))

    # Prevent excessive logging of canceled orders at market close.
    schedule_function(
        cancel_open_orders,
        date_rules.every_day(),
        time_rules.market_close(
            hours=0,
            minutes=1))

    # Record variables at the end of each day.
    schedule_function(
        my_record_vars,
        date_rules.every_day(),
        time_rules.market_close())
Ejemplo n.º 4
0
def initialize (context): # runs once when script starts
    #context is a python dictionary that contains information on portfolio/performance.
    context.idr_losers = pd.Series(([]))
    context.day_count = 0
    context.daily_message = "Day {}."
    context.open_orders = get_open_orders()
    context.backup_stocks = symbols('VTI')

    #Factor criteria
    #dolvol = AverageDollarVolume(window_length = 1)
    close_price = USEquityPricing.close.latest
    vol = USEquityPricing.volume.latest
    ann_var = AnnualizedVolatility()
    #daily_return = DailyReturns([USEquityPricing.close], window_length = 2) #-- going to use history instead of pipeline
    
    #screening
    mask_custom = (IsPrimaryShare() & (vol < 200000) & (close_price > 1) & (close_price < 3) & (ann_var > 0.815)) # Q3000US(8000000) &
    stockBasket = USEquityPricing.close.latest.top(3000,  mask = mask_custom)
    
    #Column construction
    pipe_columns = {'close_price': close_price, "volume": vol, 'ann_var': ann_var}
    
    #Ceation of actual pipeline
    pipe = Pipeline(columns = pipe_columns, screen = stockBasket)
    attach_pipeline(pipe, "Stocks")

    #Schedule functions
    schedule_function(late_day_trade, date_rules.every_day(), time_rules.market_open(hours = 5, minutes = 56)) #offset open tells when to run a user defined function
    schedule_function(check_portfolio, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 1))
    schedule_function(morning_day_trade1, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 15))
    #schedule_function(check_portfolio, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 16))
    schedule_function(morning_day_trade2, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 45))
Ejemplo n.º 5
0
def initialize(context):

    context.MaxCandidates = 40
    context.MaxBuyOrdersAtOnce = 30
    context.MyLeastPrice = 3.00
    context.MyMostPrice = 25.00
    context.MyFireSalePrice = context.MyLeastPrice
    context.MyFireSaleAge = 6

    # over simplistic tracking of position age
    context.age = {}
    print(len(context.portfolio.positions))

    # Rebalance
    EveryThisManyMinutes = 1
    TradingDayHours = 6.5
    TradingDayMinutes = int(TradingDayHours * 60)
    for minutez in range(1, TradingDayMinutes, EveryThisManyMinutes):
        schedule_function(my_rebalance, date_rules.every_day(),
                          time_rules.market_open(minutes=minutez))

    # Prevent excessive logging of canceled orders at market close.
    schedule_function(cancel_open_orders, date_rules.every_day(),
                      time_rules.market_close(hours=0, minutes=1))

    # Record variables at the end of each day.
    schedule_function(my_record_vars, date_rules.every_day(),
                      time_rules.market_close())
Ejemplo n.º 6
0
def initialize(context):
    EveryThisManyMinutes = 1
    TradingDayHours = 6.5
    TradingDayMinutes = int(TradingDayHours * 60)
    for minutez in range(1, TradingDayMinutes, EveryThisManyMinutes):
        schedule_function(grab_data, date_rules.every_day(),
                          time_rules.market_open(minutes=minutez))
        schedule_function(handle_trade, date_rules.every_day(),
                          time_rules.market_open(minutes=minutez))
Ejemplo n.º 7
0
def initialize(context):

    log.info('Initializing Algorithm')

    # Adjustable variables
    context.avoid_trades = []
    context.trade_restrictions = [
        'ANDV', 'DDAIF', 'DHR', 'HL', 'FTV', 'LPX', 'DDAIF', 'NNHE', 'NVST',
        'PNM', 'SKY', 'XSAU'
    ]

    rebalance_hours = 0.0
    rebalance_minutes = 8.0
    context.long_exposure = 0.90
    context.short_exposure = -0.90
    context.flip_signal = False
    context.num_longs = 15
    context.num_shorts = 15
    context.spyleverage = 1.25
    context.std_cutoff = 0.17

    # Fixed variables
    rebalance_start_time = rebalance_hours * 60 + rebalance_minutes
    context.combined_restrictions = context.avoid_trades + context.trade_restrictions
    context.rebalance_complete = False
    context.trade_queue = {}
    context.rolling_portfolios = []
    context.idays = 3
    context.ndays = 0
    context.clear_queue_run = 0
    context.long_weight = context.long_exposure / context.num_longs
    context.short_weight = context.short_exposure / context.num_shorts
    context.SPY = symbol('VOO')

    attach_pipeline(make_pipeline(), 'pipeline')

    # Scheduling functions
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(minutes=rebalance_start_time))
    schedule_function(eod_operations, date_rules.every_day(),
                      time_rules.market_open(hours=6, minutes=29))

    clear_queue_frequency = 1
    clear_queue_duration = 60
    clear_queue_start = int(rebalance_start_time) + 4
    for minutez in range(clear_queue_start,
                         clear_queue_start + clear_queue_duration,
                         clear_queue_frequency):
        schedule_function(clear_queue, date_rules.every_day(),
                          time_rules.market_open(minutes=minutez))

    check_order_frequency = 10
    for minutez in range(10, 390, check_order_frequency):
        schedule_function(check_order_status, date_rules.every_day(),
                          time_rules.market_open(minutes=minutez))
def initialize(context):
    log.debug("Initializing...")
    set_long_only()

    schedule_function(sell, date_rules.every_day(), time_rules.market_open(hours=0, minutes=5), half_days=False)
    schedule_function(buy, date_rules.every_day(), time_rules.market_open(hours=0, minutes=59), half_days=False)
    schedule_function(cancel_open_orders, date_rules.every_day(), time_rules.market_close(minutes=1), half_days=False)
    schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close(), half_days=False)
    attach_pipeline(make_pipeline(), 'my_pipeline')

    context.tracker = dict()
    context.tmp_tracker = dict()
    context.first_time = True
    log.debug("Done initializing.")
Ejemplo n.º 9
0
def initialize(context):
    context.ALLOW_SHORT = False
    # False => 754% on $1000 12/31/2016 => 10/31/2018

    schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())

    my_pipe = make_pipeline()
    attach_pipeline(my_pipe, 'my_pipeline')
Ejemplo n.º 10
0
def initialize(context):
    log.info("initializing")
    context.currently_holding = set()
    schedule_function(clear, date_rules.month_start(),
                      time_rules.market_open())
    schedule_function(daily_rebalance, date_rules.every_day(),
                      time_rules.market_open(hours=1))
    schedule_function(rebalance, date_rules.month_start(),
                      time_rules.market_close(hours=1))
    set_benchmark(symbol('SPY'))
    context.days_cnt = 0
Ejemplo n.º 11
0
def initialize(context):

    #context.leverage = 1.0
    #schedule_function(rebalance, date_rules.every_day(), time_rules.every_minute())

    EveryThisManyMinutes = 1
    TradingDayHours = 6.5
    TradingDayMinutes = int(TradingDayHours * 60)
    for minutez in range(1, TradingDayMinutes, EveryThisManyMinutes):
        schedule_function(rebalance, date_rules.every_day(),
                          time_rules.market_open(minutes=minutez))
Ejemplo n.º 12
0
def initialize(context):
    """Sets up the context"""
    context.stocks = {
        symbol("TMF"): 0.2,
        symbol("UJB"): 0.2,
        symbol("TQQQ"): 0.6
    }

    context.target_leverage = 1

    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(minutes=11))
Ejemplo n.º 13
0
def initialize(context):
    #set_slippage(slippage.VolumeShareSlippage(volume_limit=.20, price_impact=0.0))
    #set_commission(commission.PerTrade(cost=0.0))
    #set_long_only()

    context.MaxCandidates = 100
    context.MaxBuyOrdersAtOnce = 30
    context.MyLeastPrice = 3.00
    context.MyMostPrice = 20.00
    context.MyFireSalePrice = context.MyLeastPrice
    context.MyFireSaleAge = 6

    # over simplistic tracking of position age
    context.age = {}
    print(len(context.portfolio.positions))

    # Rebalance
    EveryThisManyMinutes = 5
    TradingDayHours = 6.5
    TradingDayMinutes = int(TradingDayHours * 60)
    for minutez in range(1, TradingDayMinutes, EveryThisManyMinutes):
        schedule_function(my_rebalance, date_rules.every_day(),
                          time_rules.market_open(minutes=minutez))

    # Prevent excessive logging of canceled orders at market close.
    schedule_function(cancel_open_orders, date_rules.every_day(),
                      time_rules.market_close(hours=0, minutes=1))

    # Record variables at the end of each day.
    schedule_function(my_record_vars, date_rules.every_day(),
                      time_rules.market_close())

    # Create our pipeline and attach it to our algorithm.
    my_pipe = make_pipeline(context)
    attach_pipeline(my_pipe, 'my_pipeline')
    print("test 1 complete")
Ejemplo n.º 14
0
def initialize (context): # runs once when script starts
    log.info("Welcome Vincent Perkins")
    #context is a python dictionary that contains information on portfolio/performance.
    context.idr_losers = pd.Series(([])) #intraday losing stocks
    context.day_count = 0
    context.daily_message = "Day {}."
    context.open_orders = get_open_orders()
    context.backup_stocks = symbols('BAM')
    context.age = {} #empty dictionary maps one value to another
    #context.usep = USEquityPricing() #USEquityPricing object

    #Factor criteria
    close_price = USEquityPricing.close.latest
    vol = USEquityPricing.volume.latest
    ann_var = AnnualizedVolatility()
    rsi = RSI()

    #screening
    mask_custom = (IsPrimaryShare() & (vol < 150000) & (close_price > 1) & (close_price < 3) & (ann_var > 0.815) & (rsi < 50))
    stockBasket = USEquityPricing.close.latest.top(3000,  mask = mask_custom)
    
    #Column construction
    pipe_columns = {'close_price': close_price, 'volume': vol, 'ann_var': ann_var}
    
    #Creation of actual pipeline
    pipe = Pipeline(columns = pipe_columns, screen = stockBasket)
    attach_pipeline(pipe, 'Stocks')
    #Testing
    log.info(USEquityPricing.get_loader())
    eng = LivePipelineEngine(list_symbols)
    df = eng.run_pipeline(pipe)
    log.info(df)

    #Schedule functions
    schedule_function(day_start, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 1))
    schedule_function(late_day_trade, date_rules.every_day(), time_rules.market_open(hours = 5, minutes = 56)) #offset open tells when to run a user defined function
    schedule_function(check_portfolio, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 1))
    schedule_function(morning_day_trade1, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 15))
    schedule_function(morning_day_trade2, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 45))
    schedule_function(check_portfolio, date_rules.every_day(), time_rules.market_open(hours = 0, minutes = 48))
    schedule_function(cancel_open_orders, date_rules.every_day(),time_rules.market_close(hours=0, minutes=1))
Ejemplo n.º 15
0
def initialize(context):

    '''
    Called once at the start of the algorithm.
    '''
    # Set any algorithm 'constants' you will be using
    MIN_CASH = 25.00
    MIN_ADJUST_AMT = 200.00


    # Here we specify the ETFs and their associated weights
    # Ensure the weights sum to 1.0
    context.MY_ETFS = pd.DataFrame.from_items(
            [
                (symbol('TYD'), [0.1]), # Daily 7-10 Year Treasury Bull 3X Shares
                (symbol('TMF'), [0.2]), # Daily 20+ Year Treasury Bull 3X Shares
                (symbol('EDZ'), [0.2]), # Daily MSCI Emerging Markets Bear 3X Shares
                (symbol('SPXL'), [0.5]), # Daily S&P 500 Bull 3X Shares
            ],
            columns = ['weight'], orient='index')

    # Create a list of daily orders. Initially it's empty.
    context.todays_orders = []

    # Create and attach pipeline to get data
    attach_pipeline(my_pipeline(context), name='my_pipeline')


    # Try to place orders
    schedule_function(enter_sells, date_rules.every_day(), time_rules.market_open(minutes = 10))
    schedule_function(enter_buys, date_rules.every_day(), time_rules.market_open(minutes = 30))

    # Retry any cancelled orders 3 times for 10 minutes
    schedule_function(retry_cancelled_order, date_rules.every_day(), time_rules.market_open(minutes = 35))
    schedule_function(retry_cancelled_order, date_rules.every_day(), time_rules.market_open(minutes = 45))
    schedule_function(retry_cancelled_order, date_rules.every_day(), time_rules.market_open(minutes = 55))

    # Record tracking variables at the end of each day.
    schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())
    log.info('Alorithim initialized variables:')
Ejemplo n.º 16
0
def initialize(context):

    """Initialize context to store data for the algorithm."""

    LOG.info('Initializing Algorithm')

    # Adjustable variables
    context.avoid_trades = []
    context.trade_restrictions = ['ANDV', 'DDAIF', 'DHR', 'HL', 'FTV', 'LPX', 'DDAIF',
                                  'NNHE', 'NVST', 'PNM', 'SKY', 'XSAU']

    rebalance_hours = 0.0
    rebalance_minutes = 8.0
    context.long_exposure = 0.85
    context.short_exposure = -0.85
    context.num_longs = 15
    context.num_shorts = 15
    context.spyleverage = 1.25
    context.std_cutoff = 0.15
    context.idays = 3

    # Fixed variables
    rebalance_start_time = rebalance_hours*60 + rebalance_minutes
    context.combined_restrictions = context.avoid_trades + context.trade_restrictions
    context.rebalance_complete = False
    context.trade_queue = {}
    context.rolling_portfolios = []
    context.clear_queue_run = 0
    context.long_weight = context.long_exposure / context.num_longs
    context.short_weight = context.short_exposure / context.num_shorts
    context.SPY = symbol('VOO')

    redis_data = redis.from_url(os.environ.get("REDIS_URL"))
    try:
        loaded_state = pickle.loads(redis_data.get('pylivetrader_redis_state'))
        loaded_ndays = loaded_state['ndays']
        LOG.info('Loaded ndays = {}'.format(loaded_ndays))
    except:
        loaded_ndays = 0
        LOG.info('No state has been loaded: ndays = {}'.format(loaded_ndays))

    context.ndays = loaded_ndays

    attach_pipeline(make_pipeline(), 'pipeline')

    schedule_function(calculate_weights, date_rules.every_day(),
                      time_rules.market_open(minutes=(rebalance_start_time-7)))

    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(minutes=rebalance_start_time))

    clear_queue_frequency = 1
    clear_queue_duration = 56
    clear_queue_start = int(rebalance_start_time) + 4
    for minutez in range(clear_queue_start,
                         clear_queue_start + clear_queue_duration,
                         clear_queue_frequency):
        schedule_function(clear_queue,
                          date_rules.every_day(),
                          time_rules.market_open(minutes=minutez))

    check_order_frequency = 10
    check_order_duration = 50
    check_order_start = int(rebalance_start_time) + 10
    for minutez in range(check_order_start,
                         check_order_start + check_order_duration,
                         check_order_frequency):
        schedule_function(check_order_status,
                          date_rules.every_day(),
                          time_rules.market_open(minutes=minutez))

    eod_operations_start_time = int(rebalance_start_time) + 70
    schedule_function(eod_operations, date_rules.every_day(),
                      time_rules.market_open(minutes=eod_operations_start_time))