Esempio n. 1
0
def before_trading_start(context, data):
    # Gets our pipeline output every day.
    context.output = pipeline_output('my_pipeline')
    stocks_worst = context.output['stocks_worst']
    context.stocks_worst = context.output[stocks_worst].index.tolist()
    context.stocks_worst_weight = my_compute_weights(context)
    context.MyCandidate = cycle(context.stocks_worst)
    context.MyCandidateMean = {}
    context.LowestPrice = context.MyLeastPrice  # reset beginning of day
    positions = context.portfolio.positions

    #print_position(context)
    #print 'beggining positions', len(positions)

    for stock in positions:
        CurrPrice = float(data.current(stock, 'price'))
        if CurrPrice < context.LowestPrice:
            context.LowestPrice = CurrPrice
        if stock in context.age:
            context.age[stock] += 1
        else:
            context.age[stock] = 1
    for stock in context.age.keys():
        if stock not in positions:
            del context.age[stock]
        else:
            message = 'stock.symbol:{}  age:{}'
            #log.info(message.format(stock.symbol,  context.age[stock]))
    for stock in context.stocks_worst:
        PH_Avg = data.history(stock, 'price', 20, '1d').mean()
        context.MyCandidateMean[stock] = PH_Avg
Esempio n. 2
0
def rebalance(context, data):
    
    pipeline_output_df = pipeline_output('pipeline').dropna(how='any')
    
    # part of constrains
    max_lever = opt.MaxGrossExposure(context.max_lever)
    dollar_net = opt.DollarNeutral()
    constrain_sector_style_risk = opt.experimental.RiskModelExposure(  
        risk_model_loadings=context.risk_loading_pipeline,  
        version=0,
    )

    todays_predictions = pipeline_output_df.Model
    target_weight_series = todays_predictions.sub(todays_predictions.mean())
    target_weight_series = target_weight_series/target_weight_series.abs().sum()
    order_optimal_portfolio(
        objective=TargetWeights(target_weight_series),
        constraints=[
            #constrain_posTam,
            max_lever,
            constrain_sector_style_risk,
            dollar_net
        ]
    )

    pass
Esempio n. 3
0
def rebalance(context, data):
    """ Execute orders according to our schedule_function() timing."""

    # Timeit!
    start_time = time.time()

    ## Run pipeline
    pipeline_output_df = pipeline_output('my_pipeline').dropna(how='any')

    todays_predictions = pipeline_output_df.Model

    # Demean pipeline scores
    target_weight_series = todays_predictions.sub(todays_predictions.mean())

    # Reweight scores to prepare for portfolio ordering.
    target_weight_series = target_weight_series / target_weight_series.abs(
    ).sum()

    order_optimal_portfolio(objective=TargetWeights(target_weight_series),
                            constraints=[])

    # Print useful things. You could also track these with the "record" function.
    print('Full Rebalance Computed Seconds: ' + '{0:.2f}').format(time.time() -
                                                                  start_time)
    print("Number of total securities trading: ") + str(
        len(target_weight_series[target_weight_series > 0]))
    print("Leverage: ") + str(context.account.leverage)
Esempio n. 4
0
def before_trading_start(context, data):
    """
    Called every day before market open.
    """
    # Gets our pipeline output every day.
    context.output = pipeline_output('my_pipeline')

    # Go long in securities for which the 'longs' value is True.
    context.longs = context.output[context.output['longs']].index.tolist()
    # Go short in securities for which the 'shorts' value is True.
    context.shorts = context.output[context.output['shorts']].index.tolist()

    # Compute daily momentum for the past 6 months.
    momentum = my_compute_momentum(context, data)
    # Convert into a NumPy array for computations.
    momentum_np = np.array(momentum)

    # Calculate daily volatility of historical momentum.
    realized_vol_daily = np.std(momentum_np)
    # Annualize
    realized_vol_annual = realized_vol_daily * np.sqrt(252)

    # Target volatility of 12%
    target_vol = 0.12

    ratio = target_vol / realized_vol_annual

    # Scale leverage.
    leverage = 0.5 * ratio
    # Max leverage of 1.1
    if leverage > 0.55:
        leverage = 0.55

    context.long_leverage = leverage
    context.short_leverage = -1 * leverage
