# Our custom slippage model
class PerStockSpreadSlippage(slippage.SlippageModel):
# We specify the constructor so that we can pass state to this class, but this is optional.
def __init__(self, spreads):
# Store a dictionary of spreads, keyed by sid.
self.spreads = spreads
#def __getitem__(self, date):
# return self.spreads[date]
def process_order(self, trade_bar, order):
spread = self.spreads[order.sid]
# In this model, the slippage is going to be half of the spread for
# the particular stock
slip_amount = spread / 2
# Compute the price impact of the transaction. Size of price impact is
# proprotional to order size.
# A buy will increase the price, a sell will decrease it.
new_price = trade_bar.price + (slip_amount * order.direction)
log.info('executing order ' + str(trade_bar.sid) + ' stock bar price: ' + \
str(trade_bar.price) + ' and trade executes at: ' + str(new_price))
# Create the transaction using the new price we've calculated.
return slippage.create_transaction(
trade_bar,
order,
new_price,
order.amount
)
def initialize(context):
set_symbol_lookup_date('2007-04-11') # Set Symbol detection date. Because there are two securities with symbol 'HYG'
set_benchmark(symbol('HYG')) # Set benchmark
# In our example, we're looking at High yield ETF.
context.security = symbol('HYG')
# Load forecasts from dropbox
fetch_csv('https://dl.dropboxusercontent.com/u/406893222/Forecast.csv',
date_column = 'date',
date_format = '%d.%m.%y',
symbol = 'forc')
# Load bid-ask spread
spreads=fetch_csv('https://dl.dropboxusercontent.com/u/406893222/BAS.csv',
date_column = 'date',
symbol = 'HYG1',
date_format = '%d.%m.%y')
# Provide the bid-ask spread for each of the securities in the universe.
#spreads = {
# sid(33655): 0.3134
#}
# These are the default slippage settings
# set_slippage(slippage.VolumeShareSlippage(volume_limit=1, price_impact=0.0))
set_commission(commission.PerTrade(cost=0.0))
# Initialize slippage settings given the parameters of our model
set_slippage(PerStockSpreadSlippage(spreads))
def handle_data(context, data):
# We've built a handful of useful data transforms for you to use,
# such as moving average.
# To make market decisions, we're calculating the stock's
# moving average for the last 5 days and its current price.
if 'Signals' in data['forc']:
cforc = data['forc']['Signals']
cprice = data[context.security].price
cash = context.portfolio.cash
if (not has_orders(context.security)):
# Here is the meat of our algorithm.
if cforc > 0 and cash > cprice:
# Place the buy order (positive means buy, negative means sell)
order_value(context.security, cash)
log.info("Buying %s" % (context.security.symbol))
elif cforc < 0 and context.portfolio.positions[context.security].amount > 0:
# Sell all of our shares by setting the target position to zero
order_target(context.security, 0)
log.info("Selling %s" % (context.security.symbol))
# You can use the record() method to track any custom signal.
record(value = context.portfolio.portfolio_value)
# print ntrades
def has_orders(sec):
# Return true if there are pending orders.
has_orders = False
orders = get_open_orders(sec)
if orders:
for oo in orders:
message = 'Open order for {amount} shares in {stock}'
message = message.format(amount=oo.amount, stock=sec)
log.info(message)
has_orders = True
return has_orders