Beispiel #1
0
    def topList(self, date=None, retry=3, pause=0.001):
        """
        获取每日龙虎榜列表
        Parameters
        --------
        date:string
                    明细数据日期 format:YYYY-MM-DD 如果为空,返回最近一个交易日的数据
        retry : int, 默认 3
                     如遇网络等问题重复执行的次数 
        pause : int, 默认 0
                    重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
        
        Return
        ------
        DataFrame or List: [{'code':, 'name':, ...}, ...]
            code:代码
            name :名称
            pchange:涨跌幅     
            amount:龙虎榜成交额(万)
            buy:买入额(万)
            bratio:占总成交比例
            sell:卖出额(万)
            sratio :占总成交比例
            reason:上榜原因
            unscramble: 解读
            date  :日期
        """
        self._data = pd.DataFrame()

        if date is None:
            if Utility.getHour() < 18:
                date = Utility.lastTradeDate()
            else:
                date = Utility.getToday()
        else:
            if not Utility.isTradeDay(date):
                return None

        for _ in range(retry):
            time.sleep(pause)

            try:
                # http://data.eastmoney.com/DataCenter_V3/stock2016/TradeDetail/pagesize=200,page=1,sortRule=-1,sortType=,startDate=2019-01-10,endDate=2019-01-10,gpfw=0,js=vardata_tab_1.html
                request = self._session.get(cf.LHB_URL % (date, date),
                                            timeout=10)
                request.encoding = 'gbk'
                text = request.text.split('_1=')[1]
                dataDict = Utility.str2Dict(text)

                self._data = pd.DataFrame(dataDict['data'],
                                          columns=cf.LHB_TMP_COLS)
                self._data.columns = cf.LHB_COLS
                self._data['buy'] = self._data['buy'].astype(float)
                self._data['sell'] = self._data['sell'].astype(float)
                self._data['amount'] = self._data['amount'].astype(float)
                self._data['Turnover'] = self._data['Turnover'].astype(float)
                self._data[
                    'bratio'] = self._data['buy'] / self._data['Turnover']
                self._data[
                    'sratio'] = self._data['sell'] / self._data['Turnover']
                self._data['bratio'] = self._data['bratio'].map(cf.FORMAT)
                self._data['sratio'] = self._data['sratio'].map(cf.FORMAT)
                self._data['date'] = date
                for col in ['amount', 'buy', 'sell']:
                    self._data[col] = self._data[col].astype(float)
                    self._data[col] = self._data[col] / 10000
                    self._data[col] = self._data[col].map(cf.FORMAT)
                self._data = self._data.drop('Turnover', axis=1)
            except:
                pass
            else:
                return self._result()

        raise IOError(cf.NETWORK_URL_ERROR_MSG)
Beispiel #2
0
    def todayTicks(self, retry=3, pause=0.001):
        """
        获取当日分笔明细数据
        Parameters
        ------
            retry : int, 默认 3
                      如遇网络等问题重复执行的次数
            pause : int, 默认 0
                     重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
         return
         -------
            DataFrame or list: [{'time':, 'price':, ...}, ...]      
		    time:时间
		    price:当前价格
		    pchange:涨跌幅
		    change:价格变动
		    volume:成交手
		    amount:成交金额(元)
		    type:买卖类型【买盘、卖盘、中性盘】

        """
        self._data = pd.DataFrame()

        if self.__code is None or len(self.__code) != 6:
            return None

        if not Utility.isTradeDay():
            return None

        # 不到交易时间
        openTime = time.mktime(
            time.strptime(Utility.getToday() + ' 09:25:00',
                          '%Y-%m-%d %H:%M:%S'))
        now = time.time()
        if now < openTime:
            return None

        symbol = Utility.symbol(self.__code)
        date = Utility.getToday()

        for _ in range(retry):
            time.sleep(pause)

            try:
                # http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_Transactions.getAllPageTime?date=2018-12-26&symbol=sh600000
                request = self._session.get(cf.TODAY_TICKS_PAGE_URL %
                                            (date, symbol),
                                            timeout=10)
                request.encoding = 'gbk'
                text = request.text[1:-1]
                data_dict = Utility.str2Dict(text)
                pages = len(data_dict['detailPages'])

                self._writeHead()
                for pNo in range(1, pages + 1):
                    # http://vip.stock.finance.sina.com.cn/quotes_service/view/vMS_tradedetail.php?symbol=sh600000&date=2018-12-26&page=1
                    url = cf.TODAY_TICKS_URL % (symbol, date, pNo)
                    self._data = self._data.append(self.__handleTicks(
                        url, cf.TODAY_TICK_COLUMNS, retry, pause),
                                                   ignore_index=True)
            except Exception as e:
                print(str(e))
            else:
                return self._result()

        raise IOError(cf.NETWORK_URL_ERROR_MSG)