Return the eod market data frame for pricing
960187
def get_eod_frame(self):
        """"""
        close = self.pxs.close
        mktval = self.get_mkt_val(close)
        dvds = self.pxs.dvds
        df = pd.DataFrame({'close': close, 'mkt_val': mktval, 'dvds': dvds})
        df.index.name = 'date'
        return df
741455
def pack_req(cls, trd_side, order_type, price, qty,
                 code, adjust_limit, trd_env, sec_mkt_str, acc_id, trd_mkt, conn_id):
        """"""
        from futuquant.common.pb.Trd_PlaceOrder_pb2 import Request
        req = Request()
        serial_no = get_unique_id32()
        req.c2s.packetID.serialNo = serial_no
        req.c2s.packetID.connID = conn_id

        req.c2s.header.trdEnv = TRD_ENV_MAP[trd_env]
        req.c2s.header.accID = acc_id
        req.c2s.header.trdMarket = TRD_MKT_MAP[trd_mkt]

        req.c2s.trdSide = TRD_SIDE_MAP[trd_side]
        req.c2s.orderType = ORDER_TYPE_MAP[order_type]
        req.c2s.code = code
        req.c2s.qty = qty
        req.c2s.price = price
        req.c2s.adjustPrice = adjust_limit != 0
        req.c2s.adjustSideAndLimit = adjust_limit
        proto_qot_mkt = MKT_MAP.get(sec_mkt_str, Qot_Common_pb2.QotMarket_Unknown)
        proto_trd_sec_mkt = QOT_MARKET_TO_TRD_SEC_MARKET_MAP.get(proto_qot_mkt,
                                                                 Trd_Common_pb2.TrdSecMarket_Unknown)
        req.c2s.secMarket = proto_trd_sec_mkt

        return pack_pb_req(req, ProtoId.Trd_PlaceOrder, conn_id, serial_no)
602205
def get_price(self):
        
        tick = self.get_ticks(lookback=1, as_dict=True)
        return None if tick is None else tick['last']
1335433
def items_with_price(raw_df):
    
    df = (
        raw_df
        [['PRONAC', 'idPlanilhaAprovacao', 'Item',
            'idPlanilhaItens', 'VlUnitarioAprovado',
            'idSegmento', 'DataProjeto', 'idPronac',
            'UfItem', 'idProduto', 'cdCidade', 'cdEtapa']]
    ).copy()

    df['VlUnitarioAprovado'] = df['VlUnitarioAprovado'].apply(pd.to_numeric)
    return df
