def __init__( self, starting_cash, period_open=None, period_close=None, keep_transactions=True, keep_orders=False, serialize_positions=True): self.period_open = period_open self.period_close = period_close self.ending_value = 0.0 self.period_cash_flow = 0.0 self.pnl = 0.0 # sid => position object self.positions = positiondict() self.ending_cash = starting_cash # rollover initializes a number of self's attributes: self.rollover() self.keep_transactions = keep_transactions self.keep_orders = keep_orders # Arrays for quick calculations of positions value self._position_amounts = pd.Series() self._position_last_sale_prices = pd.Series() self.calculate_performance() # An object to recycle via assigning new values # when returning portfolio information. # So as not to avoid creating a new object for each event self._portfolio_store = zp.Portfolio() self._positions_store = zp.Positions() self.serialize_positions = serialize_positions
def ib_portfolio(self): portfolio_store = zp.Portfolio() positions_store = zp.Positions() for acct in self.account.child_accounts: positions = self.portfolio(acct) for pos in positions: # Skip empty requests if hasattr(pos, 'contract'): contract = pos.contract # determine position sid if contract.m_secType == 'STK': sid = contract.m_localSymbol if contract.m_secType == 'FUT': sid = self.__ib_to_aleph_sym_map__(contract) # if sid not in positions create a new position object if sid not in positions_store: if type(sid) is tuple: positions_store[sid] = zp.Position(sid[0], contract=sid[1]) else: positions_store[sid] = zp.Position(sid) positions_store[sid].amount = pos.position_size positions_store[sid].last_sale_price = pos.market_price positions_store[sid].cost_basis = pos.avg_cost else: current_size = positions_store[sid].amount # adjust cost basis: # this should never result in a different value unless # IB doesn't enforce best execution positions_store[sid].amount += pos.position_size if positions_store[sid].amount != 0: mkt_value = positions_store[ sid].cost_basis * current_size added_value = pos.avg_cost * pos.position_size positions_store[sid].cost_basis = (mkt_value + added_value) / \ positions_store[sid].amount portfolio_store.positions_value += pos.market_value portfolio_store.pnl = pos.realized_pnl + pos.unrealized_pnl portfolio_store.positions = positions_store return portfolio_store