Ejemplo n.º 1
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
def balance(context, data):
    history_stock = data.history(context.stock, 'price', 20, '1d')
    history_guide = data.history(context.guide, 'price', 20, '1d')

    price_stock   = data.current(context.stock, 'price')
    price_guide   = data.current(context.guide, 'price')

    mean_stock    = np.mean(history_stock)
    mean_guide    = np.mean(history_guide)

    stddev_stock  = np.std(history_stock)
    stddev_guide  = np.std(history_guide)

    zscore_stock  = (price_stock - mean_stock) / stddev_stock
    zscore_guide  = (price_guide - mean_guide) / stddev_guide

    context.weight_stock =  0.5
    context.weight_guide = -0.5

    if (abs(zscore_guide) > abs(zscore_stock)) & (zscore_stock > 0) & (zscore_guide > 0):
        context.weight_stock =  .9

    if (abs(zscore_stock) > abs(zscore_guide)) & (zscore_stock < 0) & (zscore_guide < 0):
        context.weight_guide = -.9

    #record(leverage = context.account.leverage)

    objective = opt.TargetWeights({
        context.stock: context.weight_stock,
        context.guide: context.weight_guide
    })
    constraints = [opt.MaxGrossExposure(1.0)]
    algo.order_optimal_portfolio(objective, constraints)
Ejemplo n.º 3
0
def rebalance(context, data):
    # Create MaximizeAlpha objective using
    # sentiment_score data from pipeline output
    objective = opt.MaximizeAlpha(context.output.sentiment_score)

    # Create position size constraint
    constrain_pos_size = opt.PositionConcentration.with_equal_bounds(
        -context.max_pos_size, context.max_pos_size)

    # Ensure long and short books
    # are roughly the same size
    dollar_neutral = opt.DollarNeutral()

    # Constrain target portfolio's leverage
    max_leverage = opt.MaxGrossExposure(context.max_leverage)

    # Constrain portfolio turnover
    max_turnover = opt.MaxTurnover(context.max_turnover)

    # Constrain target portfolio's risk exposure
    # By default, max sector exposure is set at
    # 0.2, and max style exposure is set at 0.4
    factor_risk_constraints = opt.experimental.RiskModelExposure(
        context.risk_factor_betas, version=opt.Newest)

    # Rebalance portfolio using objective
    # and list of constraints
    order_optimal_portfolio(objective=objective,
                            constraints=[
                                max_leverage,
                                dollar_neutral,
                                constrain_pos_size,
                                max_turnover,
                                factor_risk_constraints,
                            ])
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
def rebalance(context, data):

    # Retrieve pipeline output
    pipeline_data = context.pipeline_data

    risk_loadings = context.risk_loadings

    objective = opt.MaximizeAlpha(pipeline_data.combined_factor)

    # Define the list of constraints
    constraints = []
    # Constrain our maximum gross leverage
    constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE))

    # Require our algorithm to remain dollar neutral
    constraints.append(opt.DollarNeutral())

    # Add the RiskModelExposure constraint to make use of the
    # default risk model constraints
    neutralize_risk_factors = opt.experimental.RiskModelExposure(
        risk_model_loadings=risk_loadings, version=0)
    constraints.append(neutralize_risk_factors)

    #constraints para las posiciones de las securities
    constraints.append(
        opt.PositionConcentration.with_equal_bounds(
            min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE))

    algo.order_optimal_portfolio(objective=objective, constraints=constraints)
Ejemplo n.º 6
0
def rebalance(context, data):
    alpha = context.pipeline_data.sentiment_score
    
    if not alpha.empty:
        objective = opt.MaximizeAlpha(alpha)
        
        constrain_pos_size = opt.PositionConcentration.with_equal_bounds(
            -context.max_pos_size,
             constrain.max_pos_size
        )
        
        max_leverage = opt.MaxGrossExposure(context.max_leverage)
        dollar_neutral = opt.DollarNeutral()
        max_turnover = opt.MaxTurnover(context.max_turnover)
        
        factor_risk_constrains = opt.experimental.RiskModelExposure(
            context.risk_factor_betas,
            version = opt.Newest
        )
        
        algo.order_optimal_portfolio(
            objective = objective,
            constrains = [
                constrain_pos_size,
                max_leverage,
                dollar_neutral,
                max_turnover,
                factor_risk_constrains
            ]
        )
