查询分笔成交

        :param market: 市场代码
        :param symbol: 股票代码
        :param start: 起始位置
        :param offset: 请求数量
        :return: pd.dataFrame or None
552339
def trans(self, symbol='', start=0, offset=10):
        '''
        
        '''
        market = get_stock_market(symbol)

        with self.client.connect(*self.bestip):
            data = self.client.get_transaction_data(
                int(market), symbol, int(start), int(market))
            return self.client.to_df(data)
636409
def main(symbol: str):
    
    print("Displaying the balance for", symbol)

    with BookAggregate() as svc:
        security = svc.book.get(Commodity, mnemonic=symbol)
		#security.transactions, security.prices

        sec_svc = SecurityAggregate(svc.book, security)

        # Display number of shares
        shares_no = sec_svc.get_quantity()
        print("Quantity:", shares_no)

        # Calculate average price.
        avg_price = sec_svc.get_avg_price()
        print("Average price:", avg_price)
955519
def buy_on_drop(symbol_set="sp5002012", 
            dataobj=dataobj, 
            start=datetime.datetime(2008, 1, 3), 
            end=datetime.datetime(2009, 12, 28),
            market_sym='$SPX',
            threshold=6,
            sell_delay=5,
            ):
    ''''''
    if symbol_set:
        if isinstance(symbol_set, basestring):
            if symbol_set.lower().startswith('sp'):
                symbol_set = dataobj.get_symbols_from_list(symbol_set.lower())
            else:
                symbol_set = [sym.stip().upper() for sym in symbol_set.split(",")]
    else:
        symbol_set = dataobj.get_symbols_from_list("sp5002012")
    if market_sym:
        symbol_set.append(market_sym)

    print "Starting Event Study, retrieving data for the {0} symbol list...".format(symbol_set)
    market_data = get_clean_prices(symbol_set, dataobj=dataobj, start=start, end=end)
    print "Finding events for {0} symbols between {1} and {2}...".format(len(symbol_set), start, end)
    trigger_kwargs={'threshold': threshold}
    events = find_events(symbol_set, market_data,  market_sym=market_sym, trigger=drop_below, trigger_kwargs=trigger_kwargs)

    csvwriter = csv.writer(getattr(args, 'outfile', open('buy_on_drop_outfile.csv', 'w')), dialect='excel', quoting=csv.QUOTE_MINIMAL)
    for order in generate_orders(events, sell_delay=sell_delay, sep=None):
        csvwriter.writerow(order)

    print "Creating Study report for {0} events...".format(len(events))
    ep.eventprofiler(events, market_data, 
                         i_lookback=20, i_lookforward=20,
                         s_filename='Event report--buy on drop below {0} for {1} symbols.pdf'.format(threshold, len(symbol_set)),
                         b_market_neutral=True,
                         b_errorbars=True,
                         s_market_sym=market_sym,
                         )
    return events
797877
def _index_range(self, version, symbol, date_range=None, **kwargs):
        
        if date_range and 'segment_index' in version:
            # index is read-only but it's never written to
            index = np.frombuffer(decompress(version['segment_index']), dtype=INDEX_DTYPE)
            dtcol = self._datetime64_index(index)
            if dtcol and len(index):
                dts = index[dtcol]
                start, end = _start_end(date_range, dts)
                if start > dts[-1]:
                    return -1, -1
                idxstart = min(np.searchsorted(dts, start), len(dts) - 1)
                idxend = min(np.searchsorted(dts, end, side='right'), len(dts) - 1)
                return int(index['index'][idxstart]), int(index['index'][idxend] + 1)
        return super(PandasStore, self)._index_range(version, symbol, **kwargs)
1132742
def parse_market(self, market, split_char='_'):
        
        crypto, fiat = market.lower().split(split_char)
        return (
            self.fix_symbol(crypto, reverse=True),
            self.fix_symbol(fiat, reverse=True)
        )
367263
def trade_signals_handler(self, signals):
        '''
        
        '''
        alloc = {}

        if signals['buy'] or signals['sell']:
            # Compute the optimal portfolio allocation,
            # Using user defined function
            try:
                alloc, e_ret, e_risk = self.optimize(
                    self.date, signals['buy'], signals['sell'],
                    self._optimizer_parameters)
            except Exception, error:
                raise PortfolioOptimizationFailed(
                    reason=error, date=self.date, data=signals)
        return _remove_useless_orders(alloc)
