Exemplo n.º 1
0
    def get_positions(self):

        positions = self._positions_store

        for sid, pos in iteritems(self.positions):

            if pos.amount == 0:
                # Clear out the position if it has become empty since the last
                # time get_positions was called.  Catching the KeyError is
                # faster than checking `if sid in positions`, and this can be
                # potentially called in a tight inner loop.
                try:
                    del positions[sid]
                except KeyError:
                    pass
                continue

            position = zp.Position(sid)
            position.amount = pos.amount
            position.cost_basis = pos.cost_basis
            position.last_sale_price = pos.last_sale_price
            position.last_sale_date = pos.last_sale_date

            # Adds the new position if we didn't have one before, or overwrite
            # one we have currently
            positions[sid] = position

        return positions
Exemplo n.º 2
0
    def positions(self):
        z_positions = zp.Positions()

        positions = self.api_client.Position.Position_get().result()[0][0]
        position_map = {}
        symbols = []
        for pos in positions:
            symbol = pos['symbol']
            try:
                z_position = zp.Position(symbol_lookup(symbol))
            except SymbolNotFound:
                continue
            z_position.amount = pos['currentQty']
            z_position.cost_basis = float(pos['currentCost'])
            z_position.last_sale_price = None
            z_position.last_sale_date = None
            z_positions[symbol_lookup(symbol)] = z_position
            symbols.append(symbol)
            position_map[symbol] = z_position

        quotes = self.ws_client.recent_trades()
        for quote in quotes:
            if quote['symbol'] != 'XBTUSD':
                continue
            price = quote['price']
            dt = quote['timestamp']
            z_position = position_map[quote['symbol']]
            z_position.last_sale_price = float(price)
            z_position.last_sale_date = dt
        return z_positions
Exemplo n.º 3
0
    def positions(self):
        z_positions = zp.Positions()
        positions = self._api.list_positions()
        position_map = {}
        symbols = []
        for pos in positions:
            symbol = pos.symbol
            try:
                z_position = zp.Position(symbol_lookup(symbol))
            except SymbolNotFound:
                continue
            z_position.amount = pos.qty
            z_position.cost_basis = float(pos.cost_basis)
            z_position.last_sale_price = None
            z_position.last_sale_date = None
            z_positions[symbol_lookup(symbol)] = z_position
            symbols.append(symbol)
            position_map[symbol] = z_position

        quotes = self._api.list_quotes(symbols)
        for quote in quotes:
            price = quote.last
            dt = quote.last_timestamp
            z_position = position_map[quote.symbol]
            z_position.last_sale_price = float(price)
            z_position.last_sale_date = dt
        return z_positions
Exemplo n.º 4
0
    def positions(self):
        curr_pos = self.get_latest_positions()

        z_positions = zp.Positions()
        # TODO: check/test this for loop
        for index, symbol in curr_pos['holding_name'].iteritems():
            vb_position = curr_pos[curr_pos['holding_name'] == symbol]
            try:
                z_position = zp.Position(symbol_lookup(symbol))
            except SymbolNotFound:
                # The symbol might not have been ingested to the db therefore
                # it needs to be skipped.
                continue
            # Amount = quantity
            z_position.amount = int(vb_position.quantity)
            z_position.cost_basis = float(vb_position.buy_price)
            # Check if symbol exists in bars df
            if symbol in self._tws.bars:
                z_position.last_sale_price = \
                    float(self._tws.bars[symbol].last_trade_price.iloc[-1])
                z_position.last_sale_date = \
                    self._tws.bars[symbol].index.values[-1]
            else:
                z_position.last_sale_price = None
                z_position.last_sale_date = None
            z_positions[symbol_lookup(symbol)] = z_position

        return z_positions
Exemplo n.º 5
0
    def get_positions(self):

        positions = self._positions_store

        for sid, pos in self.positions.iteritems():
            if sid not in positions:
                positions[sid] = zp.Position(sid)
            position = positions[sid]
            position.amount = pos.amount
            position.cost_basis = pos.cost_basis
            position.last_sale_price = pos.last_sale_price

        return positions