Ejemplo n.º 7
0
def rebalance(context, data):

    # Each day, we will enter and exit positions by defining a portfolio optimization problem.
    # To do that, we need to set an objective for our portfolio as well as a series of constraints.

    # Our objective is to maximize alpha, where 'alpha' is defined by the negative of total_score factor.
    objective = opt.MaximizeAlpha(-context.total_score)

    # We want to constrain our portfolio to invest a maximum total amount of money (defined by MAX_GROSS_EXPOSURE).
    max_gross_exposure = opt.MaxGrossExposure(MAX_GROSS_EXPOSURE)

    # We want to constrain our portfolio to invest a limited amount in any one position.
    #To do this, we constrain the position to be between +/-
    # MAX_POSITION_CONCENTRATION (on Quantopian, a negative weight corresponds to a short position).
    max_position_concentration = opt.PositionConcentration.with_equal_bounds(
        -MAX_POSITION_CONCENTRATION, MAX_POSITION_CONCENTRATION)

    # We want to constraint our portfolio to be dollar neutral (equal amount invested in long and short positions).
    dollar_neutral = opt.DollarNeutral()

    # Stores all of our constraints in a list.
    constraints = [
        max_gross_exposure,
        max_position_concentration,
        dollar_neutral,
    ]

    algo.order_optimal_portfolio(objective, constraints)
Ejemplo n.º 8
0
def my_rebalance2(context, data):
    """
    order_optimal_portfolio で資金の〜%を注文するという注文を行う.
    """
    # もしポジションを持っている場合は,ログ出力.
    cpp = context.portfolio.positions
    if cpp:
        df = get_my_position(cpp)
        log.info('PL: {}'.format(df['PL'].sum()))
    else:
        log.info("No position")

    target_weights = dict()
    context.ratio = get_ratio(context, data)

    current_contract = data.current(context.my_future, 'contract')

    if context.ratio < -0.01:
        target_weights[current_contract] = -1.0
    elif context.ratio > -0.01:
        target_weights[current_contract] = 1.0
    else:
        target_weights[current_contract] = 0  # 1 になってた0に書き換え.

    if target_weights:
        order_optimal_portfolio(opt.TargetWeights(target_weights),
                                constraints=[])
Ejemplo n.º 9
0
def rebalance(context, data):
    # Create MaximizeAlpha objective using
    # sentiment_score data from pipeline output
    objective = opt.MaximizeAlpha(context.output.sentiment_score)

    # Create position size constraint
    constrain_pos_size = opt.PositionConcentration.with_equal_bounds(
        -context.max_pos_size, context.max_pos_size)

    # Constrain target portfolio's leverage
    max_leverage = opt.MaxGrossExposure(context.max_leverage)

    # Constrain portfolio turnover
    max_turnover = opt.MaxTurnover(context.max_turnover)

    # Constrain target portfolio's risk exposure
    factor_risk_constraints = opt.experimental.RiskModelExposure(
        context.risk_factor_betas, version=opt.Newest)

    # Rebalance portfolio using objective
    # and list of constraints
    order_optimal_portfolio(objective=objective,
                            constraints=[
                                max_leverage,
                                constrain_pos_size,
                                max_turnover,
                                factor_risk_constraints,
                            ])
Ejemplo n.º 10
0
def rebalance_portfolio(context, data):
    """
    Execute orders according to our schedule_function() timing.
    """

    predictions = context.predictions
    predictions = predictions.loc[data.can_trade(predictions.index)]

    # Select long/short positions
    n_positions = int(min(N_POSITIONS, len(predictions)) / 2)
    to_trade = (predictions[predictions > 0].nlargest(n_positions).append(
        predictions[predictions < 0].nsmallest(n_positions)))

    # Model may produce duplicate predictions
    to_trade = to_trade[~to_trade.index.duplicated()]

    # Setup Optimization Objective
    objective = opt.MaximizeAlpha(to_trade)

    # Setup Optimization Constraints
    constrain_gross_leverage = opt.MaxGrossExposure(1.0)
    constrain_pos_size = opt.PositionConcentration.with_equal_bounds(-.02, .02)
    market_neutral = opt.DollarNeutral()
    constrain_risk = RiskModelExposure(
        risk_model_loadings=context.risk_loading_pipeline, version=opt.Newest)

    # Optimizer calculates portfolio weights and
    # moves portfolio toward the target.
    order_optimal_portfolio(
        objective=objective,
        constraints=[
            constrain_gross_leverage, constrain_pos_size, market_neutral,
            constrain_risk
        ],
    )