595257
def _example_get_trade_days(quote_ctx):
    
    ret_status, ret_data = quote_ctx.get_trading_days("US", None, None)
    if ret_status != ft.RET_OK:
        print(ret_data)
        exit()
    print("TRADING DAYS")
    for x in ret_data:
        print(x)
1084871
def from_tushare(dataframe, dtype='day'):
    

    if dtype in ['day']:
        return QA_DataStruct_Stock_day(
            dataframe.assign(date=pd.to_datetime(dataframe.date)
                            ).set_index(['date',
                                         'code'],
                                        drop=False),
            dtype='stock_day'
        )
    elif dtype in ['min']:
        return QA_DataStruct_Stock_min(
            dataframe.assign(datetime=pd.to_datetime(dataframe.datetime)
                            ).set_index(['datetime',
                                         'code'],
                                        drop=False),
            dtype='stock_min'
        )
1345697
def from_dict(data, ctx):
        

        data = data.copy()

        if data.get('units') is not None:
            data['units'] = ctx.convert_decimal_number(
                data.get('units')
            )

        if data.get('price') is not None:
            data['price'] = ctx.convert_decimal_number(
                data.get('price')
            )

        if data.get('realizedPL') is not None:
            data['realizedPL'] = ctx.convert_decimal_number(
                data.get('realizedPL')
            )

        if data.get('financing') is not None:
            data['financing'] = ctx.convert_decimal_number(
                data.get('financing')
            )

        if data.get('guaranteedExecutionFee') is not None:
            data['guaranteedExecutionFee'] = ctx.convert_decimal_number(
                data.get('guaranteedExecutionFee')
            )

        if data.get('halfSpreadCost') is not None:
            data['halfSpreadCost'] = ctx.convert_decimal_number(
                data.get('halfSpreadCost')
            )

        return TradeReduce(**data)
126670
def from_dict(data, ctx):
        

        data = data.copy()

        if data.get('units') is not None:
            data['units'] = ctx.convert_decimal_number(
                data.get('units')
            )

        if data.get('price') is not None:
            data['price'] = ctx.convert_decimal_number(
                data.get('price')
            )

        if data.get('guaranteedExecutionFee') is not None:
            data['guaranteedExecutionFee'] = ctx.convert_decimal_number(
                data.get('guaranteedExecutionFee')
            )

        if data.get('clientExtensions') is not None:
            data['clientExtensions'] = \
                ctx.transaction.ClientExtensions.from_dict(
                    data['clientExtensions'], ctx
                )

        if data.get('halfSpreadCost') is not None:
            data['halfSpreadCost'] = ctx.convert_decimal_number(
                data.get('halfSpreadCost')
            )

        if data.get('initialMarginRequired') is not None:
            data['initialMarginRequired'] = ctx.convert_decimal_number(
                data.get('initialMarginRequired')
            )

        return TradeOpen(**data)
829462
def run(self, symbol: str) -> SecurityDetailsViewModel:
        
        from pydatum import Datum

        svc = self._svc
        sec_agg = svc.securities.get_aggregate_for_symbol(symbol)

        model = SecurityDetailsViewModel()

        model.symbol = sec_agg.security.namespace + ":" + sec_agg.security.mnemonic
        model.security = sec_agg.security

        # Quantity
        model.quantity = sec_agg.get_quantity()
        model.value = sec_agg.get_value()
        currency = sec_agg.get_currency()
        if currency:
            assert isinstance(currency, str)
            model.currency = currency
        model.price = sec_agg.get_last_available_price()

        model.average_price = sec_agg.get_avg_price()
        # Here we take only the amount paid for the remaining stock.
        model.total_paid = sec_agg.get_total_paid_for_remaining_stock()

        # Profit/loss
        model.profit_loss = model.value - model.total_paid
        if model.total_paid:
            model.profit_loss_perc = abs(model.profit_loss) * 100 / model.total_paid
        else:
            model.profit_loss_perc = 0
        if abs(model.value) < abs(model.total_paid):
            model.profit_loss_perc *= -1

        # Income
        model.income = sec_agg.get_income_total()
        if model.total_paid:
            model.income_perc = model.income * 100 / model.total_paid
        else:
            model.income_perc = 0
        # income in the last 12 months
        start = Datum()
        start.subtract_months(12)
        end = Datum()
        model.income_last_12m = sec_agg.get_income_in_period(start, end)
        if model.total_paid == 0:
            model.income_perc_last_12m = 0
        else:
            model.income_perc_last_12m = model.income_last_12m * 100 / model.total_paid

        # Return of Capital
        roc = sec_agg.get_return_of_capital()
        model.return_of_capital = roc

        # total return
        model.total_return = model.profit_loss + model.income
        if model.total_paid:
            model.total_return_perc = model.total_return * 100 / model.total_paid
        else:
            model.total_return_perc = 0

        # load all holding accounts
        model.accounts = sec_agg.accounts
        # Income accounts
        model.income_accounts = sec_agg.get_income_accounts()

        # Load asset classes to which this security belongs.
        # todo load asset allocation, find the parents for this symbol
        # svc.asset_allocation.load_config_only(svc.currencies.default_currency)
        # stocks = svc.asset_allocation.get_stock(model.symbol)
        #
        # for stock in stocks:
        #     model.asset_classes.append(stock.asset_class)
        from asset_allocation import AppAggregate
        aa = AppAggregate()
        aa.open_session()
        aa.get_asset_classes_for_security(None, model.symbol)

        return model
