Beispiel #1
0
def test_basic_api_call():

    with pytest.raises(RuntimeError) as e:

        api.symbol('AAPL')

    assert 'must be called during live trading' in str(e.value)
Beispiel #2
0
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 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))
Beispiel #4
0
    def rebalance(self, context):

        #
        # xell any stocks that are not in the new list of
        # stocks to be purchased
        #
        desiredStocks = self.masterFrame.index.values
        for stock in context.portfolio.positions:
            if stock not in desiredStocks:
                order_target_percent(stock, 0)

        #
        # set the target weights for the stocks.  The weight is the sector weight
        # as a percentage of the portolio allocation
        #
        self.displayMasterFrame()
        df = self.masterFrame
        for stock in desiredStocks:
            try:
                print('Buying {}'.format(stock))
                weight = self.getWeight(stock, df)
                order_target_percent(symbol(stock), weight)
            except:
                print('Error: Tried to purchase {} but there was an error.'.
                      format(stock))
                pass
Beispiel #5
0
def initialize(context):
    # The initialize method is called at the very start of your script's
    # execution. You can set up anything you'll be needing later here. The
    # context argument will be received by all pylivetrader methods in
    # your script, and you can store information on it that you'd like to
    # share between methods.

    # This is the asset that we'll be trading.
    context.asset = symbol('AA')
Beispiel #6
0
 def set_position(self, symbol, amount, cost_basis,
                  last_sale_price=None, last_sale_date=None):
     asset = api.symbol(symbol) if isinstance(symbol, str) else symbol
     pos = zp.Position(asset)
     pos.amount = amount
     pos.cost_basis = cost_basis
     pos.last_sale_price = last_sale_price
     pos.last_sale_date = last_sale_date
     self._positions[asset] = pos
Beispiel #7
0
def entryAndExitLogic(context, data, filtered):
    numOfPositions = len(context.portfolio.positions)
    if not filtered.empty:
        for asset, value in filtered.iterrows():
            asset = symbol(asset)
            currentPrice = data.current(asset, 'close')
            # stopPrice = currentPrice * context.stopLevel
            if longConditionsMet(value, currentPrice):
                # enter position with position size as long as leverage is below certain level
                if withinLeverageLimit(context, numOfPositions):
                    logging.info(
                        f'Ordering shares of {asset} at {currentPrice}')
                    # context.stopPriceMap[asset] = stopPrice
                    order_target_percent(asset, context.position_size)
                    numOfPositions += 1
            elif asset in context.portfolio.positions.keys():
                logging.info(f'Exiting position in {asset}')
                if not asset in [symbol('NCNO'), symbol('GME')]:
                    order_target_percent(asset, 0.0)
Beispiel #8
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))
Beispiel #9
0
def initialize(context):
    context.i = 0
    
    # what stock to trade - FAANG in this example
    stocklist = ['FB', 'AMZN', 'AAPL', 'NFLX', 'GOOGL']

    # make a list of symbols for the list of tickers
    context.stocks = [symbol(s) for s in stocklist]
    
    # create initial RSI threshold values for low (oversold and buy signal) and high (overbought and sell signal)
    context.LOW_RSI = 30
    context.HIGH_RSI = 70