def rebalance_pairs(context, data):
    # Calculate how far away the current spread is from its equilibrium
    zscore = calc_spread_zscore(context, data)
    
    # Get target weights to rebalance portfolio
    target_weights = get_target_weights(context, data, zscore)
    constrain_pos_size = opt.PositionConcentration.with_equal_bounds(
            -context.max_pos_size,
            context.max_pos_size
        )

        # Constrain target portfolio's leverage
    max_leverage=opt.MaxGrossExposure(context.max_leverage)

        # Ensure long and short books
        # are roughly the same size
    dollar_neutral = opt.DollarNeutral()

        # Constrain portfolio turnover
    max_turnover = opt.MaxTurnover(context.max_turnover)

        # Constrain target portfolio's risk exposure
        # By default, max sector exposure is set at
        # 0.2, and max style exposure is set at 0.4


    if target_weights:
        # If we have target weights, rebalance portfolio
        order_optimal_portfolio(
            opt.TargetWeights(target_weights),
            constraints=[
                dollar_neutral ,
 
            ]
        )
Ejemplo n.º 12
0
def rebalance(context, data):

    # Obtener dataframes
    pipeline_data = context.pipeline_data
    risk_loadings = context.risk_loadings

    # Objetivo: Maximizar retornos para el factor combinado
    objective = opt.MaximizeAlpha(pipeline_data.combined_factor)

    # Definir la lista de restricciones
    constraints = []

    # Restricción: Limitar la exposición maxima de la inversión (Donde 1 es el 100%)
    constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE))

    # Restricción: Realizar Long y short en la misma proporción
    constraints.append(opt.DollarNeutral())

    # Crear restricción del modelo de riesgo
    neutralize_risk_factors = opt.experimental.RiskModelExposure(
        risk_model_loadings=risk_loadings, version=0)
    constraints.append(neutralize_risk_factors)

    # Restricción: Limitar la cantidad de dinero que se invierte en una sola acción (Donde 1 es el 100%)
    constraints.append(
        opt.PositionConcentration.with_equal_bounds(
            min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE))

    # Calcular pesos de una cartera óptima y haga pedidos hacia esa cartera segun el objetivo y las restricciones especificadas
    algo.order_optimal_portfolio(objective=objective, constraints=constraints)
def rebalance(context, data):

    pipeline_data = context.pipeline_data
    todays_universe = pipeline_data.index

    risk_factor_exposures = pd.DataFrame(
        {'market_beta': pipeline_data.market_beta.fillna(1.0)})

    objective = opt.MaximizeAlpha(pipeline_data.combined_alpha)

    constraints = []
    constraints.append(opt.MaxGrossExposure(MAX_GROSS_EXPOSURE))
    constraints.append(opt.DollarNeutral())
    constraints.append(
        opt.NetGroupExposure.with_equal_bounds(
            labels=pipeline_data.sector,
            min=-MAX_SECTOR_EXPOSURE,
            max=MAX_SECTOR_EXPOSURE,
        ))
    neutralize_risk_factors = opt.FactorExposure(
        loadings=risk_factor_exposures,
        min_exposures={'market_beta': -MAX_BETA_EXPOSURE},
        max_exposures={'market_beta': MAX_BETA_EXPOSURE})
    constraints.append(neutralize_risk_factors)
    constraints.append(
        opt.PositionConcentration.with_equal_bounds(
            min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE))
    try:
        order_optimal_portfolio(objective=objective,
                                constraints=constraints,
                                universe=todays_universe)
    except:
        return