Esempio n. 5
0
def before_trading_start(context, data):
    # Gets our pipeline output every day.
    context.output = pipeline_output('my_pipeline')

    context.stocks_worst = context.output[
        context.output['stocks_worst']].index.tolist()

    context.stocks_worst_weight = my_compute_weights(context)

    context.MyCandidate = cycle(context.stocks_worst)

    context.LowestPrice = context.MyLeastPrice  #reset beginning of day
    print len(context.portfolio.positions)
    for stock in context.portfolio.positions:
        CurrPrice = float(data.current([stock], 'price'))
        if CurrPrice < context.LowestPrice:
            context.LowestPrice = CurrPrice
        if stock in context.age:
            context.age[stock] += 1
        else:
            context.age[stock] = 1
    for stock in context.age:
        if stock not in context.portfolio.positions:
            context.age[stock] = 0
        message = 'stock.symbol: {symbol}  :  age: {age}'
        log.info(message.format(symbol=stock.symbol, age=context.age[stock]))

    pass
def before_trading_start(context,data):
    context.output = pipeline_output('my_pipeline')
    # LONG
    context.longs = context.output[context.output['longs']].index.tolist()
    # SHORT
    context.shorts = context.output[context.output['shorts']].index.tolist()
    context.long_weight,context.short_weight = my_compute_weights(context)
def set_pairs(context, data):
    print "IT IS A NEW WEEK - set pairs"
    context.output = pipeline_output('my_pipeline')
    # turn pipeline output into 2d array of equities by industry
    context.eq_arr_by_indus = get_2d_equities_from_pipe_by_industry(context.output)
    # use loop to convert 2d array of equities into array of price dataframes by industry
    context.arr_of_price_dfs = []
    for i in range(len(context.eq_arr_by_indus)):
        this_industry = context.eq_arr_by_indus[i]
        this_price_df = eq_list_to_price_df(this_industry, COINT_TEST_NUM_DAYS, data)
        # print this_price_df
        context.arr_of_price_dfs.append(this_price_df)
    # find cointegrated pairs on this array of price dataframes
    found_some_pairs = find_cointegrated_pairs(context.arr_of_price_dfs)
    for pair in found_some_pairs:
        if pair not in context.stock_pairs:  
            context.stock_pairs.append(pair)
            context.tstat_list.append([])
    # print "context.stock_pairs is", context.stock_pairs
            
    #updates tstats list of lists each week 
    create_list_of_tstat_lists(context, data)
    #updates correlation lookback df each week
    make_correlation_df(context,data)
    #narrows down all cointegrted (past tense) stock pairs to just ones that will be cointegrated in the next week
   
    if len(context.correlation_df.index)>2:
        actual_pair_indicies = sort_correlation_and_choose_trading_pairs_indicies(context, data)
        actual_pair_indicies = actual_pair_indicies.astype(int)
        for index in actual_pair_indicies:
            context.actualpairs.append(context.stock_pairs[index])

    return
Esempio n. 8
0
def before_trading_start(context, data):
    """
    Called every day before market open.
    """
    context.output = pipeline_output('my_pipeline')
    context.current_stock_list = context.output.index.tolist()
    context.hourly_data = {}
Esempio n. 9
0
def trade (context, data):    

    results = pipeline_output('my_pipeline')
                        
    stck = context.stock_traded   
    stck_close = results.loc[stck].close
    stck_rsi = results.loc[stck].rsi_9                    
                        
    if not context.invested:
        if stck_rsi < 30:
            order_target_percent(stck, context.leverage)
            context.invested = True
            context.short = False
    else:
        if stck_rsi > 70:
            order_target(stck, 0)
            context.invested = False
        
    
    # Record decisions made by algo:
    if context.invested:
        if context.short:
            position = -100.0
        else:
            position = 100.0
    else:
        position = 0.0
    
    record(stck_rsi = stck_rsi,
           stck = stck_close,
           pos = position,
          )
Esempio n. 10
0
def before_trading_start(context, data):
    # Pipeline_output returns the constructed dataframe.
    output = pipeline_output('example')

    # Select and update your universe.
    context.my_universe = output.sort('simple_return', ascending=False).iloc[:context.x]
    update_universe(context.my_universe.index)
