コード例 #1
0
def job_once_global_tick(ts):
    """
    获取全部商品分笔数据
    :param ts:
    :return:
    """
    global is_closing
    df = ts.get_stock_basics()
    if df is None:
        return
    cont = False
    #lastsymbol = '300598'
    for symbol in df['name'].index.values:
        # if symbol == lastsymbol:
        #     cont = True
        # if not cont:
        #     continue
        for ndays in range(1, 2, 1):
            if not is_closing:
                day = DateUtil.getDatetimePastStr(DateUtil.getDatetimeToday(),
                                                  ndays)
                if not is_holiday(day):
                    ts.get_tick_data(symbol, day)
                    time.sleep(1)
                else:
                    logging.info('is holiday')
        if not is_closing:
            time.sleep(2)
コード例 #2
0
def job_realtime_global(ts):
    """
    交易日里读取指数信息和全盘Snap(20秒左右)
    :param ts:
    :return:
    """
    global is_closing
    today = DateUtil.getDatetimeToday()
    while not is_closing and not is_holiday(DateUtil.date_toString(today)):
        ts.get_index()
        time.sleep(3)
        ts.get_today_all()
        time.sleep(5)
コード例 #3
0
def job_global_remedy_task(ts):
    """
    定时作业,收盘数据:分笔数据,5日数据和日线数据
    :param ts:
    :return:
    """
    global is_closing
    df = ts.get_stock_basics()
    if df is None:
        return
    ndays = 1
    startDate = '2018-07-09'
    endDate = DateUtil.getDatetimeFutureStr(DateUtil.string_toDate(startDate),
                                            ndays)
    days = []
    days.append(startDate)
    for day in range(1, ndays, 1):
        continueDate = DateUtil.getDatetimeFutureStr(
            DateUtil.string_toDate(startDate), day)
        days.append(continueDate)

    cont = False
    #lastsymbol = '603895'
    for symbol in df['name'].index.values:
        # if symbol == lastsymbol:
        #     cont = True
        # if not cont:
        #     continue
        for day in days:
            if not is_closing:
                if not is_holiday(day):
                    ts.get_tick_data(symbol, day)
                    time.sleep(1)
                else:
                    logging.info('is holiday')

        ts.get_hist_data(symbol, startDate, endDate, '5')
        time.sleep(2)
        ts.get_hist_data(symbol, startDate, endDate)
        time.sleep(2)
コード例 #4
0
def top_list(date=None, retry_count=3, pause=0.001):
    """
    获取每日龙虎榜列表
    Parameters
    --------
    date:string
                明细数据日期 format:YYYY-MM-DD 如果为空,返回最近一个交易日的数据
    retry_count : int, 默认 3
                 如遇网络等问题重复执行的次数 
    pause : int, 默认 0
                重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
    
    Return
    ------
    DataFrame
        code:代码
        name :名称
        pchange:涨跌幅     
        amount:龙虎榜成交额(万)
        buy:买入额(万)
        bratio:占总成交比例
        sell:卖出额(万)
        sratio :占总成交比例
        reason:上榜原因
        date  :日期
    """
    if date is None:
        if du.get_hour() < 18:
            date = du.last_tddate()
        else:
            date = du.today()
    else:
        if (du.is_holiday(date)):
            return None
    for _ in range(retry_count):
        time.sleep(pause)
        try:
            request = Request(
                rv.LHB_URL % (ct.P_TYPE['http'], ct.DOMAINS['em'], date, date))
            text = urlopen(request, timeout=10).read()
            text = text.decode('GBK')
            text = text.split('_1=')[1]
            text = eval(
                text,
                type('Dummy', (dict, ), dict(__getitem__=lambda s, n: n))())
            text = json.dumps(text)
            text = json.loads(text)
            df = pd.DataFrame(text['data'], columns=rv.LHB_TMP_COLS)
            df.columns = rv.LHB_COLS
            df = df.fillna(0)
            df = df.replace('', 0)
            df['buy'] = df['buy'].astype(float)
            df['sell'] = df['sell'].astype(float)
            df['amount'] = df['amount'].astype(float)
            df['Turnover'] = df['Turnover'].astype(float)
            df['bratio'] = df['buy'] / df['Turnover']
            df['sratio'] = df['sell'] / df['Turnover']
            df['bratio'] = df['bratio'].map(ct.FORMAT)
            df['sratio'] = df['sratio'].map(ct.FORMAT)
            df['date'] = date
            for col in ['amount', 'buy', 'sell']:
                df[col] = df[col].astype(float)
                df[col] = df[col] / 10000
                df[col] = df[col].map(ct.FORMAT)
            df = df.drop('Turnover', axis=1)
        except Exception as e:
            print(e)
        else:
            return df
    raise IOError(ct.NETWORK_URL_ERROR_MSG)