32604
def QA_fetch_get_option_contract_time_to_market():
    '''
    
    '''
    result = QA_fetch_get_option_list('tdx')
    # pprint.pprint(result)
    #  category  market code name desc  code
    '''
    fix here : 
    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
    result['meaningful_name'] = None
    C:\work_new\QUANTAXIS\QUANTAXIS\QAFetch\QATdx.py:1468: SettingWithCopyWarning: 
    A value is trying to be set on a copy of a slice from a DataFrame.
    Try using .loc[row_indexer,col_indexer] = value instead
    '''
    # df = pd.DataFrame()
    rows = []

    result['meaningful_name'] = None
    for idx in result.index:
        # pprint.pprint((idx))
        strCategory = result.loc[idx, "category"]
        strMarket = result.loc[idx, "market"]
        strCode = result.loc[idx, "code"]  # 10001215
        strName = result.loc[idx, 'name']  # 510050C9M03200
        strDesc = result.loc[idx, 'desc']  # 10001215

        if strName.startswith("510050"):
            # print(strCategory,' ', strMarket, ' ', strCode, ' ', strName, ' ', strDesc, )

            if strName.startswith("510050C"):
                putcall = '50ETF,认购期权'
            elif strName.startswith("510050P"):
                putcall = '50ETF,认沽期权'
            else:
                putcall = "Unkown code name ： " + strName

            expireMonth = strName[7:8]
            if expireMonth == 'A':
                expireMonth = "10月"
            elif expireMonth == 'B':
                expireMonth = "11月"
            elif expireMonth == 'C':
                expireMonth = "12月"
            else:
                expireMonth = expireMonth + '月'

            # 第12位期初设为“M”，并根据合约调整次数按照“A”至“Z”依序变更，如变更为“A”表示期权合约发生首次调整，变更为“B”表示期权合约发生第二次调整，依此类推；
            # fix here : M ??
            if strName[8:9] == "M":
                adjust = "未调整"
            elif strName[8:9] == 'A':
                adjust = " 第1次调整"
            elif strName[8:9] == 'B':
                adjust = " 第2调整"
            elif strName[8:9] == 'C':
                adjust = " 第3次调整"
            elif strName[8:9] == 'D':
                adjust = " 第4次调整"
            elif strName[8:9] == 'E':
                adjust = " 第5次调整"
            elif strName[8:9] == 'F':
                adjust = " 第6次调整"
            elif strName[8:9] == 'G':
                adjust = " 第7次调整"
            elif strName[8:9] == 'H':
                adjust = " 第8次调整"
            elif strName[8:9] == 'I':
                adjust = " 第9次调整"
            elif strName[8:9] == 'J':
                adjust = " 第10次调整"
            else:
                adjust = " 第10次以上的调整，调整代码 %s" + strName[8:9]

            executePrice = strName[9:]
            result.loc[idx, 'meaningful_name'] = '%s,到期月份:%s,%s,行权价:%s' % (
                putcall, expireMonth, adjust, executePrice)

            row = result.loc[idx]
            rows.append(row)

        elif strName.startswith("SR"):
            # print("SR")
            # SR1903-P-6500
            expireYear = strName[2:4]
            expireMonth = strName[4:6]

            put_or_call = strName[7:8]
            if put_or_call == "P":
                putcall = "白糖,认沽期权"
            elif put_or_call == "C":
                putcall = "白糖,认购期权"
            else:
                putcall = "Unkown code name ： " + strName

            executePrice = strName[9:]
            result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
                putcall, expireYear, expireMonth, executePrice)

            row = result.loc[idx]
            rows.append(row)

            pass
        elif strName.startswith("CU"):
            # print("CU")

            # print("SR")
            # SR1903-P-6500
            expireYear = strName[2:4]
            expireMonth = strName[4:6]

            put_or_call = strName[7:8]
            if put_or_call == "P":
                putcall = "铜,认沽期权"
            elif put_or_call == "C":
                putcall = "铜,认购期权"
            else:
                putcall = "Unkown code name ： " + strName

            executePrice = strName[9:]
            result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
                putcall, expireYear, expireMonth, executePrice)

            row = result.loc[idx]
            rows.append(row)

            pass
        # todo 新增期权品种 棉花，玉米， 天然橡胶
        elif strName.startswith("RU"):
            # print("M")
            # print(strName)
            ##
            expireYear = strName[2:4]
            expireMonth = strName[4:6]

            put_or_call = strName[7:8]
            if put_or_call == "P":
                putcall = "天然橡胶,认沽期权"
            elif put_or_call == "C":
                putcall = "天然橡胶,认购期权"
            else:
                putcall = "Unkown code name ： " + strName

            executePrice = strName[9:]
            result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
                putcall, expireYear, expireMonth, executePrice)

            row = result.loc[idx]
            rows.append(row)

            pass

        elif strName.startswith("CF"):
            # print("M")
            # print(strName)
            ##
            expireYear = strName[2:4]
            expireMonth = strName[4:6]

            put_or_call = strName[7:8]
            if put_or_call == "P":
                putcall = "棉花,认沽期权"
            elif put_or_call == "C":
                putcall = "棉花,认购期权"
            else:
                putcall = "Unkown code name ： " + strName

            executePrice = strName[9:]
            result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
                putcall, expireYear, expireMonth, executePrice)

            row = result.loc[idx]
            rows.append(row)

            pass

        elif strName.startswith("M"):
            # print("M")
            # print(strName)
            ##
            expireYear = strName[1:3]
            expireMonth = strName[3:5]

            put_or_call = strName[6:7]
            if put_or_call == "P":
                putcall = "豆粕,认沽期权"
            elif put_or_call == "C":
                putcall = "豆粕,认购期权"
            else:
                putcall = "Unkown code name ： " + strName

            executePrice = strName[8:]
            result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
                putcall, expireYear, expireMonth, executePrice)

            row = result.loc[idx]
            rows.append(row)

            pass
        elif strName.startswith("C") and strName[1] != 'F' and strName[1] != 'U':
            # print("M")
            # print(strName)
            ##
            expireYear = strName[1:3]
            expireMonth = strName[3:5]

            put_or_call = strName[6:7]
            if put_or_call == "P":
                putcall = "玉米,认沽期权"
            elif put_or_call == "C":
                putcall = "玉米,认购期权"
            else:
                putcall = "Unkown code name ： " + strName

            executePrice = strName[8:]
            result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
                putcall, expireYear, expireMonth, executePrice)

            row = result.loc[idx]
            rows.append(row)

            pass
        else:
            print("未知类型合约")
            print(strName)

    return rows