Ejemplo n.º 14
0
def rebalance(context, data):

    pipeline_data = context.pipeline_data

    risk_loadings = context.risk_loadings

    objective = opt.MaximizeAlpha(pipeline_data.combined_factor)

    constraints = []
    # Constrain our maximum gross leverage
    constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE))

    # Require our algorithm to remain dollar neutral
    constraints.append(opt.DollarNeutral())
    neutralize_risk_factors = opt.experimental.RiskModelExposure(
        risk_model_loadings=risk_loadings,
        version=0
    )
    constraints.append(neutralize_risk_factors)

    constraints.append(
        opt.PositionConcentration.with_equal_bounds(
            min=-MAX_SHORT_POSITION_SIZE,
            max=MAX_LONG_POSITION_SIZE
        ))

    algo.order_optimal_portfolio(
        objective=objective,
        constraints=constraints
    )
def rebalance(context, data):
    """
    Execute orders according to our schedule_function() timing.
    """
    alpha = context.output.score.dropna()

    if not alpha.empty:
        # Create MaximizeAlpha objective
        objective = opt.MaximizeAlpha(alpha)

        # Create position size constraint
        constrain_pos_size = opt.PositionConcentration.with_equal_bounds(
            -context.max_pos_size, context.max_pos_size)

        # Constrain target portfolio's leverage
        max_leverage = opt.MaxGrossExposure(context.max_leverage)

        # Ensure long and short books
        # are roughly the same size
        dollar_neutral = opt.DollarNeutral()

        # Constrain portfolio turnover
        max_turnover = opt.MaxTurnover(context.max_turnover)

        # Rebalance portfolio using objective
        # and list of constraints
        algo.order_optimal_portfolio(objective=objective,
                                     constraints=[
                                         constrain_pos_size,
                                         max_leverage,
                                         dollar_neutral,
                                         max_turnover,
                                     ])
Ejemplo n.º 16
0
def my_rebalance(context, data):
    target_weight = {}

    context.ratio = get_ratio(context, data)
    contract_sym1 = data.current(context.sym1, 'contract')
    contract_sym2 = data.current(context.sym2, 'contract')

    if (context.ratio < 1.0) and context.long_spread:
        target_weight[contract_sym1] = 0
        target_weight[contract_sym2] = 0
        context.holding_days = 0
        context.long_spread = False

    elif (context.ratio > 1) and context.short_spread:
        target_weight[contract_sym1] = 0
        target_weight[contract_sym2] = 0
        context.holding_days = 0
        context.short_spread = False

    elif context.ratio > 1.1:
        target_weight[contract_sym1] = -0.5
        target_weight[contract_sym2] = 0.5
        context.long_spread = True
        context.holding_days = context.holding_days + 1

    # elif context.ratio < 0.96:
    #     target_weight[contract_sym1] = 0.5
    #     target_weight[contract_sym2] = -0.5
    #     context.short_spread = True
    #     context.holding_days = context.holding_days + 1

    if target_weight:
        order_optimal_portfolio(opt.TargetWeights(target_weight),
                                constraints=[])
def rebalance(context, data):
    """
    A function scheduled to run once every Monday at 10AM ET in order to
    rebalance the longs and shorts lists.

    Parameters
    ----------
    context : AlgorithmContext
        See description above.
    data : BarData
        See description above.
    """
    pipeline_data = context.pipeline_data

    risk_loadings = context.risk_loadings
    objective = opt.MaximizeAlpha(pipeline_data.combined_factor)
    constraints = []
    constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE))
    constraints.append(opt.DollarNeutral())
    neutralize_risk_factors = opt.experimental.RiskModelExposure(
        risk_model_loadings=risk_loadings, version=0)
    constraints.append(neutralize_risk_factors)
    constraints.append(
        opt.PositionConcentration.with_equal_bounds(
            min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE))
    algo.order_optimal_portfolio(objective=objective, constraints=constraints)
