Return the amount of time at which the stock of materal will be
        depleted.

        :param V_stock: Volume of the stock of material
        :type V_stock: float

        :return: Time at which the stock will be depleted
        :rtype: float
198754
def T_stock(self, V_stock):
        
        return Stock.T_stock(self, V_stock, self.Q_stock()).to(u.hr)
630306
def get_market_iex_volume(*args, **kwargs):
    
    import warnings
    warnings.warn(WNG_MSG, ("get_market_iex_volume",
                            "stocks.get_market_iex_volume"))
    return stocks.get_market_iex_volume(*args, **kwargs)
1349090
def query_stock(self, stock_id, op_user_id=None, device_info=None):
        
        data = {
            'appid': self.appid,
            'coupon_stock_id': stock_id,
            'op_user_id': op_user_id,
            'device_info': device_info,
            'version': '1.0',
            'type': 'XML',
        }
        return self._post('mmpaymkttransfers/query_coupon_stock', data=data)
1309132
def get_MD_VDS(tail_check_max, vds):
    
    if tail_check_max == 0 or numpy.isnan(tail_check_max):
        return float('nan')
    MD_VDS = (old_div(tail_check_max, vds)) * 100
    return MD_VDS
1330840
def QA_SU_trans_stock_min(client=DATABASE, ui_log=None, ui_progress=None,
                          data_path: str = "D:\\skysoft\\", type_="1min"):
    
    code_list = list(map(lambda x: x[2:8], os.listdir(data_path)))
    coll = client.stock_min
    coll.create_index([
        ("code", pymongo.ASCENDING),
        ("time_stamp", pymongo.ASCENDING),
        ("date_stamp", pymongo.ASCENDING),
    ])
    err = []

    def __transform_ss_to_qa(file_path: str = None, end_time: str = None, type_="1min"):
        """
        导入相应 csv 文件，并处理格式
        1. 这里默认为天软数据格式:

             time                  symbol      open    high    low     close   volume  amount
           0 2013-08-01 09:31:00	SH600000	7.92	7.92	7.87	7.91	518700	4105381
        ...
        2. 与 QUANTAXIS.QAFetch.QATdx.QA_fetch_get_stock_min 获取数据进行匹配，具体处理详见相应源码

                              open  close   high    low           vol        amount    ...
           datetime
           2018-12-03 09:31:00  10.99  10.90  10.99  10.90  2.211700e+06  2.425626e+07 ...
        """

        if file_path is None:
            raise ValueError("输入文件地址")

        df_local = pd.read_csv(file_path)

        # 列名处理
        df_local = df_local.rename(
            columns={"time": "datetime", "volume": "vol"})

        # 格式处理
        df_local = df_local.assign(
            code=df_local.symbol.map(str).str.slice(2),
            date=df_local.datetime.map(str).str.slice(0, 10),
        ).drop(
            "symbol", axis=1)
        df_local = df_local.assign(
            datetime=pd.to_datetime(df_local.datetime),
            date_stamp=df_local.date.apply(lambda x: QA_util_date_stamp(x)),
            time_stamp=df_local.datetime.apply(
                lambda x: QA_util_time_stamp(x)),
            type="1min",
        ).set_index(
            "datetime", drop=False)
        df_local = df_local.loc[slice(None, end_time)]
        df_local["datetime"] = df_local["datetime"].map(str)
        df_local["type"] = type_
        return df_local[[
            "open",
            "close",
            "high",
            "low",
            "vol",
            "amount",
            "datetime",
            "code",
            "date",
            "date_stamp",
            "time_stamp",
            "type",
        ]]

    def __saving_work(code, coll):
        QA_util_log_info(
            "##JOB03 Now Saving STOCK_MIN ==== {}".format(code), ui_log=ui_log)
        try:
            col_filter = {"code": code, "type": type_}
            ref_ = coll.find(col_filter)
            end_time = ref_[0]['datetime']  # 本地存储分钟数据最早的时间
            filename = "SH"+code+".csv" if code[0] == '6' else "SZ"+code+".csv"
            __data = __transform_ss_to_qa(
                data_path+filename, end_time, type_)  # 加入 end_time， 避免出现数据重复

            QA_util_log_info(
                "##JOB03.{} Now Saving {} from {} to {} == {}".format(
                    type_,
                    code,
                    __data['datetime'].iloc[0],
                    __data['datetime'].iloc[-1],
                    type_,
                ),
                ui_log=ui_log,
            )
            if len(__data) > 1:
                coll.insert_many(
                    QA_util_to_json_from_pandas(__data)[1::])
        except Exception as e:
            QA_util_log_info(e, ui_log=ui_log)
            err.append(code)
            QA_util_log_info(err, ui_log=ui_log)

    executor = ThreadPoolExecutor(max_workers=4)
    res = {
        executor.submit(__saving_work, code_list[i_], coll)
        for i_ in range(len(code_list))
    }
    count = 0
    for i_ in concurrent.futures.as_completed(res):
        strProgress = "TRANSFORM PROGRESS {} ".format(
            str(float(count / len(code_list) * 100))[0:4] + "%")
        intProgress = int(count / len(code_list) * 10000.0)
        count = count + 1
    if len(err) < 1:
        QA_util_log_info("SUCCESS", ui_log=ui_log)
    else:
        QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
        QA_util_log_info(err, ui_log=ui_log)

    if len(err) < 1:
        QA_util_log_info("SUCCESS", ui_log=ui_log)
    else:
        QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
        QA_util_log_info(err, ui_log=ui_log)