Beispiel #10
0
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)
Beispiel #11
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:')
Beispiel #12
0
def handle_trade(context, data):

    context.dgaz = [symbol('DGAZ')]
    context.ugaz = [symbol('UGAZ')]

    current_dgaz_price = data.current(context.dgaz, 'price')

    current_ugaz_price = data.current(context.ugaz, 'price')

    average_dgaz_two_week_price = dgaz_two_week_price.mean()

    average_ugaz_two_week_price = ugaz_two_week_price.mean()

    average_dgaz_week_price = dgaz_week_price.mean()

    if current_dgaz_price > average_dgaz_two_week_price:
        order_target_percent(symbol('DGAZ'), 0)

    if current_ugaz_price > average_ugaz_two_week_price:
        order_target_percent(symbol('UGAZ'), 0)

    if current_dgaz_price <= (0.8 * average_dgaz_two_week_price):
        order_target_percent(symbol('DGAZ'), 0)

    if current_ugaz_price <= (0.8 * average_ugaz_two_week_price):
        order_target_percent(symbol('UGAZ'), 0)

    if current_dgaz_price <= (0.8 * average_dgaz_two_week_price):
        order_target_percent(symbol('UGAZ'), 1)

    if current_ugaz_price <= (0.8 * average_ugaz_two_week_price):
        order_target_percent(symbol('DGAZ'), 1)

    if current_dgaz_price < (0.95 * average_dgaz_week_price):
        order_target_percent(symbol('DGAZ'), 1)

    if current_dgaz_price >= (1.1 * average_dgaz_two_week_price):
        order_target_percent(symbol('DGAZ'), 1)
def determine_market_direction(context, data):
    history = data.history(symbol("QQQ"),
                           fields="price",
                           bar_count=390,
                           frequency="1d")
    slow_ema = talib.EMA(history, 90)
    slow_sma = talib.SMA(history, 100)
    diff = (slow_ema - slow_sma)[-1]

    if (slow_ema - slow_sma)[-1] >= -2:
        LOG.info("market is up %0.4f" % diff)
        context.direction = 1
    else:
        LOG.info("market is down %0.4f" % diff)
        context.direction = -1
def set_portfolio(context, data):
    if context.direction == 1:
        context.stocks = {
            symbol("TMF"): 0.2,
            symbol("UJB"): 0.2,
            symbol("TQQQ"): 0.6
        }
    else:
        context.stocks = {
            symbol("TMF"): 0.2,
            symbol("UJB"): 0.2,
            symbol("XLU"): 0.6
        }
Beispiel #15
0
def rebalance(context, data):
    order(symbol('AAPL'), 2)
    record(AAPL=data.current(symbol('AAPL'), 'price'))
def initialize(context):
    # question: what is i here?
    context.i = 0
    context.asset = symbol("AAPL")
Beispiel #17
0
def initialize(context):
    context.i = 0
    context.asset = symbol('VZ')
    context.eddie = symbol('AAPL')

    print("Init")
Beispiel #18
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))
Beispiel #19
0
def initialize(context):
    context.i = 0
    context.asset = symbol('AAPL')
Beispiel #20
0
def generateEndDayFile(context, data):

    #
    # get all the postions hel;d on account
    #
    positions = [equity.symbol for equity in context.portfolio.positions]

    #
    # queries have a max length
    #
    if len(positions) > 100:
        print("Warning: maximum query length exceeded generating file")

    #
    # get all of the data needed to be written out for
    # later processing
    #
    stocks = Stock(positions)
    quotes = stocks.get_quote()
    companies = stocks.get_company()

    #
    # build a dictionary entry for each position and its asscoiated
    # data in turn> Format: POSITION:{basis:x, amount:x, market:x, sector:s}
    #
    positionsDict = {}
    for position in positions:
        #
        # data dictionary
        #
        assetData = {}

        #
        # cost basis
        #
        basis = context.portfolio.positions[symbol(position)].cost_basis
        assetData['basis'] = basis

        #
        # Number of shares
        #
        shares = context.portfolio.positions[symbol(position)].amount
        assetData['amount'] = shares

        #
        # current market price
        #
        market = quotes[position]['latestPrice']
        assetData['market'] = market

        #
        # sector
        #
        assetData['sector'] = companies[position]['sector']
        positionsDict[position] = assetData

    #
    # write the opandas data frame and pickle the file
    df = pd.DataFrame.from_dict(positionsDict).T

    try:
        df.to_pickle("positions.pkl")
        generateEndDayReport(context.sectors)
    except:
        print("Error: could not generate report pickle file")