923891
def to_frame(self):
        
        col_names = _column_names_from_metadata(
            t.metadata for t in self.transactions)

        def trow(t):
            return tz.concatv(
                (t.amount, t.subaccount),
                (t.metadata.get(c) for c in col_names))
        rows = [trow(t) for t in self.transactions]

        if len(rows) == 0:
            return pd.DataFrame(columns=COLS + col_names)

        return pd.DataFrame(rows, columns=COLS + col_names)
28034
def typical_price(close_data, high_data, low_data):
    
    catch_errors.check_for_input_len_diff(close_data, high_data, low_data)
    tp = [(high_data[idx] + low_data[idx] + close_data[idx]) / 3 for idx in range(0, len(close_data))]
    return np.array(tp)
471650
def import_prices(self, prices: List[PriceModel]):
        
        result = {}
        for price in prices:
            result[price.symbol] = self.import_price(price)

        return result
1157579
def from_dict(data, ctx):
        

        type = data.get("type")

        if type == "TAKE_PROFIT":
            return TakeProfitOrder.from_dict(data, ctx)
        if type == "STOP_LOSS":
            return StopLossOrder.from_dict(data, ctx)
        if type == "TRAILING_STOP_LOSS":
            return TrailingStopLossOrder.from_dict(data, ctx)
        if type == "MARKET":
            return MarketOrder.from_dict(data, ctx)
        if type == "FIXED_PRICE":
            return FixedPriceOrder.from_dict(data, ctx)
        if type == "LIMIT":
            return LimitOrder.from_dict(data, ctx)
        if type == "STOP":
            return StopOrder.from_dict(data, ctx)
        if type == "MARKET_IF_TOUCHED":
            return MarketIfTouchedOrder.from_dict(data, ctx)

        data = data.copy()

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

        return Order(**data)
350770
def get_frame(self, idx):
        """"""
        cont = self.data[idx]
        frame = int(cont.strip().split(" ", 1)[0])
        return frame
575132
def load_data(self):
        
        try:
            df = self.live_quote_arg_func(self.tickers)
            for index, ticker in enumerate(self.tickers):
                ticker_info = df.loc[index]
                self.ticker_dict[ticker].append(ticker_info['price'],
                                                ticker_info['volume'],
                                                ticker_info['amount'],
                                                ticker_info['time'])
        except Exception:
            raise ValueError('Polling thread exception')
1302297
def get_market_last(symbols=None, **kwargs):
    
    import warnings
    warnings.warn(WNG_MSG % ("get_market_last", "iexdata.get_last"))
    return Last(symbols, **kwargs).fetch()
1306998
def to_frame(self, **kwargs):
        
        """
        df = export.write_dataframe(self._values, **kwargs)
        df.name = self.title
        return df
10473
def trade(self):
        

        return self.history_table.pivot_table(
            index=['datetime',
                   'account_cookie'],
            columns='code',
            values='amount',
            aggfunc=np.sum
        ).fillna(0).sort_index()
902964
def get_fields_frame(schema):
    '''
    
    '''
    fields = []

    def get_field_record(i, key, value, parents):
        if value.get('private') or 'default' not in value:
            raise Skip
        field = (len(parents) - 1, i, tuple(parents[:-1]), parents[-1],
                 value['type'], value['default'])
        return fields.append(field)

    # Fill fields list.
    get_types(schema['properties'], get_field_record)

    # Order by level, then explicit index.
    df_fields = pd.DataFrame(sorted(fields), columns=['level_i', 'field_i',
                                                      'parents', 'field',
                                                      'field_type', 'default'])

    df_fields['attributes'] = df_fields.apply(lambda row:
                                              get_nested_item(row, schema
                                                              ['properties'],
                                                              row.parents +
                                                              (row.field, )),
                                              axis=1)
    return df_fields
815144
def _get_data(self) -> BaseFrameManager:
        

        def iloc(partition, row_internal_indices, col_internal_indices):
            return partition.iloc[row_internal_indices, col_internal_indices]

        masked_data = self.parent_data.apply_func_to_indices_both_axis(
            func=iloc,
            row_indices=self.index_map.values,
            col_indices=self.columns_map.values,
            lazy=False,
            keep_remaining=False,
        )
        return masked_data
1322248
def to_xdr_object(self):
        
        selling = self.selling.to_xdr_object()
        buying = self.buying.to_xdr_object()

        price = Operation.to_xdr_price(self.price)
        price = Xdr.types.Price(price['n'], price['d'])

        amount = Operation.to_xdr_amount(self.amount)

        create_passive_offer_op = Xdr.types.CreatePassiveOfferOp(
            selling, buying, amount, price)
        self.body.type = Xdr.const.CREATE_PASSIVE_OFFER
        self.body.createPassiveOfferOp = create_passive_offer_op
        return super(CreatePassiveOffer, self).to_xdr_object()