Hi everyone,
I am trying to build a simple algo that would buy when the market make a gap up of more than 3% but I have some trouble to implement a stop loss.
Any idea ?
Thanks
Chris
import numpy as np
import pandas as pd
def initialize(context):
set_universe(universe.DollarVolumeUniverse(floor_percentile=95.0, ceiling_percentile=100.0))
context.stop_price = 0
context.stop_pct = 0.99
schedule_function(
func=market_open,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_open(hours=0, minutes=5),
half_days=True)
schedule_function(
func=close_all_positions,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_close(hours=0, minutes=5),
half_days=True)
# Set execution cost assumptions. For live trading with Interactive Brokers
# we will assume a $1.00 minimum per trade fee, with a per share cost of $0.0075.
set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.00))
# Set market impact assumptions. We limit the simulation to
# trade up to 2.5% of the traded volume for any one minute,
# and our price impact constant is 0.1.
set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.10))
def market_open(context, data):
for stock in data:
price_history = history(bar_count=5, frequency='1d', field='price')
#close_2_day_ago = price_history[data.stock][-3] # close two days ago
close_yesterday = price_history[stock][-2] # close of yesterday
open_today = price_history[stock][-1]
cash = context.portfolio.cash
nb_of_shares = int(cash / open_today)
#target_shares = cash / stock.price
gap_percent = (open_today / close_yesterday - 1)
#log.info('Percent change {}'.format(gap_percent))
### ENTRY ###
if gap_percent > 0.03 and len(get_open_orders()) == 0:
order(stock, nb_of_shares)
log.info('Bought {} shares of {}'.format(nb_of_shares, stock.symbol))
def handle_data(context, data):
set_stop_loss(context, data)
if data[context.stock].price < context.stop_price:
order_target(context.stock, 0)
def set_stop_loss(context, data):
if context.portfolio.positions[context.stock].amount:
price = data[context.stock].price
context.stop_price = context.stop_pct * price
def close_all_positions(context, data):
for stock in data:
current_positions = context.portfolio.positions
if current_positions != 0:
order_target_percent(stock, 0)
log.info('cover before the close of the day')