475480
def min_volatility(self):
        
        args = (self.cov_matrix, self.gamma)
        result = sco.minimize(
            objective_functions.volatility,
            x0=self.initial_guess,
            args=args,
            method="SLSQP",
            bounds=self.bounds,
            constraints=self.constraints,
        )
        self.weights = result["x"]
        return dict(zip(self.tickers, self.weights))
946908
def __getCashToBuyStock(self):
        '''  '''
        account=self.__strategy.getAccountCopy()

        if (account.buyingPower >= account.getTotalValue() / self.__buyingRatio):
            return account.getTotalValue() / self.__buyingRatio
        else:
            return 0
1020929
def QA_fetch_stock_day_full_adv(date):
    '''
    
    '''
    # 🛠 todo 检查日期data参数
    res = QA_fetch_stock_full(date, 'pd')
    if res is None:
        print("QA Error QA_fetch_stock_day_full_adv parameter date=%s call QA_fetch_stock_full return None" % (date))
        return None
    else:
        res_set_index = res.set_index(['date', 'code'])
        # if res_set_index is None:
        #     print("QA Error QA_fetch_stock_day_full set index 'date, code' return None")
        return QA_DataStruct_Stock_day(res_set_index)
1137389
def output(self):
    #re = "{%(time)s} %(name)s %(stock_no)s %(c)s %(range)+.2f(%(pp)+.2f%%) %(value)s" % {
    '''
    
    '''
    if covstr(self.g['range']) > 0:
      css = "red"
    elif covstr(self.g['range']) < 0:
      css = "green"
    else:
      css = "gray"

    re = {
      'name': self.g['name'],
      'stock_no': self.g['no'],
      'time': self.g['time'],
      'open': self.g['open'],
      'h': self.g['h'],
      'l': self.g['l'],
      'c': self.g['c'],
      'max': self.g['max'],
      'min': self.g['min'],
      'range': covstr(self.g['range']),
      'ranges': self.g['ranges'],
      'value': self.g['value'],
      'pvalue': self.g['pvalue'],
      'pp': covstr(self.g['pp']),
      'top5buy': self.g['top5buy'],
      'top5sell': self.g['top5sell'],
      'crosspic': self.g['crosspic'],
      'css': css
    }
    return re
514082
def calculate_current_allocation(self):
        
        for ac in self.asset_classes:
            ac.curr_alloc = ac.curr_value * 100 / self.total_amount
821358
def tradevolume(self):
        """"""
        request = '/v1/tradevolume'
        url = self.base_url + request
        params = {
            'request': request,
            'nonce': self.get_nonce()
        }

        return requests.post(url, headers=self.prepare(params))
548161
def value(self, loss_type, time_event=None):
        
        if loss_type == 'occupants':
            return self.values['occupants_' + str(time_event)]
        try:  # extract from the cache
            val = self._cost[loss_type]
        except KeyError:  # compute
            val = self.calc(loss_type, self.values, self.area, self.number)
            self._cost[loss_type] = val
        return val
1241589
def min_volatility(self):
        """"""
        if not self.w:
            self.solve()
        var = []
        for w in self.w:
            a = np.dot(np.dot(w.T, self.cov_matrix), w)
            var.append(a)
        # return min(var)**.5, self.w[var.index(min(var))]
        self.weights = self.w[var.index(min(var))].reshape((self.n_assets,))
        return dict(zip(self.tickers, self.weights))
187576
def stock_status(self, stock_status):
        
        allowed_values = ["available", "alert", "unavailable"]
        if stock_status is not None and stock_status not in allowed_values:
            raise ValueError(
                "Invalid value for `stock_status` ({0}), must be one of {1}"
                .format(stock_status, allowed_values)
            )

        self._stock_status = stock_status
28372
def volatility(data, period):
    
    volatility = sd(data, period) / sv(data, period)
    return volatility
579223
def Q_stock(self):
        
        return self._Q_sys * (self._C_sys / self._C_stock).to(u.dimensionless)
219332
def get_ticker(self):
        ''''''
        lastQuote = self.data['quote'][-1]
        lastTrade = self.data['trade'][-1]
        ticker = {
            "last": lastTrade['price'],
            "buy": lastQuote['bidPrice'],
            "sell": lastQuote['askPrice'],
            "mid": (float(lastQuote['bidPrice'] or 0) + float(lastQuote['askPrice'] or 0)) / 2
        }

        # The instrument has a tickSize. Use it to round values.
        instrument = self.data['instrument'][0]
        return {k: round(float(v or 0), instrument['tickLog']) for k, v in list(ticker.items())}