Esempio n. 11
0
def before_trading_start(context, data):  
    context.output = pipeline_output('ranked_stocks').dropna()  
    log.info("Original DF:\n%s" %context.output.head(3))
    
    n_30 = int(context.portfolio.portfolio_value/30e3)
    context.holdings = max(context.min_holdings, n_30)
   
    # Only consider stocks with a efficiency rating > threshold
    ranked_stocks = context.output[context.output.factor_5 > 0.0]

    
    # We are interested in the top 10 stocks ranked by combo_rank
    context.stock_factors = ranked_stocks.sort(['combo_rank'], ascending=True).iloc[:context.holdings]  
     
    context.stock_list = context.stock_factors.index   

#
# Entry/exit logic using slow/fast SMA
#
    Canary = data.history(context.canary, 'price', 80, '1d')
    Canary_fast = Canary[-15:].mean()
    Canary_slow = Canary.mean()
    
    context.buy_stocks = False
    if Canary_fast > Canary_slow: context.buy_stocks = True
def before_trading_start(context, data):
    """
    Called every day before market open.
    """
    context.output = pipeline_output('pipeline')
    context.output[context.output['Market Cap'] > 1e8]
    context.output.sort(['Market Cap'], ascending=False, inplace=True)
    context.security_list = context.output.head(500).index

    prices = np.log(data.history(context.security_list,
                    'price', context.lookback, '1d')).dropna(axis=1)
    R = (prices / prices.shift(context.return_window)).dropna()
    R = R[np.isfinite(R[R.columns])].fillna(0)

    # Subtract the cross-sectional average out of each data point on each day.
    ranks = (R.T - R.T.mean()).T.mean()
    # Take the top and botton percentiles for the long and short baskets
    lower, upper = ranks.quantile([.05, .95])
    shorts = ranks[ranks <= lower]
    longs = ranks[ranks >= upper]

    # Get weights that reduce the correlation within each basket
    if context.reduce_correlation:
        daily_R = prices.pct_change().dropna()
        context.longs = get_reduced_correlation_weights(daily_R[longs.index])
        context.shorts = get_reduced_correlation_weights(daily_R[shorts.index])

    else:
        # Use even weights
        longs = longs.abs()
        context.longs /= longs.sum()

        shorts = shorts.abs()
        context.shorts /= shorts.sum()
Esempio n. 13
0
def before_trading_start(context, data):
    L, S = 0, 0
    for sec in context.portfolio.positions:
        if context.portfolio.positions[sec].amount > 0:
            L += 1
        if context.portfolio.positions[sec].amount < 0:
            S += 1
    record(Longs=L)
    record(Shorts=S)
    record(leverage=context.account.leverage)
    context.output = pipeline_output('my_pipeline')
    context.List = context.output.index
    while context.newM == True:
        for sec in context.List:
            stockSymbol = str(sec.symbol)
            context.Data_Dictionary[stockSymbol] = 0.0
        for sec in context.List:
            stockSymbol = str(sec.symbol)
            Historical_Data = data.history(sec, "price", 390 * 10, "1m")
            for i in range(1, (390 * 10)):
                if i % 1 == 0:  # PLACEHOLDER - DOES NOTHING.
                    # NOT DEFAULT - GIVES SECURITIES THAT FALL OVER THE WHOLE TIME SERIES A BOOST, AND THOSE THAT RISE GET A PENALTY
                    # Reasoning: Mean Reversion Theorem
                    # Results : Positive
                    old_price = (
                        Historical_Data[i - 60]
                    )  #remember, 0 is the first value in the array, but, with HISTORICAL data, the first value is the "oldest"
                    new_price = (Historical_Data[i])
                    if new_price > old_price:
                        context.Data_Dictionary[stockSymbol] += 1
                    elif new_price < old_price:
                        context.Data_Dictionary[stockSymbol] -= 1
        #we are done scoring stocks for this month: leave the while loop.
        context.newM = False
