fetch data for multiple stocks
175539
def all(cls, client, symbols):
        "
        params = {"symbol": ",".join(symbols)}
        request_url = "https://api.robinhood.com/instruments/"

        data = client.get(request_url, params=params)
        results = data["results"]

        while data["next"]:
            data = client.get(data["next"])
            results.extend(data["results"])
        return results
1185331
def get_all(self, security):
        
        url = 'http://www.google.com/finance?q=%s' % security
        page = self._request(url)

        soup = BeautifulSoup(page)
        snapData = soup.find("table", {"class": "snap-data"})
        if snapData is None:
            raise UfException(Errors.STOCK_SYMBOL_ERROR, "Can find data for stock %s, security error?" % security)
        data = {}
        for row in snapData.findAll('tr'):
            keyTd, valTd = row.findAll('td')
            data[keyTd.getText()] = valTd.getText()

        return data
1367268
def QA_data_stock_to_fq(__data, type_='01'):

    def __QA_fetch_stock_xdxr(
            code,
            format_='pd',
            collections=DATABASE.stock_xdxr
    ):
        '获取股票除权信息/数据库'
        try:
            data = pd.DataFrame(
                [item for item in collections.find({'code': code})]
            ).drop(['_id'],
                   axis=1)
            data['date'] = pd.to_datetime(data['date'])
            return data.set_index(['date', 'code'], drop=False)
        except:
            return pd.DataFrame(
                data=[],
                columns=[
                    'category',
                    'category_meaning',
                    'code',
                    'date',
                    'fenhong',
                    'fenshu',
                    'liquidity_after',
                    'liquidity_before',
                    'name',
                    'peigu',
                    'peigujia',
                    'shares_after',
                    'shares_before',
                    'songzhuangu',
                    'suogu',
                    'xingquanjia'
                ]
            )

    ''

    code = __data.index.remove_unused_levels().levels[1][0] if isinstance(
        __data.index,
        pd.core.indexes.multi.MultiIndex
    ) else __data['code'][0]

    return _QA_data_stock_to_fq(
        bfq_data=__data,
        xdxr_data=__QA_fetch_stock_xdxr(code),
        fqtype=type_
    )
1235341
def QA_SU_save_stock_list(client=DATABASE, ui_log=None, ui_progress=None):
    
    client.drop_collection('stock_list')
    coll = client.stock_list
    coll.create_index('code')

    try:
        # 🛠todo 这个应该是第一个任务 JOB01， 先更新股票列表！！
        QA_util_log_info(
            '##JOB08 Now Saving STOCK_LIST ====',
            ui_log=ui_log,
            ui_progress=ui_progress,
            ui_progress_int_value=5000
        )
        stock_list_from_tdx = QA_fetch_get_stock_list()
        pandas_data = QA_util_to_json_from_pandas(stock_list_from_tdx)
        coll.insert_many(pandas_data)
        QA_util_log_info(
            "完成股票列表获取",
            ui_log=ui_log,
            ui_progress=ui_progress,
            ui_progress_int_value=10000
        )
    except Exception as e:
        QA_util_log_info(e, ui_log=ui_log)
        print(" Error save_tdx.QA_SU_save_stock_list exception!")

        pass
1131362
def QA_SU_save_stock_info(client=DATABASE, ui_log=None, ui_progress=None):
    

    client.drop_collection('stock_info')
    stock_list = QA_fetch_get_stock_list().code.unique().tolist()
    coll = client.stock_info
    coll.create_index('code')
    err = []

    def __saving_work(code, coll):
        QA_util_log_info(
            '##JOB10 Now Saving STOCK INFO ==== {}'.format(str(code)),
            ui_log=ui_log
        )
        try:
            coll.insert_many(
                QA_util_to_json_from_pandas(QA_fetch_get_stock_info(str(code)))
            )

        except:
            err.append(str(code))

    for i_ in range(len(stock_list)):
        # __saving_work('000001')

        strLogProgress = 'DOWNLOAD PROGRESS {} '.format(
            str(float(i_ / len(stock_list) * 100))[0:4] + '%'
        )
        intLogProgress = int(float(i_ / len(stock_list) * 10000.0))
        QA_util_log_info('The {} of Total {}'.format(i_, len(stock_list)))
        QA_util_log_info(
            strLogProgress,
            ui_log=ui_log,
            ui_progress=ui_progress,
            ui_progress_int_value=intLogProgress
        )

        __saving_work(stock_list[i_], coll)
    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)
659396
def allck():
  '''  '''
  for i in twseno().allstockno:
    a = goristock.goristock(i)
    try:
      if a.stock_vol[-1] > 1000*1000 and a.raw_data[-1] > 10:
        #a.goback(3) ## 倒退天數
        ck4m(a)
    except:
      pass
665428
def fetch_data(self):
        """"""
        if relativedelta(self.end_date, self.start_date).years <= const.ONE_YEAR:
            data = self.request.send(self.symbol, self.start_date, self.end_date)
        else:
            data = self.fetch_chunk_data()

        return self.clean(data)
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)
532801
def optimize(self, to_buy, to_sell):
        '''
        
        '''
        allocations = {}

        # Process every stock the same way
        for s in to_buy:
            quantity = self.properties.get('buy_amount', 100)
            if s in self.properties.get('scale', {}):
                quantity *= self.properties['scale'][s]
            # Allocate defined amount to buy
            allocations[s] = int(quantity)

        # NOTE You must provide sell_amount if you want to short
        for s in to_sell:
            quantity = self.properties.get(
                'sell_amount', self.portfolio.positions[s].amount)
            if s in self.properties.get('scale', {}):
                quantity *= self.properties['scale'][s]
            # Allocate defined amount to buy
            allocations[s] = -int(quantity)

        # Defaults values
        e_ret = 0
        e_risk = 1
        return allocations, e_ret, e_risk