コード例 #5
0
ファイル: trading.py プロジェクト: hsstock/hsstock
def get_h_data(code,
               start=None,
               end=None,
               autype='qfq',
               index=False,
               retry_count=3,
               pause=0.001,
               drop_factor=True):
    '''
    获取历史复权数据
    Parameters
    ------
      code:string
                  股票代码 e.g. 600848
      start:string
                  开始日期 format:YYYY-MM-DD 为空时取当前日期
      end:string
                  结束日期 format:YYYY-MM-DD 为空时取去年今日
      autype:string
                  复权类型,qfq-前复权 hfq-后复权 None-不复权,默认为qfq
      retry_count : int, 默认 3
                 如遇网络等问题重复执行的次数 
      pause : int, 默认 0
                重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
      drop_factor : bool, 默认 True
                是否移除复权因子,在分析过程中可能复权因子意义不大,但是如需要先储存到数据库之后再分析的话,有该项目会更加灵活
    return
    -------
      DataFrame
          date 交易日期 (index)
          open 开盘价
          high  最高价
          close 收盘价
          low 最低价
          volume 成交量
          amount 成交金额
    '''

    start = du.today_last_year() if start is None else start
    end = du.today() if end is None else end
    qs = du.get_quarts(start, end)
    qt = qs[0]
    ct._write_head()
    data = _parse_fq_data(_get_index_url(index, code, qt), index, retry_count,
                          pause)
    if data is None:
        data = pd.DataFrame()
    if len(qs) > 1:
        for d in range(1, len(qs)):
            qt = qs[d]
            ct._write_console()
            df = _parse_fq_data(_get_index_url(index, code, qt), index,
                                retry_count, pause)
            if df is None:  # 可能df为空,退出循环
                break
            else:
                data = data.append(df, ignore_index=True)
    if len(data) == 0 or len(
            data[(data.date >= start) & (data.date <= end)]) == 0:
        return pd.DataFrame()
    data = data.drop_duplicates('date')
    if index:
        data = data[(data.date >= start) & (data.date <= end)]
        data = data.set_index('date')
        data = data.sort_index(ascending=False)
        return data
    if autype == 'hfq':
        if drop_factor:
            data = data.drop('factor', axis=1)
        data = data[(data.date >= start) & (data.date <= end)]
        for label in ['open', 'high', 'close', 'low']:
            data[label] = data[label].map(ct.FORMAT)
            data[label] = data[label].astype(float)
        data = data.set_index('date')
        data = data.sort_index(ascending=False)
        return data
    else:
        if autype == 'qfq':
            if drop_factor:
                data = data.drop('factor', axis=1)
            df = _parase_fq_factor(code, start, end)
            df = df.drop_duplicates('date')
            df = df.sort_values('date', ascending=False)
            firstDate = data.head(1)['date']
            frow = df[df.date == firstDate[0]]
            rt = get_realtime_quotes(code)
            if rt is None:
                return pd.DataFrame()
            if ((float(rt['high']) == 0) & (float(rt['low']) == 0)):
                preClose = float(rt['pre_close'])
            else:
                if du.is_holiday(du.today()):
                    preClose = float(rt['price'])
                else:
                    if (du.get_hour() > 9) & (du.get_hour() < 18):
                        preClose = float(rt['pre_close'])
                    else:
                        preClose = float(rt['price'])

            rate = float(frow['factor']) / preClose
            data = data[(data.date >= start) & (data.date <= end)]
            for label in ['open', 'high', 'low', 'close']:
                data[label] = data[label] / rate
                data[label] = data[label].map(ct.FORMAT)
                data[label] = data[label].astype(float)
            data = data.set_index('date')
            data = data.sort_index(ascending=False)
            return data
        else:
            for label in ['open', 'high', 'close', 'low']:
                data[label] = data[label] / data['factor']
            if drop_factor:
                data = data.drop('factor', axis=1)
            data = data[(data.date >= start) & (data.date <= end)]
            for label in ['open', 'high', 'close', 'low']:
                data[label] = data[label].map(ct.FORMAT)
            data = data.set_index('date')
            data = data.sort_index(ascending=False)
            data = data.astype(float)
            return data