Esempio n. 14
0
def rebalance(context, data):
    """
    Execute orders according to our schedule_function() timing.
    """

    df = algo.pipeline_output('pipeline')

    # These are the securities that we are interested in trading each month.
    top_roe = df['roe'].nlargest(context.roe_top_n).index

    # Perform Momentum calculations for each security
    ranking = []
    for sec in top_roe:
        ts = data.history(sec, 'price',
                          context.momentum_days + context.days_to_skip + 10,
                          '1d')
        score = momentum_score(ts[:-context.days_to_skip])
        if score > context.score_to_go:
            ranking.append((score, sec))

    # Sort to rank each security based on momentum
    ranking.sort(reverse=True)

    sec_to_trade = [el[1] for el in ranking]
    sec_to_trade = sec_to_trade[:context.num_stocks_to_trade]

    # weights for next order
    weights = {}

    # First find positions to close
    for sec in context.portfolio.positions:
        if sec not in sec_to_trade:
            if sec not in context.bonds:
                weights[sec] = 0.0
            elif context.can_buy_stocks:  # TODO Gradual decrease of bonds not all at once sold
                weights[sec] = 0.0

    # Compute remaining weights
    if context.can_buy_stocks and context.can_buy:

        for sec in sec_to_trade:
            weights[sec] = 1.0 / len(sec_to_trade)

    elif not context.can_buy_stocks and context.can_buy:  # buy bonds

        cs = current_money_in_stocks(context)
        bond_weight = 1.0 - (cs / context.portfolio.portfolio_value)

        for bond in context.bonds:
            if bond_weight > 0.0:
                weights[bond] = bond_weight / len(context.bonds)
            else:
                weights[bond] = 0.0

    if context.use_weights:  # Use optimizer with weights
        objective = TargetWeights(weights)
        constraints = [NetExposure(0, 1.0)]

        algo.order_optimal_portfolio(objective, constraints)
Esempio n. 15
0
def before_trading_start(context, data):
    """
    Called every day before market open.
    """
    context.output = pipeline_output('my_pipeline')
  
    # These are the securities that we are interested in trading each day.
    context.security_list = context.output.index
Esempio n. 16
0
def before_trading_start(context, data):
    """
    Called every day before market open.
    """
    context.output = pipeline_output('my_pipeline')

    # These are the securities that we are interested in trading each day.
    context.security_list = context.output.index
Esempio n. 17
0
def before_trading_start(context, data):
    """
    Called every day before market open.
    """

    # Get pipeline output
    context.output = algo.pipeline_output('pipeline')
    context.output['ebit_ttm_asof_date'] =context.output['ebit_ttm_asof_date'].astype('datetime64[ns]')
Esempio n. 18
0
def before_trading_start(context, data):
    ## パイプラインにadd したデータと, fetch_csvでフェッチしたデータの取り込み方の違いも確認!!
    context.output = pipeline_output(
        'my_pipeline')  # pipeline_output は pandas.DataFrame を返す
    context.vix = context.output['QuandleVIXClose'].loc[context.vxx]  # ⇐ここ
    context.vxv = context.output['QuandleVXVClose'].loc[context.vxx]  # ⇐ここ
    context.vixcsv = data.current('vix', 'Close')
    context.vxvcsv = data.current('vxv', 'Close')
Esempio n. 19
0
def before_trading_start(context, data):
    context.output = pipeline_output('Custom_pipeline')
    
    record(Leverage=context.account.leverage, 
           pos=len(context.portfolio.positions), 
           results=len(context.output.index))
    
    print context.output 
Esempio n. 20
0
def before_trading_start(context, data): 
    context.output = pipeline_output('momentum_metrics')
    ranks = context.output['combined_rank']
    context.longs = rank[context.output['longs']]
    context.shorts = rank[context.output['shorts']]
    # union は 論理和. set{a,b,c}.union(set{'a, d'}) => set{a,b,c,d}
    context.active_portfolio = context.longs.index.union(context.shorts.index)
    update_universe(context.active_portfolio)
Esempio n. 21
0
def before_trading_start(context, data):
    context.pipe = pipeline_output('sectorFilter')
    for sector in context.pipe['Sector']:
        if sector in context.sectorCount.keys():
            context.sectorCount[sector] += 1
    print(context.sectorCount)
    print(len(context.pipe))
    print(context.pipe)
def before_trading_start(context, data):
    context.share_for_allocation = 0.99
    context.out = algo.pipeline_output('pipeline')
    context.to_hold = {
        x: 0.0
        for x in (equity_universe + bonds_universe + reits_universe +
                  stress_universe)
    }