160527
function getDataItems (items) {
  validate.requiredItems(items)

  const data = {}
  validate.vatIdNumber(items.dicPopl)
  data.dic_popl = items.dicPopl

  validate.businessPremisesId(items.idProvoz)
  data.id_provoz = items.idProvoz

  validate.cashRegisterId(items.idPokl)
  data.id_pokl = items.idPokl

  validate.receiptNumber(items.poradCis)
  data.porad_cis = items.poradCis

  validate.date(items.datTrzby)
  data.dat_trzby = formatDate(items.datTrzby)

  if (isDefinedAndNotNull(items.rezim)) {
    validate.regime(items.rezim)
    data.rezim = items.rezim
  } else {
    data.rezim = 0
  }

  if (isDefinedAndNotNull(items.dicPoverujiciho)) {
    validate.vatIdNumber(items.dicPoverujiciho)
    data.dic_poverujiciho = items.dicPoverujiciho
  }

  validate.financialNumber(items.celkTrzba)
  data.celk_trzba = formatNumber(items.celkTrzba)

  const map = {
    zaklNepodlDph: 'zakl_nepodl_dph',
    zaklDan1: 'zakl_dan1',
    dan1: 'dan1',
    zaklDan2: 'zakl_dan2',
    dan2: 'dan2',
    zaklDan3: 'zakl_dan3',
    dan3: 'dan3',
    cestSluz: 'cest_sluz',
    pouzitZboz1: 'pouzit_zboz1',
    pouzitZboz2: 'pouzit_zboz2',
    pouzitZboz3: 'pouzit_zboz3',
    urcenoCerpZuct: 'urceno_cerp_zuct',
    cerpZuct: 'cerp_zuct'
  }
  Object.keys(map)
  .filter(key => isDefinedAndNotNull(items[key]))
  .forEach(key => {
    validate.financialNumber(items[key])
    data[map[key]] = formatNumber(items[key])
  })

  return {
    attributes: data
  }
}
1089545
def QA_fetch_get_stock_adj(code, end=''):
    

    pro = get_pro()
    adj = pro.adj_factor(ts_code=code, trade_date=end)
    return adj
82445
def venue_stocks(self):
        
        url = urljoin(self.base_url, 'venues/{0}/stocks'.format(self.venue))
        return self.session.get(url).json()
623521
def QA_fetch_get_stock_transaction_realtime(code, ip=None, port=None):
    ''
    ip, port = get_mainmarket_ip(ip, port)
    api = TdxHq_API()
    try:
        with api.connect(ip, port):
            data = pd.DataFrame()
            data = pd.concat([api.to_df(api.get_transaction_data(
                _select_market_code(str(code)), code, (2 - i) * 2000, 2000)) for i in range(3)], axis=0)
            if 'value' in data.columns:
                data = data.drop(['value'], axis=1)
            data = data.dropna()
            day = datetime.date.today()
            return data.assign(date=str(day)).assign(
                datetime=pd.to_datetime(data['time'].apply(lambda x: str(day) + ' ' + str(x)))) \
                .assign(code=str(code)).assign(order=range(len(data.index))).set_index('datetime', drop=False,
                                                                                       inplace=False)
    except:
        return None
1245
def get_today_all(output='pd'):
    

    data = []
    today = str(datetime.date.today())
    codes = QA_fetch_get_stock_list('stock').code.tolist()
    bestip = select_best_ip()['stock']
    for code in codes:
        try:
            l = QA_fetch_get_stock_day(
                code, today, today, '00', ip=bestip)
        except:
            bestip = select_best_ip()['stock']
            l = QA_fetch_get_stock_day(
                code, today, today, '00', ip=bestip)
        if l is not None:
            data.append(l)

    res = pd.concat(data)
    if output in ['pd']:
        return res
    elif output in ['QAD']:
        return QA_DataStruct_Stock_day(res.set_index(['date', 'code'], drop=False))
788857
def deal_list_query(self, code="", trd_env=TrdEnv.REAL, acc_id=0, acc_index=0):
        """"""
        ret, msg = self._check_trd_env(trd_env)
        if ret != RET_OK:
            return ret, msg

        ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
        if ret != RET_OK:
            return ret, msg

        ret, msg, stock_code = self._check_stock_code(code)
        if ret != RET_OK:
            return ret, msg

        query_processor = self._get_sync_query_processor(
            DealListQuery.pack_req, DealListQuery.unpack_rsp)

        kargs = {
            'code': stock_code,
            'trd_mkt': self.__trd_mkt,
            'trd_env': trd_env,
            'acc_id': acc_id,
            'conn_id': self.get_sync_conn_id()
            }
        ret_code, msg, deal_list = query_processor(**kargs)
        if ret_code != RET_OK:
            return RET_ERROR, msg

        col_list = [
            "code", "stock_name", "deal_id", "order_id", "qty", "price",
            "trd_side", "create_time", "counter_broker_id", "counter_broker_name"
        ]
        deal_list_table = pd.DataFrame(deal_list, columns=col_list)

        return RET_OK, deal_list_table
615179
function fetch_all($result_type = SQLITE_BOTH) {
		$retn = array();
		while($item = $this->fetch_array()) {
			$retn[] = $item;
		}
		return $retn;
	}
1213916
def QA_fetch_stock_list_adv(collections=DATABASE.stock_list):
    '''
    
    '''
    stock_list_items = QA_fetch_stock_list(collections)
    if len(stock_list_items) == 0:
        print("QA Error QA_fetch_stock_list_adv call item for item in collections.find() return 0 item, maybe the DATABASE.stock_list is empty!")
        return None
    return stock_list_items