def rebalance(context, data):
    #my_positions = context.portfolio.positions
    # Optimize API
    pipeline_data = context.pipeline_data

    # Extract from pipeline any specific risk factors to neutralize that have already been calculated
    risk_factor_exposures = pd.DataFrame(
        {'market_beta': pipeline_data.market_beta.fillna(1.0)})
    # Fill in any missing factor values with a market beta of 1.0.
    # Do this rather than simply dropping the values because want to err on the side of caution. Don't want to exclude a security just because it is missing a calculated market beta data value, so assume any missing values have full exposure to the market.

    # Define objective for the Optimize API.
    # Here we use MaximizeAlpha because we believe our combined factor ranking to be proportional to expected returns. This routine will optimize the expected return of the algorithm, going long on the highest expected return and short on the lowest.

    objective = opt.MaximizeAlpha(pipeline_data.combined_rank)

    # Define the list of constraints
    constraints = []

    # Constrain maximum gross leverage
    constraints.append(opt.MaxGrossExposure(MAX_GROSS_EXPOSURE))

    # Require algorithm to remain dollar-neutral
    constraints.append(opt.DollarNeutral())  # default tolerance = 0.0001

    # Add sector neutrality constraint using the sector classifier included in the pipeline
    constraints.append(
        opt.NetGroupExposure.with_equal_bounds(
            labels=pipeline_data.sector,
            min=-MAX_SECTOR_EXPOSURE,
            max=MAX_SECTOR_EXPOSURE,
        ))

    # Take the risk factors extracted above and list desired max/min exposures to them.
    neutralize_risk_factors = opt.FactorExposure(
        loadings=risk_factor_exposures,
        min_exposures={'market_beta': -MAX_BETA_EXPOSURE},
        max_exposures={'market_beta': MAX_BETA_EXPOSURE})
    constraints.append(neutralize_risk_factors)

    # With this constraint, we enforce that no position can make up greater than MAX_SHORT_POSITION_SIZE on the short side and no greater than MAX_LONG_POSITION_SIZE on the long side. This ensures we don't overly concentrate the portfolio in one security or a small subset of securities.
    constraints.append(
        opt.PositionConcentration.with_equal_bounds(
            min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE))

    # Put together all the pieces defined above by passing them into the order_optimal_portfolio function. This handles all ordering logic, assigning appropriate weights to the securities in our universe to maximize alpha with respect to the given constraints.
    order_optimal_portfolio(
        objective=objective,
        constraints=constraints,
    )


#=================================================================
# Python "time test", if required.  Acknowledgement & thanks to Ernesto Perez, Quantopian support.
#start = time.time()
# Block of code you want to test here
#end = time.time()
#log.info(end - start)

#=================================================================
Ejemplo n.º 19
0
def my_rebalance(context, data):
    ## 現在の期近と5限月のコントラクトを取得
    sy_1_contract = data.current(context.soybeans_1, 'contract')
    sy_5_contract = data.current(context.soybeans_5, 'contract')
    target_weights = {}

    context.my_slope = get_slope(context, data)

    if context.my_slope > context.target_slope:
        if not context.short_spread:
            context.short_spread = True
            target_weights[sy_1_contract] = -0.5
            target_weights[sy_5_contract] = 0.5
        else:
            pass
    elif context.my_slope < -context.slope:
        if not context.long_spread:
            context.long_spread = True
            target_weights[sy_1_contract] = 0.5
            target_weights[sy_5_contract] = -0.5
        else:
            pass
    elif (-0.005 < context.my_slope) and (context.my_slope < 0.005):
        context.short_spread = False
        context.long_spread = False
        target_weights[sy_1_contract] = 0.0
        target_weights[sy_5_contract] = 0.0

    log.info(context.short_spread)
    #log.info("context.long_spread:", context.long_spread)

    if target_weights:
        order_optimal_portfolio(objective=opt.TargetWeights(target_weights),
                                constraints=[])