Esempio n. 23
0
def before_trading_start(context, data):
    port = pipeline_output('pipeline')
    context.longs = port[(port['impact'] == 100)
                         and (port['sentiment'] > 0.5)].index.tolist()
    context.shorts = port[(port['impact'] == 100)
                          and (port['sentiment'] < -0.5)].index.tolist()
    #
    context.long_weight, context.short_weight = compute_weights(context)
def before_trading_start(context, data):
    # Access results using the name passed to `attach_pipeline`.
    results = pipeline_output('my_pipeline')
    print results.head(5)

    # Define a universe with the results of a Pipeline.
    # Take the first ten assets by 30-day SMA.
    update_universe(results.sort('sma_30').index[:10])
Esempio n. 25
0
def before_trading_start(context, data):
    
    # CALL PIPELINE BEFORE TRADING START (FILL N/A IS DEFAULT TO NaN)
    context.output = pipeline_output('quality pipe').fillna(1000)
      
    # DEFINE NUMBER OF SECURITIES TO LONG AND SHORT BASED ON INDEX LOCATION 
    context.long_list = context.output.sort_values(['quality_rank'], ascending=False).iloc[:100]
    context.short_list = context.output.sort_values(['quality_rank'], ascending=False).iloc[-100:]   
def before_trading_start(context,data):
    context.output = pipeline_output('my_pipeline')

    # Long
    context.longs = context.output[context.output['High Growth']].index.tolist()


    context.long_weight = my_compute_weights(context)
Esempio n. 27
0
def rebalance(context, data):
    pipeline_output_df = pipeline_output('my_pipeline').dropna(how='any')
    todays_predictions = pipeline_output_df.Model
    target_weight_series = todays_predictions.sub(todays_predictions.mean())
    target_weight_series = target_weight_series * random.random(
    ) / target_weight_series.abs().sum()
    order_optimal_portfolio(objective=TargetWeights(target_weight_series),
                            constraints=[])
def before_trading_start(context, data):
    results = pipeline_output('factors').dropna()
    ranks = results.rank().mean(axis=1).order()

    context.hold = ranks[results["momentum"] > 1].tail(40)
    context.hold /= context.hold.sum()

    context.security_list = context.hold.tolist()
Esempio n. 29
0
def before_trading_start(context, data):
    context.output = pipeline_output('my_pipeline')
    context.security_list = context.output.index
    context.security_listF = {}
    try:
        context.vix = context.output["VixClose"].iloc[1]
    except:
        context.vix = 30
Esempio n. 30
0
def before_trading_start(context, data):
    context.output = pipeline_output('ranked_stocks')

    ranked_stocks = context.output.fillna(0)
    context.stock_list = ranked_stocks.sort(
        ['combo_rank'], ascending=True).iloc[:context.holdings]

    update_universe(context.stock_list.index)
Esempio n. 31
0
def before_trading_start(context, data):
    # Screen for securities that only have an earnings release
    # 1 business day previous and separate out the earnings surprises into
    # positive and negative
    results = pipeline_output('estimize')
    results = results[results['pe'] == 1]
    assets_in_universe = results.index
    context.positive_surprise = assets_in_universe[results.longs]
def before_trading_start(context, data):
    
    context.output = pipeline_output('my_pipeline')
    context.output = context.output.dropna()
    
    context.long_df = context.output.sort_values(by = 'combo_rank', ascending=False).iloc[:20]
    context.short_df = context.output.sort_values(by = 'combo_rank', ascending=False).iloc[-20:]
    context.cash_etf_list = [context.bond]
Esempio n. 33
0
def before_trading_start(context, data):

    context.output = algo.pipeline_output('pipeline')

    # These are the securities that we are interested in trading each day.
    context.security_list = context.output.index
    context.day_count += 1
    log.info(context.daily_message.format(context.day_count))
Esempio n. 34
0
def before_trading_start(context, data):
    context.output = pipeline_output('my_pipeline')
    
    #Filtramos por el indice creado en el pipeline#
    context.longs = context.output[context.output['Top Growth Company']].index
    
    #Llamamos a la función que asigna el peso de cada una de las posiciones#
    context.long_weight = assign_weights(context,data)