1249347
def from_dict(data, ctx):
        

        type = data.get("type")

        if type == "MARKET_ORDER":
            return MarketOrderTransaction.from_dict(data, ctx)
        if type == "ORDER_FILL":
            return OrderFillTransaction.from_dict(data, ctx)
        if type == "ORDER_CANCEL":
            return OrderCancelTransaction.from_dict(data, ctx)
        if type == "MARKET_ORDER_REJECT":
            return MarketOrderRejectTransaction.from_dict(data, ctx)
        if type == "TRADE_CLIENT_EXTENSIONS_MODIFY":
            return TradeClientExtensionsModifyTransaction.from_dict(data, ctx)
        if type == "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT":
            return TradeClientExtensionsModifyRejectTransaction.from_dict(data, ctx)
        if type == "TAKE_PROFIT_ORDER":
            return TakeProfitOrderTransaction.from_dict(data, ctx)
        if type == "STOP_LOSS_ORDER":
            return StopLossOrderTransaction.from_dict(data, ctx)
        if type == "TRAILING_STOP_LOSS_ORDER":
            return TrailingStopLossOrderTransaction.from_dict(data, ctx)
        if type == "ORDER_CANCEL_REJECT":
            return OrderCancelRejectTransaction.from_dict(data, ctx)
        if type == "TAKE_PROFIT_ORDER_REJECT":
            return TakeProfitOrderRejectTransaction.from_dict(data, ctx)
        if type == "STOP_LOSS_ORDER_REJECT":
            return StopLossOrderRejectTransaction.from_dict(data, ctx)
        if type == "TRAILING_STOP_LOSS_ORDER_REJECT":
            return TrailingStopLossOrderRejectTransaction.from_dict(data, ctx)
        if type == "CLIENT_CONFIGURE":
            return ClientConfigureTransaction.from_dict(data, ctx)
        if type == "CLIENT_CONFIGURE_REJECT":
            return ClientConfigureRejectTransaction.from_dict(data, ctx)
        if type == "CREATE":
            return CreateTransaction.from_dict(data, ctx)
        if type == "CLOSE":
            return CloseTransaction.from_dict(data, ctx)
        if type == "REOPEN":
            return ReopenTransaction.from_dict(data, ctx)
        if type == "TRANSFER_FUNDS":
            return TransferFundsTransaction.from_dict(data, ctx)
        if type == "TRANSFER_FUNDS_REJECT":
            return TransferFundsRejectTransaction.from_dict(data, ctx)
        if type == "FIXED_PRICE_ORDER":
            return FixedPriceOrderTransaction.from_dict(data, ctx)
        if type == "LIMIT_ORDER":
            return LimitOrderTransaction.from_dict(data, ctx)
        if type == "LIMIT_ORDER_REJECT":
            return LimitOrderRejectTransaction.from_dict(data, ctx)
        if type == "STOP_ORDER":
            return StopOrderTransaction.from_dict(data, ctx)
        if type == "STOP_ORDER_REJECT":
            return StopOrderRejectTransaction.from_dict(data, ctx)
        if type == "MARKET_IF_TOUCHED_ORDER":
            return MarketIfTouchedOrderTransaction.from_dict(data, ctx)
        if type == "MARKET_IF_TOUCHED_ORDER_REJECT":
            return MarketIfTouchedOrderRejectTransaction.from_dict(data, ctx)
        if type == "ORDER_CLIENT_EXTENSIONS_MODIFY":
            return OrderClientExtensionsModifyTransaction.from_dict(data, ctx)
        if type == "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT":
            return OrderClientExtensionsModifyRejectTransaction.from_dict(data, ctx)
        if type == "MARGIN_CALL_ENTER":
            return MarginCallEnterTransaction.from_dict(data, ctx)
        if type == "MARGIN_CALL_EXTEND":
            return MarginCallExtendTransaction.from_dict(data, ctx)
        if type == "MARGIN_CALL_EXIT":
            return MarginCallExitTransaction.from_dict(data, ctx)
        if type == "DELAYED_TRADE_CLOSURE":
            return DelayedTradeClosureTransaction.from_dict(data, ctx)
        if type == "DAILY_FINANCING":
            return DailyFinancingTransaction.from_dict(data, ctx)
        if type == "RESET_RESETTABLE_PL":
            return ResetResettablePLTransaction.from_dict(data, ctx)

        data = data.copy()

        return Transaction(**data)