Ejemplo n.º 20
0
def my_rebalance(context, data):
    fx_contract = data.current(context.fx, 'contract')
    fy_contract = data.current(context.fy, 'contract')

    target_weights = {}
    sign_f1_f2, sign_fx_fy, entry_flag = get_entry_flag(context, data)

    if entry_flag:  # 符号が同じなのでトレードしない.
        context.x_short_y_long = False
        context.x_long_y_short = False
        target_weights[fx_contract] = 0.0
        target_weights[fy_contract] = 0.0
        c_pair = opt.Pair(fx_contract, fy_contract)

    else:
        if sign_fx_fy > 0:
            context.x_long_y_short = True
            target_weights[fx_contract] = 0.5 * context.levarage
            target_weights[fy_contract] = -0.5 * context.levarage
            c_pair = opt.Pair(fx_contract, fy_contract)

        else:  # sign_fx_fy < 0
            context.x_short_y_long = True
            target_weights[fx_contract] = -0.5 * context.levarage
            target_weights[fy_contract] = 0.5 * context.levarage
            c_pair = opt.Pair(fy_contract, fx_contract)

    order_optimal_portfolio(
        objective=opt.TargetWeights(target_weights),
        constraints=[opt.MaxGrossExposure(context.levarage), c_pair])
Ejemplo n.º 21
0
def rebalance_pairs(context, data): 
    target_weights = get_target_weights(context, data)
    
    if target_weights:
        order_optimal_portfolio(
            opt.TargetWeights(target_weights),
            constraints=[])
Ejemplo n.º 22
0
def rebalance(context, data):
    """
    A function scheduled to run once every Monday at 10AM ET in order to
    rebalance the longs and shorts lists.

    Parameters
    ----------
    context : AlgorithmContext
        See description above.
    data : BarData
        See description above.
    """
    # Retrieve pipeline output
    pipeline_data = context.pipeline_data

    risk_loadings = context.risk_loadings

    # Here we define our objective for the Optimize API. We have
    # selected MaximizeAlpha because we believe our combined factor
    # ranking to be proportional to expected returns. This routine
    # will optimize the expected return of our algorithm, going
    # long on the highest expected return and short on the lowest.
    objective = opt.MaximizeAlpha(pipeline_data.combined_factor)

    # Define the list of constraints
    constraints = []
    # Constrain our maximum gross leverage
    constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE))

    # Require our algorithm to remain dollar neutral
    constraints.append(opt.DollarNeutral())

    # Add the RiskModelExposure constraint to make use of the
    # default risk model constraints
    neutralize_risk_factors = opt.experimental.RiskModelExposure(
        risk_model_loadings=risk_loadings,
        version=0
    )
    constraints.append(neutralize_risk_factors)

    # With this constraint we enforce that no position can make up
    # greater than MAX_SHORT_POSITION_SIZE on the short side and
    # no greater than MAX_LONG_POSITION_SIZE on the long side. This
    # ensures that we do not overly concentrate our portfolio in
    # one security or a small subset of securities.
    constraints.append(
        opt.PositionConcentration.with_equal_bounds(
            min=-MAX_SHORT_POSITION_SIZE,
            max=MAX_LONG_POSITION_SIZE
        ))

    # Put together all the pieces we defined above by passing
    # them into the algo.order_optimal_portfolio function. This handles
    # all of our ordering logic, assigning appropriate weights
    # to the securities in our universe to maximize our alpha with
    # respect to the given constraints.
    algo.order_optimal_portfolio(
        objective=objective,
        constraints=constraints
    )
Ejemplo n.º 23
0
def rebalance(context, data):
    """
    Execute orders according to our schedule_function() timing.
    """
    weights = compute_weights(context, data)
    # Optimize API variables
    objective = opt.TargetWeights(weights)
    
    leverage_constraint = opt.MaxGrossExposure(MAX_GROSS_LEVERAGE)
    
    max_turnover = opt.MaxTurnover(context.max_turnover)
    
    factor_risk_constraints = opt.experimental.RiskModelExposure(
            context.risk_factor_betas,
            version=opt.Newest
        )
    
    position_size = opt.PositionConcentration.with_equal_bounds(
        -MAX_SHORT_POSITION_SIZE,
        MAX_LONG_POSITION_SIZE,
    )
    
    market_neutral = opt.DollarNeutral()
    
    algo.order_optimal_portfolio(
        objective = objective,
        constraints = [
            leverage_constraint,
            position_size,
            market_neutral,
            max_turnover,
            factor_risk_constraints,
        ],
    )