def before_trading_start(context, data):
    # Pipeline_output returns the constructed dataframe.
    output = pipeline_output('dollar_volume_10m_pipeline')

    # sort the output. Most liquid stocks are at the top of the list,
    # and least liquid stocks are at the bottom
    sorted_output = output.sort('dollar_volume', ascending = False)

    context.my_securities = sorted_output.index
def before_trading_start(context, data):
    """
    Called every day before market open.
    """
    context.output = pipeline_output('my_pipeline')
  
    # These are the securities that we are interested in trading each day.
    context.security_list = context.output.index
    context.long_list = context.output[(context.output['ewma15'] >= context.output['ewma120']) & (context.output['yes_price'] < context.output['ewma15'])]
    context.short_list = context.output[(context.output['ewma15'] < context.output['ewma120']) & (context.output['yes_price'] > context.output['ewma15'])]
def before_trading_start(context, data):

    # apply the logic to the data pull in order to get a ranked list of equities
    context.output = pipeline_output("Data")
    context.output, index = standard_frame_compute(context.output)
    context.output = composite_score(context.output, index)

    # create lists of stocks on which to go long and short
    context.long_set = set(context.output.head(26).index)
    context.short_set = set(context.output.tail(6).index)
Esempio n. 38
0
def before_trading_start(context, data):
    # Call pipeline_output to get the output
    context.output = pipeline_output('long_short_factors')
    
    context.longs = context.output[context.output['longs']].index.tolist()
    context.shorts = context.output[context.output['shorts']].index.tolist()

    context.long_weight, context.short_weight = assign_weights(context)
    
    # These are the securities that we are interested in trading each day.
    context.security_list = context.output.index
def before_trading_start(context, data):
    """
    Called every day before market open.
    """
    context.output = pipeline_output('pipeline')

    # sort by earning yield
    context.output = context.output.sort(
        columns='Free Cash Flow', ascending=False)

    # get top 20 stocks as security list
    context.eligible_assets = context.output.iloc[:19]
Esempio n. 40
0
def before_trading_start(context, data):
    
    # Pipeline_output returns a pandas DataFrame with the results of our factors
    # and filters.
    context.output = pipeline_output('mean_reversion_example')
    
    # Sets the list of securities we want to long as the securities with a 'True'
    # value in the low_returns column.
    context.long_secs = context.output[context.output['low_returns']]
    
    # Sets the list of securities we want to short as the securities with a 'True'
    # value in the high_returns column.
    context.short_secs = context.output[context.output['high_returns']]
    
    # Update our universe to contain the securities that we would like to long and short.
    update_universe(context.long_secs.index.union(context.short_secs.index))
def before_trading_start(context, data):
    # Call pipeline_output to get the output
    # Note: this is a dataframe where the index is the SIDs for all
    # securities to pass my screen and the columns are the factors which
    output = pipeline_output('ranking_example')
    ranks = output['combined_rank']

    long_ranks = ranks[output['longs']]
    short_ranks = ranks[output['shorts']]

    context.long_weights = (long_ranks / long_ranks.sum())
    log.info("Long Weights:")
    log.info(context.long_weights)

    context.short_weights = (short_ranks / short_ranks.sum())
    log.info("Short Weights:")
    log.info(context.short_weights)
def before_trading_start(context, data):
    """
    Called every day before market open. This is where we get the securities
    that made it through the pipeline.
    """
    
    # Pipeline_output returns a pandas DataFrame with the results of our factors
    # and filters.
    context.output = pipeline_output('mean_reversion_example')
    
    # Sets the list of securities we want to long as the securities with a 'True'
    # value in the low_returns column.
    context.long_secs = context.output[context.output['low_returns']]
    
    # Sets the list of securities we want to short as the securities with a 'True'
    # value in the high_returns column.
    context.short_secs = context.output[context.output['high_returns']]
    
    # Keep a list reference and a set reference to all of our pipeline securities
    # (set has much faster lookup)
    context.security_list = context.long_secs.index.union(context.short_secs.index).tolist()
    context.security_set = set(context.security_list)
def before_trading_start(context, data):
    output = pipeline_output('vix_pipeline')
    output = output.dropna()    
    context.vixpipe = output
Esempio n. 44
0
def before_trading_start(context, data):
   context.pipeline_data = pipeline_output('long_short_equity_template')
def before_trading_start(context, data):

    context.pipe_output = pipeline_output('top_dollar_volume')