442184
def run(self):
        
        # 如果出现了日期的改变 才会进行结算的事件
        _date = None

        while QA_util_if_tradetime(self.now):
            for data in self.ingest_data:  # 对于在ingest_data中的数据
                # <class 'QUANTAXIS.QAData.QADataStruct.QA_DataStruct_Stock_day'>
                date = data.date[0]
                if self.market_type is MARKET_TYPE.STOCK_CN:  # 如果是股票市场
                    if _date != date:  # 如果新的date
                        # 前一天的交易日已经过去
                        # 往 broker 和 account 发送 settle 事件
                        try:
                            self.market.trade_engine.join()
                            # time.sleep(2)
                            self.market._settle(self.broker_name)

                        except Exception as e:
                            raise e
                # 基金 指数 期货
                elif self.market_type in [MARKET_TYPE.FUND_CN, MARKET_TYPE.INDEX_CN, MARKET_TYPE.FUTURE_CN]:
                    self.market._settle(self.broker_name)
                # print(data)
                self.broker.run(
                    QA_Event(event_type=ENGINE_EVENT.UPCOMING_DATA, market_data=data))
                # 生成 UPCOMING_DATA 事件放到 队列中去执行

                self.market.upcoming_data(self.broker_name, data)

                self.market.trade_engine.join()

                _date = date
840220
def xdxr(self, symbol=''):
        '''
        
        '''
        market = get_stock_market(symbol)

        with self.client.connect(*self.bestip):
            data = self.client.get_xdxr_info(int(market), symbol)
            return self.client.to_df(data)
1017290
def run(self, event):
        '''
        
        '''
        'QA_WORKER method'
        if event.event_type is ACCOUNT_EVENT.SETTLE:
            print('account_settle')
            self.settle()

        # elif event.event_type is ACCOUNT_EVENT.UPDATE:
        #     self.receive_deal(event.message)
        elif event.event_type is ACCOUNT_EVENT.MAKE_ORDER:
            """generate order
            if callback callback the order
            if not return back the order
            """
            data = self.send_order(
                code=event.code,
                amount=event.amount,
                time=event.time,
                amount_model=event.amount_model,
                towards=event.towards,
                price=event.price,
                order_model=event.order_model
            )
            if event.callback:
                event.callback(data)
            else:
                return data
        elif event.event_type is ENGINE_EVENT.UPCOMING_DATA:
            """update the market_data
            1. update the inside market_data struct
            2. tell the on_bar methods

            # 这样有点慢


            """

            self._currenttime = event.market_data.datetime[0]
            if self._market_data is None:
                self._market_data = event.market_data
            else:
                self._market_data = self._market_data + event.market_data
            self.on_bar(event)

            if event.callback:
                event.callback(event)
1083330
def trans_his(self, symbol='', start=0, offset=10, date=''):
        '''
        
        '''
        market = get_stock_market(symbol)

        with self.client.connect(*self.bestip):
            data = self.client.get_history_transaction_data(
                int(market), symbol, int(start), int(offset), date)
            return self.client.to_df(data)
1058938
def requestMarketDepth(self, contracts=None, num_rows=10):
        

        if num_rows > 10:
            num_rows = 10

        if contracts == None:
            contracts = list(self.contracts.values())
        elif not isinstance(contracts, list):
            contracts = [contracts]

        for contract in contracts:
            tickerId = self.tickerId(self.contractString(contract))
            self.ibConn.reqMktDepth(
                tickerId, contract, num_rows)