Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Class for tracking Margins

I quantopified a class for tracking margins I worked on in zipline a while ago since it's difficult to write code that can be cut/pasted between the two.

It keeps a dict of position margins and the portfolio margin. It logs the data nice and pretty for you too, Enjoy!

import pandas as pd


class Margins(object):  
    '''  
    Calculates portfolio minimum margin requirement and  
    keeps a dict of the requirement for each position.  
    '''

    def __init__(self, context, data, day_trader=False):  
        self.initial_margin = 25000.0 if day_trader else 2000.0  
        self.position_margins = {}  
        for stock in data.keys():  
            self.position_margins[stock] = \  
                self.position_requirement(context.portfolio.positions[stock])  
        self.requirement = sum(self.position_margins.values())

    def position_requirement(self, position):  
        amount = position.amount  
        last_sale_price = position.last_sale_price  
        if amount >= 0:  
            req = .25 * amount * last_sale_price  
        else:  
            if last_sale_price < 5:  
                req = max(2.5 * amount, abs(amount * last_sale_price))  
            else:  
                req = max(5 * amount, abs(0.3 * amount * last_sale_price))  
        return req

    def __repr__(self):  
        template = "\nSymbol  Requirement\n{position_margins}\nMargin Requirement: {req}"  
        return template.format(  
            position_margins=pd.Series(  
                {i.symbol : self.position_margins[i]  
                 for i in self.position_margins}),  
            req=self.requirement)

    def __getitem__(self, item):  
        return self.position_margins[item]  
4 responses

Thanks David,

Looking forward to trying it. Do you have a use-case example algorithm you could plug it into, that you'd be willing to share (it could be a trivial one)?

Also, how does your code map onto Interactive Brokers practices and regulatory requirements?

Grant

I tossed it in an efficient frontier type of algo. The use case is a little unrealistic and not implemented very well but the idea is that if the algo ends up outside of its margin requirements, it will cover any shorts that have made money. If it's still outside of the reqs it sells long positions that are up until it is back under the requirement. Its unrealistic because that won't always get the algo back within regs. I'm sure there's a lot of different thoughts on how to handle a margin call, but it would be ideal to catch and handle them yourself before IB liquidates positions on your behalf. I'm pretty sure I didn't use the right calculations for adding the equity and subtracting the margin req as it sell off BTW.

As for mapping onto IB, it uses the FINRA rules for minimum margin requirements. IB does use the same basic rules but has some rules of their own. They some SMA calculation that I have not really looked at, it's described here. It should be treated as an absolute minimum requirement, I'd add a safety cushion to make sure they don't beat you to liquidating positions.

Thanks David,

I'll have a look when I get the chance. Should be of interest to others, as well.

--Grant

Hi, I wanted to use this framework recently, and ran into following error:
" Cannot use built-in function getitem. Why?"

For security reasons Q blocks these functions. Is there a workaround?

Thanks