Exemplo n.º 6
0
    def _get_positions_from_broker(self):
        """
        get the positions from the broker and update zipline objects ( the ledger )
        should be used once at startup and once every time we want to refresh the positions array
        """
        cur_pos_in_tracker = self.metrics_tracker.positions
        positions = self._api.list_positions()
        for ap_position in positions:
            # ap_position = positions[symbol]
            try:
                z_position = zp.Position(
                    zp.InnerPosition(symbol_lookup(ap_position.symbol)))
                editable_position = zp.MutableView(z_position)
            except SymbolNotFound:
                # The symbol might not have been ingested to the db therefore
                # it needs to be skipped.
                log.warning(
                    'Wanted to subscribe to %s, but this asset is probably not ingested'
                    % ap_position.symbol)
                continue
            if int(ap_position.qty) == 0:
                continue
            editable_position._underlying_position.amount = int(
                ap_position.qty)
            editable_position._underlying_position.cost_basis = float(
                ap_position.avg_entry_price)
            editable_position._underlying_position.last_sale_price = float(
                ap_position.current_price)
            editable_position._underlying_position.last_sale_date = self._api.get_last_trade(
                ap_position.symbol).timestamp

            self.metrics_tracker.update_position(
                z_position.asset,
                amount=z_position.amount,
                last_sale_price=z_position.last_sale_price,
                last_sale_date=z_position.last_sale_date,
                cost_basis=z_position.cost_basis)

        # now let's sync the positions in the internal zipline objects
        position_names = [p.symbol for p in positions]
        assets_to_update = [
        ]  # separate list to not change list while iterating
        for asset in cur_pos_in_tracker:
            if asset.symbol not in position_names:
                assets_to_update.append(asset)
        for asset in assets_to_update:
            # deleting object from the metrics_tracker as its not in the portfolio
            self.metrics_tracker.update_position(asset, amount=0)
        # for some reason, the metrics tracker has self.positions AND self.portfolio.positions. let's make sure
        # these objects are consistent
        self.metrics_tracker._ledger._portfolio.positions = self.metrics_tracker.positions
Exemplo n.º 7
0
 def __init__(
     self, asset, amount=0, cost_basis=0.0, last_sale_price=0.0, last_sale_date=None
 ):
     inner = zp.InnerPosition(
         asset=asset,
         amount=amount,
         cost_basis=cost_basis,
         last_sale_price=last_sale_price,
         last_sale_date=last_sale_date,
         pnl_realized=PnlRealized(),
         lots=set(),
     )
     object.__setattr__(self, "inner_position", inner)
     object.__setattr__(self, "protocol_position", zp.Position(inner))
Exemplo n.º 8
0
    def positions(self):
        now = datetime.datetime.now()
        z_positions = protocol.Positions()
        for row in self._client.query_data(SHARES).iteritems():
            sid = row["证券代码"].values[0]
            available = row["可用数量"].values[0]
            z_position = protocol.Position(symbol(sid))
            z_position.amount = row["证券数量"].values[0]
            z_position.cost_basis = row["成本价"].values[0]
            z_position.last_sale_price = row["当前价"].values[0]
            z_position.last_sale_date = now
            z_positions[symbol(sid)] = z_position

        return z_positions
Exemplo n.º 9
0
 def __init__(self,
              asset,
              amount=0,
              cost_basis=0.0,
              last_sale_price=0.0,
              last_sale_date=None):
     inner = zp.InnerPosition(
         asset=asset,
         amount=amount,
         cost_basis=cost_basis,
         last_sale_price=last_sale_price,
         last_sale_date=last_sale_date,
     )
     object.__setattr__(self, 'inner_position', inner)
     object.__setattr__(self, 'protocol_position', zp.Position(inner))
Exemplo n.º 10
0
    def positions(self):
        now = datetime.datetime.now()
        z_positions = protocol.Positions()
        for pos in self._shipane_client.positions():
            if isinstance(pos, list):
                pos = TdxPosition(*pos)
            sid = pos.sid
            available = pos.available
            z_position = protocol.Position(symbol(sid))
            z_position.amount = pos.amount
            z_position.cost_basis = pos.cost_basis
            z_position.last_sale_price = pos.last_sale_price
            z_position.last_sale_date = now
            z_positions[symbol(sid)] = z_position

        return z_positions
Exemplo n.º 11
0
    def positions(self):
        z_positions = zp.Positions()
        for symbol in self._tws.positions:
            ib_position = self._tws.positions[symbol]
            try:
                z_position = zp.Position(symbol_lookup(symbol))
            except SymbolNotFound:
                log.warn("Symbol {} not found in the data base.", symbol)
                continue
            z_position.amount = int(ib_position.position)
            z_position.cost_basis = float(ib_position.market_price)
            z_position.last_sale_price = None  # TODO(tibor): Fill from state
            z_position.last_sale_date = None  # TODO(tibor): Fill from state
            z_positions[symbol_lookup(symbol)] = z_position

        return z_positions
