コード例 #1
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)
コード例 #2
0
    def lpr(self, startDate, endDate=None):
        """
        获取贷款基础利率
        Parameters
        ------
          startDate:开始日期(格式:YYYY-MM-DD)
          endDate:结束日期(格式:YYYY-MM-DD,为None时默认取当前日期)
          
        Return
        ------
        DataFrame or List: [{'date':, '1Y':, ...}, ...]
            date:日期
            1Y:1年贷款基础利率
        """
        self._data = pd.DataFrame()
        
        if endDate is None:
            endDate = Utility.getToday()

        request = self._session.get(cf.LPR_URL % (startDate, endDate))
        dataDict = json.loads(request.text)
        dataList = []
        for row in dataDict['records']:
            data = {'date': row['showDateCN'], '1Y': float(row['1Y'])}
            dataList.append(data)
        self._data = pd.DataFrame(dataList, columns=cf.LPR_COLS)
        
        return self._result()
コード例 #3
0
    def xrxd(self, date='', retry=3, pause=0.001):
        """
        获取股票除权除息信息
        Parameters
        ------
            date: string
                format:YYYY-MM-DD
            retry: int, 默认 3
                如遇网络等问题重复执行的次数 
            pause : int, 默认 0
                重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
                
        return
        ------
            Dict or None
                nd, 对应年份
                fh_sh, 分红数额
                djr, 股权登记日
                cqr, 除权日
                FHcontent, 除权除息信息
        """
        data = None

        if not date:
            date = Utility.getToday()

        symbol = Utility.symbol(self.__code)

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

            url = cf.HISTORY_URL % ('fq', 'qfq', symbol, 'day', date, date,
                                    'qfq', Utility.random(17))
            try:
                request = self._session.get(url, timeout=10)
                pattern = re.compile(r'({"nd".+?})')
                result = re.search(pattern, request.text)
                if result:
                    data = eval(result.group(1))
            except Exception as e:
                print(str(e))

            return data

        raise IOError(cf.NETWORK_URL_ERROR_MSG)
コード例 #4
0
    def history(self,
                start='',
                end='',
                ktype='D',
                autype='qfq',
                index=False,
                retry=3,
                pause=0.001):
        """
        获取股票交易历史数据
        ---------
        Parameters:
          start:string
                      开始日期 format:YYYY-MM-DD 为空时取上市首日
          end:string
                      结束日期 format:YYYY-MM-DD 为空时取最近一个交易日
          autype:string
                      复权类型,qfq-前复权 hfq-后复权 None-不复权,默认为qfq
          ktype:string
                      数据类型,D=日k线 W=周 M=月 5=5分钟 15=15分钟 30=30分钟 60=60分钟,默认为D
          retry: int, 默认 3
                     如遇网络等问题重复执行的次数 
          pause : int, 默认 0
                    重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
        return
        -------
          DataFrame or list: [{'date':, 'open':, ...}, ...]
              date 交易日期 (index)
              open 开盘价
              high  最高价
              close 收盘价
              low 最低价
              volume 成交量
              code 股票代码
        """
        self._data = pd.DataFrame()

        url = ''
        dataflag = ''
        symbol = cf.INDEX_SYMBOL[self.__code] if index else Utility.symbol(
            self.__code)
        autype = '' if autype is None else autype

        if (start is not None) & (start != ''):
            end = Utility.getToday() if end is None or end == '' else end

        if ktype.upper() in cf.K_LABELS:
            fq = autype if autype is not None else ''
            if self.__code[:1] in ('1', '5') or index:
                fq = ''

            kline = '' if autype is None else 'fq'
            if ((start is None or start == '') or
                (end is None or end == '')) or (start == end):
                # http://web.ifzq.gtimg.cn/appstock/app/fqkline/get?_var=kline_dayqfq&param=sh600000,day,,,640,qfq&r=0.73327461855388564
                urls = [
                    cf.HISTORY_URL %
                    (kline, fq, symbol, cf.TT_K_TYPE[ktype.upper()], start,
                     end, fq, Utility.random(17))
                ]
            else:
                years = Utility.ttDates(start, end)
                urls = []
                for year in years:
                    startdate = str(year) + '-01-01'
                    enddate = str(year + 1) + '-12-31'
                    # http://web.ifzq.gtimg.cn/appstock/app/fqkline/get?_var=kline_dayqfq2008&param=sh600000,day,2008-01-01,2009-12-31,640,qfq&r=0.73327461855388564
                    url = cf.HISTORY_URL % (kline, fq + str(year), symbol,
                                            cf.TT_K_TYPE[ktype.upper()],
                                            startdate, enddate, fq,
                                            Utility.random(17))
                    urls.append(url)
            dataflag = '%s%s' % (fq, cf.TT_K_TYPE[ktype.upper()])  # qfqday
        elif ktype in cf.K_MIN_LABELS:
            # http://ifzq.gtimg.cn/appstock/app/kline/mkline?param=sh600000,m30,,640&_var=m30_today&r=0.5537154641907898
            urls = [
                cf.HISTORY_MIN_URL % (symbol, ktype, ktype, Utility.random(16))
            ]
            dataflag = 'm%s' % ktype  # m30
        else:
            raise TypeError('ktype input error.')

        for url in urls:
            self._data = self._data.append(self.__handleHistory(
                url, dataflag, symbol, index, ktype, retry, pause),
                                           ignore_index=True)
        if ktype not in cf.K_MIN_LABELS:
            if ((start is not None) & (start != '')) & ((end is not None) &
                                                        (end != '')):
                self._data = self._data[(self._data.date >= start)
                                        & (self._data.date <= end)]

        return self._result()

        raise IOError(cf.NETWORK_URL_ERROR_MSG)
コード例 #5
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)