Ejemplo n.º 24
0
def rebalance_pairs(context, data):
    calc_ratio_2 = calc_ratio(context, data, context.No2_f1, context.No2_f2) 
    #calc_ratio_3 = calc_ratio(context, data, context.No3_f1, context.No3_f2) 
    contract1, contract2 = data.current([context.No2_f1, context.No2_f2], 'contract')
    
    target_weights = {}
    
    if calc_ratio_2:
        ratio, ratio_ma_mean = calc_ratio_2
        if ratio > ratio_ma_mean:
            target_weights[contract1] = -0.25
            target_weights[contract2] = 0.25
        # elif ratio < ratio_ma_mean:
        #     target_weights[contract1] = 0.25
        #     target_weights[contract2] = -0.25            
    
        else:
            target_weights[contract1] = 0.0
            target_weights[contract2] = 0.0            
  
    if target_weights:
        # オーダー.
        # opt.TargetWeights(target_weights) を使うことで、枚数を指定するのではなく、
        # 現在のポートフォリオ価格に対して、〜%を投入するかを指示できます。
        order_optimal_portfolio(
            opt.TargetWeights(target_weights),
            constraints=[]
        )
    record(ratio=ratio, ratio_ma_mean=ratio_ma_mean)
Ejemplo n.º 25
0
def rebalance(context, data):
    # Timeit!
    start_time = time.time()

    objective = opt.MaximizeAlpha(context.predictions)

    max_gross_exposure = opt.MaxGrossExposure(MAX_GROSS_EXPOSURE)

    max_position_concentration = opt.PositionConcentration.with_equal_bounds(
        -MAX_POSITION_CONCENTRATION, MAX_POSITION_CONCENTRATION)

    dollar_neutral = opt.DollarNeutral()

    constraints = [
        max_gross_exposure,
        max_position_concentration,
        dollar_neutral,
    ]

    algo.order_optimal_portfolio(objective, 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 "Leverage: " + str(context.account.leverage)
Ejemplo n.º 26
0
def rebalance(context, data):
    """
    Execute orders according to our schedule_function() timing.
    """

    # Attempts to allocate capital to assets based on sentiment score
    objective = opt.MaximizeAlpha(context.output.sentiment_score)

    # Constrain positions
    constrain_pos_size = opt.PositionConcentration.with_equal_bounds(
        -context.max_pos_size, context.max_pos_size)

    # Constrain risk exposure
    factor_risk_constraints = opt.experimental.RiskModelExposure(
        context.risk_factor_betas, version=opt.Newest)

    # Ensure long and short books are roughly the same size
    dollar_neutral = opt.DollarNeutral()

    # Constrain target portfolio's leverage
    max_leverage = opt.MaxGrossExposure(context.max_leverage)

    # Constrain portfolio turnover
    max_turnover = opt.MaxTurnover(context.max_turnover)

    algo.order_optimal_portfolio(objective=objective,
                                 constraints=[
                                     max_leverage, dollar_neutral,
                                     max_turnover, constrain_pos_size,
                                     factor_risk_constraints
                                 ])
Ejemplo n.º 27
0
def handle_transactions(context, asset):
    buy = context.buy
    sell = context.sell
    extra_sell_req = context.extra_sell_req

    # handle buy transaction
    if buy and context.portfolio.positions[
            asset].amount == 0 or context.hold_days == -1:
        # Buy asset
        # Target a 100% long allocation of our portfolio in the given asset.
        objective = opt.TargetWeights({asset: 1.0})
        algo.order_optimal_portfolio(objective, [])
        log.info('Buy {0} after {1} periods.'.format(asset, context.hold_days))
        context.order = context.current_price
        context.hold_days = 0

    # handle sell transaction
    if sell and context.portfolio.positions[
            asset].amount > 0 and context.hold_days > context.threshold_hold_days and extra_sell_req:
        # Sell asset
        if context.move_fund_out_of_market:
            objective = opt.TargetWeights({context.out_of_market: 1.0})
            log.info('Switch to {0} after {1} periods. {2:%}'.format(
                context.out_of_market, context.hold_days,
                context.return_percent))
        else:
            objective = opt.TargetWeights({asset: 0})
            log.info('Sell {0} after {1} periods. {2:%}'.format(
                asset, context.hold_days, context.return_percent))
        algo.order_optimal_portfolio(objective, [])
        context.order = -1 * context.current_price
        context.hold_days = 0
Ejemplo n.º 28
0
def rebalance(context, data):
    pipeline_data = context.pipeline_data

    # demean and normalize
    combined_alpha = pipeline_data.combined_alpha - pipeline_data.combined_alpha.mean(
    )
    combined_alpha = combined_alpha / combined_alpha.abs().sum()

    objective = opt.MaximizeAlpha(combined_alpha)

    constraints = []

    constraints.append(opt.MaxGrossExposure(MAX_GROSS_EXPOSURE))

    constraints.append(opt.DollarNeutral())

    constraints.append(
        opt.PositionConcentration.with_equal_bounds(min=-MAX_POSITION_SIZE,
                                                    max=MAX_POSITION_SIZE))

    # risk_model_exposure = opt.experimental.RiskModelExposure(
    #     context.risk_loading_pipeline,
    #     version=opt.Newest,
    # )

    # constraints.append(risk_model_exposure)

    order_optimal_portfolio(
        objective=objective,
        constraints=constraints,
    )
def rebalance(context, data):
    # Calculate slopes for each futures
    prediction = calc_slopes(context, data)

    # Get target weights to futures contracts based on slopes
    target_weights = get_target_weights(context, data, prediction)

    # Exposure is noted for logging and record() plotting
    context.exposure = {}
    text = ''
    for contract in target_weights:
        context.exposure[contract.root_symbol] = target_weights[contract]
        if target_weights[contract] != 0:
            text += "\n%+3.1f%% \t%s \t(%s)" % (target_weights[contract] * 100,
                                                contract.symbol,
                                                contract.asset_name)
    if text == '':
        text = '\nNo positions to take'
    log.info('Target position of today:' + text)

    # Rebalance portfolio using optimaize API
    order_optimal_portfolio(opt.TargetPortfolioWeights(target_weights),
                            constraints=[
                                opt.MaxGrossLeverage(context.maxleverage),
                            ],
                            universe=target_weights)
Ejemplo n.º 30
0
def rebalance(context, data):
    """
    A function scheduled to run once every day at 10:30AM ET in order to
    rebalance the longs and shorts lists.
    Parameters
    ----------
    context : AlgorithmContext
        See description above.
    data : BarData
        An object that provides methods to get price and volume data, check
        whether a security exists, and check the last time a security traded.
    """
    # Target a 100% long allocation of our portfolio in AAPL.
    objective = opt.TargetWeights({context.aapl: 1.0})

    # The Optimize API allows you to define portfolio constraints, which can be
    # useful when you have a more complex objective. In this algorithm, we
    # don't have any constraints, so we pass an empty list.
    constraints = []

    # order_optimal_portfolio uses `objective` and `constraints` to find the
    # "best" portfolio weights (as defined by your objective) that meet all of
    # your constraints. Since our objective is just "target 100% in AAPL", and
    # we have no constraints, this will maintain 100% of our portfolio in AAPL.
    algo.order_optimal_portfolio(objective, constraints)
Ejemplo n.º 31
0
)

objective = opt.MaximizeAlpha(pipeline_data.factor_rank)

constraints = []
constraints.append(opt.MaxGrossLeverage(MAX_GROSS_LEVERAGE))
constraints.append(opt.DollarNeutral())
constraints.append(
      opt.NetPartitionExposure.with_equal_bounds(
      labels=pipeline_data.sector,
      min=-MAX_SECTOR_EXPOSURE,
      max=MAX_SECTOR_EXPOSURE,
   )
)
neutralize_risk_factors = opt.WeightedExposure(
   loadings=risk_factor_exposures,
   min_exposures={'market_be-MAX_BETA_EXPOSURE},
   max_exposures={'market_beMAX_BETA_EXPOSURE}
)
constraints.append(neutralize_risk_factors)
constraints.append(
   opt.PositionConcentration.with_equal_bounds(
      min=-MAX_SHORT_POSITION_SIZE,      max=MAX_LONG_POSITION_SIZE
   )
)

order_optimal_portfolio(
   objective=objective,
   constraints=constraints,
   universe=todays_universe
)