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
def handle_transactions(context, data, asset): buy = context.buy sell = context.sell if 'stop_loss' not in context: stop_loss = False else: stop_loss = context.stop_loss current_price, return_percent, hold_amount = get_return( context, data, asset) if current_price == 0: return # handle buy transaction if buy: # 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.hold_days = 0 # handle sell transaction if sell: # Sell asset if context.move_fund_out_of_market and (not stop_loss): 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, return_percent)) else: objective = opt.TargetWeights({asset: 0}) log.info('Sell {0} after {1} periods. {2:%}'.format( asset, context.hold_days, return_percent)) algo.order_optimal_portfolio(objective, []) context.hold_days = 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, ], )
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)
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)
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 , ] )
def rebalance(context, data): target_weights = compute_target_weight(context, data) if target_weights: order_optimal_portfolio(objective=opt.TargetWeights(target_weights), constraints=[])
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=[])
def rebalance_pairs(context, data): target_weights = get_target_weights(context, data) if target_weights: order_optimal_portfolio( opt.TargetWeights(target_weights), constraints=[])
def trade(context, data): #runs weekly; trade/rebalance stocks total_weights = pd.concat([context.stock_weights, context.alt_weights]) target_weights = opt.TargetWeights(total_weights) order_optimal_portfolio( objective = target_weights, constraints = [] )
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])
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=[])
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)
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_pairs(context, data): zscore = calc_spread_zscore(context, data) target_weights = get_target_weights(context, data, zscore) if target_weights: ## order_optimal_portfolio は,ポートフォリオをオブジェクトを引数にとり注文を指示する関数 order_optimal_portfolio(opt.TargetWeights(target_weights), constraints=[])
def rebalance_pairs(context, data): zscore = calc_spread_zscore(context, data) target_weights = get_target_weights(context, data, zscore) if target_weights: order_optimal_portfolio(opt.TargetWeights(target_weights), constraints=[])
def rebalance(context, data): """ Execute orders according to our schedule_function() timing. """ target_weights = compute_target_weights(context, data) if target_weights: order_optimal_portfolio(objective=opt.TargetWeights(target_weights), constraints=[])
def my_rebalance(context, data): msg = "" cpp = context.portfolio.positions if cpp: df = get_my_position(cpp) log.info('PL: {}'.format(df['PL'].sum())) contract_sym1 = data.current(context.sym1_list, 'contract') contract_sym2 = data.current(context.sym2_list, 'contract') price_sym1 = data.current(contract_sym1, 'price') price_sym2 = data.current(contract_sym2, 'price') ratio = price_sym1.as_matrix() / price_sym2.as_matrix() #log.info([ratio, context.long_spread, context.short_spread]) # ratio が 1以上の場合、sym1をショート、sym2をロング target_weight = {} for r, sym1, sym2 in zip(ratio, contract_sym1, contract_sym2): if not sym1 in context.long_spread.keys(): context.long_spread[sym1] = False if not sym2 in context.long_spread.keys(): context.long_spread[sym1] = False if not sym1 in context.short_spread.keys(): context.short_spread[sym1] = False if not sym2 in context.short_spread.keys(): context.short_spread[sym1] = False if r > context.upper_band: target_weight[sym1] = -0.1 target_weight[sym2] = 0.1 context.long_spread[sym1] = True msg = "Hold long spread" elif r < context.lower_band: target_weight[sym1] = 0.1 target_weight[sym2] = -0.1 context.short_spread[sym1] = True msg = msg + " Hold short spread" elif context.long_spread[sym1] and r < 1: target_weight[sym1] = 0 target_weight[sym2] = 0 context.long_spread[sym1] = False msg = msg + " Close long spread" elif context.short_spread[sym1] and r > 1: target_weight[sym1] = 0 target_weight[sym2] = 0 context.short_spread[sym1] = False msg = msg + " Close short spread" if target_weight: log.info(target_weight) order_optimal_portfolio( opt.TargetWeights(target_weight), constraints=[] ) if msg: log.info(msg) for i,r in enumerate(ratio): record(i=r)
def rebalance_when_in_the_market(context, data): # Get signal. All rows are the same. Just choose the first one. df = algo.pipeline_output('pipeline') go_out_of_the_market = df.go_out_of_the_market[0] if not go_out_of_the_market: # Long SPY order_optimal_portfolio(objective=opt.TargetWeights( context.TRADE_WEIGHTS_IN), constraints=[])
def rebalance_when_out_of_the_market(context, data): # Check whether triggered out of market sign df = algo.pipeline_output('pipeline') go_out_of_the_market = df.go_out_of_the_market[0] if go_out_of_the_market: # Long bonds order_optimal_portfolio(objective=opt.TargetWeights( context.TRADE_WEIGHTS_OUT), constraints=[])
def my_rebalance(context, data): # Calculate target weights to rebalance target_weights = compute_target_weights(context, data) # If we have target weights, rebalance our portfolio if target_weights: order_optimal_portfolio( objective=opt.TargetWeights(target_weights), constraints=[], )
def trade(context, data): # Create a TargetWeights objective target_weights = opt.TargetWeights(context.stock_weights) # Execute the order_optimal_portfolio method with above objective and any constraint # Add opt.MaxGrossExposure(1.0) as a constraint to insure not leverage is used constraints = [] constraints.append(opt.MaxGrossExposure(1.0)) order_optimal_portfolio(objective=target_weights, constraints=constraints)
def my_rebalance(context, data): ## 現在の期近と5限月のコントラクトを取得 near = data.current(context.near, 'contract') far = data.current(context.far, 'contract') target_weights = {} sign_near, sign_far, entry_flag = get_entry_flag(context, data) # nearの満期まであと何日(営業日ベース)残っているか出力(ストラテジーには使っていない. ) todays_date = get_datetime('US/Eastern') context.distance = context.futures_calendar.session_distance(todays_date, near.auto_close_date) log.info(context.distance) #log.info(context.futures_calendar.session_distance(near.auto_close_date, far.auto_close_date)) # entry_flag がFalseのとき,もし,ポジションを持っている場合は,クローズ if not entry_flag: if context.near_short_far_long or context.near_long_far_short: context.near_short_far_long = False context.near_long_far_short = False target_weights[near] = 0.0 target_weights[far] = 0.0 # entry_flag が True, つまり sign_nearとsign_farのフラグが逆の場合. else: # 2と3限月がコンタンゴ,4と5限月がバックワーデーション if sign_near > 0: target_weights[near] = 0.5 * context.levarage target_weights[far] = -0.5 * context.levarage context.near_short_far_long = True # if context.near_short_far_long: # # 既にポジションを持っているので # pass # else: # target_weights[near] = 0.5 # target_weights[far] = -0.5 else: # つまり sign_near < 0 target_weights[near] = -0.5 * context.levarage target_weights[far] = 0.5 * context.levarage context.near_long_far_short = True # if context.near_long_far_short: # pass # else: # target_weights[near] = -0.5 # target_weights[far] = 0.5 if target_weights: order_optimal_portfolio( objective=opt.TargetWeights(target_weights), constraints=[ #opt.MaxGrossExposure(context.levarage) ] )
def rebalance(context, data): """ Execute orders according to our schedule_function() timing. """ predictions = context.predicted_probs # Filter out stocks that can not be traded predictions = predictions.loc[data.can_trade(predictions.index)] # Select top and bottom N stocks n_long_short = min(N_STOCKS_TO_TRADE // 2, len(predictions) // 2) predictions_top_bottom = pd.concat([ predictions.nlargest(n_long_short), predictions.nsmallest(n_long_short), ]) # If classifier predicts many identical values, the top might contain # duplicate stocks predictions_top_bottom = predictions_top_bottom.iloc[ ~predictions_top_bottom.index.duplicated()] # predictions are probabilities ranging from 0 to 1 predictions_top_bottom = (predictions_top_bottom - 0.5) * 2 # pull in the risk factor loadings risk_loadings = context.risk_loadings # Setup Optimization Objective # Factor-weighted portfolio objective = opt.TargetWeights(predictions_top_bottom) # Setup Optimization Constraints constrain_gross_leverage = opt.MaxGrossExposure(1.0) constrain_pos_size = opt.PositionConcentration.with_equal_bounds( -0.02, +0.02, ) market_neutral = opt.DollarNeutral() if predictions_top_bottom.index.duplicated().any(): log.debug(predictions_top_bottom.head()) risk_neutral = opt.experimental.RiskModelExposure( risk_model_loadings=risk_loadings) # Run the optimization. This will calculate new portfolio weights and # manage moving our portfolio toward the target. order_optimal_portfolio( objective=objective, constraints=[ constrain_gross_leverage, constrain_pos_size, market_neutral, risk_neutral ], )
def allocate(context, data): # Set objective to match target weights as closely as possible, given constraints objective = opt.TargetWeights(context.target_weights) # Define constraints constraints = [] constraints.append(opt.MaxGrossExposure(MAX_GROSS_EXPOSURE)) algo.order_optimal_portfolio( objective=objective, constraints=constraints, )
def rebalance_pairs(context, data): crude_oil_price = data.current(context.crude_oil, 'contract') crude_oil_2_price = data.current(context.crude_oil_2, 'contract') # Get target weights to rebalance portfolio target_weights = {} target_weights[crude_oil_price] = -0.5 target_weights[crude_oil_2_price] = 0.5 if target_weights: order_optimal_portfolio(opt.TargetWeights(target_weights), constraints=[])
def rebalance(context, data): output = pipeline_output('pipeline') alpha_factor = output.alpha_factor log.info(alpha_factor) weights = alpha_factor / alpha_factor.abs().sum() order_optimal_portfolio( objective = opt.TargetWeights(weights), constraints = [], )
def rebalance(context, data): """ Execute orders according to our schedule_function() timing. """ # Calculate target weights to rebalance target_weights = compute_target_weights(context, data) # If we have target weights, rebalance portfolio if target_weights: algo.order_optimal_portfolio( objective=opt.TargetWeights(target_weights), constraints=[])
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) if target_weights: # If we have target weights, rebalance portfolio order_optimal_portfolio(opt.TargetWeights(target_weights), constraints=[])
def my_rebalance(context, data): # もしポジションを持っている場合は,ログ出力.(ここはアルゴリズムには不要) cpp = context.portfolio.positions if cpp: df = get_my_position(cpp) log.info('PL: {}'.format(df['PL'].sum())) else: log.info("No position") # target_weight target_weight = {} # 今日のコントラクトを取得 contract_sym1 = data.current(context.sym1, 'contract') contract_sym2 = data.current(context.sym2, 'contract') # 今日のRatioを取得 context.ratio = get_ratio(context, data) context.sma = get_sma(context, data) # ポジションクローズ1 if (context.ratio[-1] < 1.0) and context.long_spread: target_weight[contract_sym1] = 0 target_weight[contract_sym2] = 0 context.holding_days = 0 context.long_spread = False # # ポジションクローズ2 # 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.12 and context.sma[-1] < context.sma[-2]: 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=[] )