Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Time varying bid-ask spread.

In Help there is a possibility to add bid ask spread in place of slippage. Code is

# Provide the bid-ask spread for each of the securities in the universe.  
    spreads = {  
        sid(24): 0.05,  
        sid(3766): 0.08  
    }  

I assume it is possible to load data frame of time varying bid-ask spread using fetch_csv. That does one need to change? Because I'm getting mistakes
out of code

 # Load bid-ask spread.

    spreads = fetch_csv('https://dl.dropboxusercontent.com/u/406893222/BAS.csv',  
             date_column = 'date',  
             date_format = '%d.%m.%y',  
             post_func=rename_col,  
             symbol = 'spr')  

KeyError: 'symbol'

Update. code of rename col is

def rename_col(df):  
    df = df.rename(columns={'bas': sid(33655)})  
    # df = df.fillna(method='ffill') # fill missing  
    #df = df[[sid(33655)]]  
    # Correct look-ahead bias in mapping data to times  
    #df = df.tshift(1, freq='b')  
    log.info(' \n %s ' % df.head())  
    return df  
7 responses

May be there is way how to access my fetched data in initialize function.

Could you share the full code here (using the code sample tool)? Or invite me as a collaborator ([email protected]) to the algo?

Seeing the full code will be easier to spot and fix the error. Thanks!

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

collaborated. Thanks.
After post I tried to make it work, so some lines of code might be a bit different from the one given here.

# 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  

Thanks for the collab invite and also sharing your code here. You were running into an error because fetch_csv always returns "None", regardless of the inputs it receives.

A way around this is to create "spreads" as a dictionary in initialize(), pass it to set_slippage, and then update the state in handle_data() via context.

Something like this as a skeleton structure,

class PerStockSpreadSlippage(slippage.SlippageModel):  
  # your custom slippage model

initialize(context):  
  context.spreads = {}  
  set_slippage(PerStockSpreadSlippage(spreads))

handle_data(context,data):  
   #update context.spreads  

Thanks, but it seems that slippage object uses value which was initialized with. I can force context.spreads to change but spreads in the slippage object is either {} and produces error or if I specify some initial value {sid(33655): 0.0123} then this value is used permanently.

So the question is how to change values of spreads in slippage object?
May be there is possibility to use pointer to context.spreads as an argument of set_slippage(PerStockSpreadSlippage(spreads))

Got it using pointer class

# pointer class to update slippage  
class ref:  
    def __init__(self, obj): self.obj = obj  
    def get(self):    return self.obj  
    def set(self, obj):      self.obj = obj