예제 #1
0
    def _get_broker_positions(self, ):

        StockPosition = self._env.get_position_model(
            DEFAULT_ACCOUNT_TYPE.STOCK.name)
        positions = Positions(StockPosition)
        resultData, returnMsg = self._trade_api.get_positions()

        if returnMsg['code'] != 0 or resultData is None:
            return positions

        for poData in resultData:
            security_id, exchange_id = poData['order_book_id'].split(".")
            # convert to rqalpha style
            if exchange_id == "SH":
                exchange_id = "XSHG"
            if exchange_id == "SZ":
                exchange_id = "XSHE"

            order_book_id = security_id + "." + exchange_id

            poItem = positions.get_or_create(order_book_id)
            poItem.set_state({
                "order_book_id": order_book_id,
                "quantity": poData['prev_qty'],  # poData["position_qty"],
                "avg_price": poData['prev_avgPx'],  # poData["position_avgPx"],
                "non_closable": 0,
                "frozen": 0,
                "transaction_cost": 0
            })
            poItem.prev_qty = poData['prev_qty']
            poItem.prev_avgPx = poData['prev_avgPx']
        return positions
예제 #2
0
def init_portfolio(env):
    accounts = {}
    config = env.config
    start_date = datetime.datetime.combine(config.base.start_date, datetime.time.min)
    units = 0

    if config.base.init_positions or (DEFAULT_ACCOUNT_TYPE.FUTURE.name in config.base.accounts and
                                      config.base.frequency != '1d'):
        BaseAccount.AGGRESSIVE_UPDATE_LAST_PRICE = True

    for account_type, starting_cash in six.iteritems(config.base.accounts):
        if starting_cash == 0:
            raise RuntimeError(_(u"{} starting cash can not be 0, using `--account {} 100000`").format(account_type, account_type))

        account_model = env.get_account_model(account_type)
        position_model = env.get_position_model(account_type)
        positions = Positions(position_model)

        for order_book_id, quantity in _filter_positions(env, account_type):
            instrument = env.get_instrument(order_book_id)
            if instrument is None:
                raise RuntimeError(_(u'invalid order book id {} in initial positions').format(order_book_id))
            if not instrument.listing:
                raise RuntimeError(_(u'instrument {} in initial positions is not listing').format(order_book_id))

            bars = env.data_proxy.history_bars(order_book_id, 1, '1d', 'close',
                                               env.data_proxy.get_previous_trading_date(start_date),
                                               adjust_type='none')
            if bars is None:
                raise RuntimeError(_(u'the close price of {} in initial positions is not available').format(order_book_id))

            price = bars[0]
            trade = _fake_trade(order_book_id, quantity, price)
            if order_book_id not in positions:
                positions[order_book_id] = position_model(order_book_id)
            positions[order_book_id].apply_trade(trade)
            # FIXME
            positions[order_book_id]._last_price = price

        # 变成昨仓
        for order_book_id, position in positions.items():
            position.apply_settlement()

        account = account_model(starting_cash, positions)
        units += account.total_value
        accounts[account_type] = account

    return Portfolio(config.base.start_date, 1, units, accounts)
예제 #3
0
 def positions(self):
     PositionModel = self._position_model
     ps = Positions(PositionModel)
     for order_book_id, pos_dict in self.pos.items():
         position = RealtimePosition(order_book_id)
         position.set_state(pos_dict)
         ps[order_book_id] = position
     return ps
예제 #4
0
 def _get_futu_positions(self, env):
     StockPosition = env.get_position_model(DEFAULT_ACCOUNT_TYPE.STOCK.name)
     positions = Positions(StockPosition)
     ret, pd_data = self._trade_context.position_list_query(self._trade_envtype)
     if ret != 0:
         return None
     for i in range(len(pd_data)):
         row = pd_data.iloc[i]
         code_str = str(row['code'])
         pos_state = {}
         pos_state['order_book_id'] = code_str
         pos_state['quantity'] = int(row['qty'])
         pos_state['avg_price'] = float(row['cost_price'])
         pos_state['non_closable'] = 0
         pos_state['frozen'] = int(row['qty']) - int(row['can_sell_qty'])
         pos_state['transaction_cost'] = 0
         item = positions.get_or_create(code_str)
         item.set_state(pos_state)
     return positions
예제 #5
0
def create_benchmark_portfolio(env):
    if env.config.base.benchmark is None:
        return None

    BenchmarkAccount = env.get_account_model(const.DEFAULT_ACCOUNT_TYPE.BENCHMARK.name)
    BenchmarkPosition = env.get_position_model(const.DEFAULT_ACCOUNT_TYPE.BENCHMARK.name)

    start_date = env.config.base.start_date
    total_cash = sum(env.config.base.accounts.values())
    accounts = {
        const.DEFAULT_ACCOUNT_TYPE.BENCHMARK.name: BenchmarkAccount(total_cash, Positions(BenchmarkPosition))
    }
    return Portfolio(start_date, 1, total_cash, accounts)