Exemplo n.º 12
0
 def _get_positions_from_broker(self):
     """
     get the positions from the broker and update zipline objects ( the ledger )
     should be used once at startup and once every time we want to refresh the positions array
     """
     cur_pos_in_tracker = self.metrics_tracker.positions
     for symbol in self._tws.positions:
         ib_position = self._tws.positions[symbol]
         try:
             z_position = zp.Position(
                 zp.InnerPosition(symbol_lookup(symbol)))
             editable_position = MutableView(z_position)
         except SymbolNotFound:
             # The symbol might not have been ingested to the db therefore
             # it needs to be skipped.
             log.warning(
                 'Wanted to subscribe to %s, but this asset is probably not ingested'
                 % symbol)
             continue
         editable_position._underlying_position.amount = int(
             ib_position.position)
         editable_position._underlying_position.cost_basis = float(
             ib_position.average_cost)
         # Check if symbol exists in bars df
         if symbol in self._tws.bars:
             editable_position._underlying_position.last_sale_price = \
                 float(self._tws.bars[symbol].last_trade_price.iloc[-1])
             editable_position._underlying_position.last_sale_date = \
                 self._tws.bars[symbol].index.values[-1]
         else:
             # editable_position._underlying_position.last_sale_price = None  # this cannot be set to None. only numbers.
             editable_position._underlying_position.last_sale_date = None
         self.metrics_tracker.update_position(
             z_position.asset,
             amount=z_position.amount,
             last_sale_price=z_position.last_sale_price,
             last_sale_date=z_position.last_sale_date,
             cost_basis=z_position.cost_basis)
     for asset in cur_pos_in_tracker:
         if asset.symbol not in self._tws.positions:
             # deleting object from the metrcs_tracker as its not in the portfolio
             self.metrics_tracker.update_position(asset, amount=0)
     # for some reason, the metrics tracker has self.positions AND self.portfolio.positions. let's make sure
     # these objects are consistent
     # (self.portfolio.positions is self.metrics_tracker._ledger._portfolio.positions)
     # (self.metrics_tracker.positions is self.metrics_tracker._ledger.position_tracker.positions)
     self.metrics_tracker._ledger._portfolio.positions = self.metrics_tracker.positions
Exemplo n.º 13
0
    def positions(self):
        z_positions = zp.Positions()
        for symbol in self._tws.positions:
            ib_position = self._tws.positions[symbol]
            try:
                z_position = zp.Position(symbol_lookup(symbol))
            except SymbolNotFound:
                # The symbol might not have been ingested to the db therefore
                # it needs to be skipped.
                continue
            z_position.amount = int(ib_position.position)
            z_position.cost_basis = float(ib_position.market_price)
            z_position.last_sale_price = None  # TODO(tibor): Fill from state
            z_position.last_sale_date = None  # TODO(tibor): Fill from state
            z_positions[symbol_lookup(symbol)] = z_position

        return z_positions
Exemplo n.º 14
0
    def _get_positions_from_broker(self):
        """
        get the positions from the broker and update zipline objects ( the ledger )
        should be used once at startup and once every time we want to refresh the positions array
        """
        cur_pos_in_tracker = self.metrics_tracker.positions
        for ib_symbol in self._tws.ib_positions:
            ib_position = self._tws.ib_positions[ib_symbol]

            equity = self._safe_symbol_lookup(ib_symbol)
            if not equity:
                log.warning(
                    'Wanted to subscribe to %s, but this asset is probably not ingested'
                    % ib_symbol)
                continue

            zp_position = zp.Position(zp.InnerPosition(equity))
            editable_position = MutableView(zp_position)

            editable_position._underlying_position.amount = int(
                ib_position.position)
            editable_position._underlying_position.cost_basis = float(
                ib_position.average_cost)
            editable_position._underlying_position.last_sale_price = ib_position.market_price
            last_close = self.metrics_tracker._trading_calendar.session_close(
                self.metrics_tracker._last_session)
            editable_position._underlying_position.last_sale_date = last_close

            self.metrics_tracker.update_position(
                zp_position.asset,
                amount=zp_position.amount,
                last_sale_price=zp_position.last_sale_price,
                last_sale_date=zp_position.last_sale_date,
                cost_basis=zp_position.cost_basis)
        for asset in cur_pos_in_tracker:
            ib_symbol = self._asset_symbol(asset)
            if ib_symbol not in self._tws.ib_positions:
                # deleting object from the metrcs_tracker as its not in the portfolio
                self.metrics_tracker.update_position(asset, amount=0)

        self.metrics_tracker._ledger._portfolio.positions = zp.Positions(
            self.metrics_tracker.positions)
Exemplo n.º 15
0
    def get_positions(self):

        positions = self._positions_store

        for sid, pos in iteritems(self.positions):
            if pos.amount != 0 and sid not in positions:
                positions[sid] = zp.Position(sid)
            position = positions[sid]
            position.amount = pos.amount
            position.cost_basis = pos.cost_basis
            position.last_sale_price = pos.last_sale_price

            # Remove positions with no amounts from portfolio container
            # that is passed to the algorithm.
            # These positions are still stored internally for use with
            # dividends etc.
            if pos.amount == 0 and sid in positions:
                del positions[sid]

        return positions
Exemplo n.º 16
0
    def positions(self):
        z_positions = zp.Positions()
        for symbol in self._tws.positions:
            ib_position = self._tws.positions[symbol]
            try:
                z_position = zp.Position(symbol_lookup(symbol))
            except SymbolNotFound:
                # The symbol might not have been ingested to the db therefore
                # it needs to be skipped.
                continue
            z_position.amount = int(ib_position.position)
            z_position.cost_basis = float(ib_position.average_cost)
            # Check if symbol exists in bars df
            if symbol in self._tws.bars:
                z_position.last_sale_price = \
                    float(self._tws.bars[symbol].last_trade_price.iloc[-1])
                z_position.last_sale_date = \
                    self._tws.bars[symbol].index.values[-1]
            else:
                z_position.last_sale_price = None
                z_position.last_sale_date = None
            z_positions[symbol_lookup(symbol)] = z_position

        return z_positions