예제 #6
0
def init_portfolio(env):
    accounts = {}
    config = env.config
    start_date = config.base.start_date
    total_cash = 0

    if DEFAULT_ACCOUNT_TYPE.FUTURE.name in config.base.accounts and config.base.frequency != '1d':
        BaseAccount.AGGRESSIVE_UPDATE_LAST_PRICE = True

    for account_type, starting_cash in six.iteritems(config.base.accounts):
        if account_type == DEFAULT_ACCOUNT_TYPE.STOCK.name:
            if starting_cash == 0:
                raise RuntimeError(
                    _(u"stock starting cash can not be 0, using `--account stock 100000`"
                      ))
            StockAccount = env.get_account_model(
                DEFAULT_ACCOUNT_TYPE.STOCK.name)
            StockPosition = env.get_position_model(
                DEFAULT_ACCOUNT_TYPE.STOCK.name)
            accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name] = StockAccount(
                starting_cash, Positions(StockPosition))
            total_cash += starting_cash
        elif account_type == DEFAULT_ACCOUNT_TYPE.FUTURE.name:
            if starting_cash == 0:
                raise RuntimeError(
                    _(u"future starting cash can not be 0, using `--account future 100000`"
                      ))
            FutureAccount = env.get_account_model(
                DEFAULT_ACCOUNT_TYPE.FUTURE.name)
            FuturePosition = env.get_position_model(
                DEFAULT_ACCOUNT_TYPE.FUTURE.name)
            accounts[DEFAULT_ACCOUNT_TYPE.FUTURE.name] = FutureAccount(
                starting_cash, Positions(FuturePosition))
            total_cash += starting_cash
        else:
            raise NotImplementedError
    return Portfolio(start_date, 1, total_cash, accounts)
예제 #7
0
    def positions(self):
        PositionModel = self._position_model
        ps = Positions(PositionModel)
        for order_book_id, pos_dict in iteritems(self.pos):
            position = PositionModel(order_book_id)

            position._buy_old_holding_list = [(pos_dict.prev_settle_price,
                                               pos_dict.buy_old_quantity)]
            position._sell_old_holding_list = [(pos_dict.prev_settle_price,
                                                pos_dict.sell_old_quantity)]

            position._buy_transaction_cost = pos_dict.buy_transaction_cost
            position._sell_transaction_cost = pos_dict.sell_transaction_cost
            position._buy_realized_pnl = pos_dict.buy_realized_pnl
            position._sell_realized_pnl = pos_dict.sell_realized_pnl

            position._buy_avg_open_price = pos_dict.buy_avg_open_price
            position._sell_avg_open_price = pos_dict.sell_avg_open_price

            if order_book_id in self.trades:
                trades = sorted(self.trades[order_book_id],
                                key=lambda t: t.trade_id,
                                reverse=True)

                buy_today_holding_list = []
                sell_today_holding_list = []
                for trade_dict in trades:
                    if trade_dict.side == SIDE.BUY and trade_dict.position_effect == POSITION_EFFECT.OPEN:
                        buy_today_holding_list.append(
                            (trade_dict.price, trade_dict.quantity))
                    elif trade_dict.side == SIDE.SELL and trade_dict.position_effect == POSITION_EFFECT.OPEN:
                        sell_today_holding_list.append(
                            (trade_dict.price, trade_dict.quantity))

                self.process_today_holding_list(pos_dict.buy_today_quantity,
                                                buy_today_holding_list)
                self.process_today_holding_list(pos_dict.sell_today_quantity,
                                                sell_today_holding_list)

                position._buy_today_holding_list = buy_today_holding_list
                position._sell_today_holding_list = sell_today_holding_list

            ps[order_book_id] = position
        return ps
예제 #8
0
 def _get_positions(self, env):
     StockPosition = env.get_position_model(DEFAULT_ACCOUNT_TYPE.STOCK.name)
     positions = Positions(StockPosition)
     # TODO:
     return positions
예제 #9
0
    def init_fixture(self):
        from rqalpha.model.base_position import Positions
        from rqalpha.mod.rqalpha_mod_sys_accounts.position_model.stock_position import StockPosition
        from rqalpha.mod.rqalpha_mod_sys_accounts.account_model import BenchmarkAccount

        super(BenchmarkAccountFixture, self).init_fixture()

        self.benchmark_account = BenchmarkAccount(self.benchmark_account_total_cash,  Positions(StockPosition))