Beispiel #1
0
def get_k_data_JQ(stk,
                  count=None,
                  start_date=None,
                  end_date=None,
                  freq='daily'):
    """
    使用JQData来下载stk的历史数据
    :param stk_code:
    :param amount:
    :return:
    """
    if 'm' in freq:
        end_date = add_date_str(get_current_date_str(), 1)

    if pd.isnull(end_date):
        end_date = get_current_date_str()
    try:

        # 增加以兼容list的情况
        if isinstance(stk, list):
            stk_code = [jqdatasdk.normalize_code(x) for x in stk]

            df = jqdatasdk.get_price(stk_code,
                                     frequency=freq,
                                     count=count,
                                     end_date=end_date,
                                     start_date=start_date)

        elif stk in ['sh', 'sz', 'cyb', 'hs300', 'sz50', 'zz500']:
            stk_code_normal = JQMethod.get_index_jq_code(stk)
            df = jqdatasdk.get_price(stk_code_normal,
                                     frequency=freq,
                                     count=count,
                                     start_date=start_date,
                                     end_date=end_date)
        else:
            df = jqdatasdk.get_price(jqdatasdk.normalize_code(stk),
                                     frequency=freq,
                                     count=count,
                                     end_date=end_date,
                                     start_date=start_date)

        if df.empty:
            return df

        df['datetime'] = df.index
        df['date'] = df.apply(lambda x: str(x['datetime'])[:10], axis=1)

        return df
    except Exception as e:
        print('函数get_k_data_JQ:出错!错误详情:\n' + str(e))
        return pd.DataFrame()
Beispiel #2
0
def get_RT_price(stk_code, source='jq'):

    if source == 'jq':
        # 使用聚宽数据接口替代
        if stk_code in ['sh', 'sz', 'cyb']:
            stk_code_normal = {
                'sh': '000001.XSHG',
                'sz': '399001.XSHE',
                'cyb': '399006.XSHE'
            }[stk_code]

        else:
            stk_code_normal = jq.normalize_code(stk_code)

        current_price = float(
            jq.get_price(stk_code_normal,
                         count=1,
                         end_date=get_current_date_str())['close'].values[0])

    elif source == 'ts':
        # 获取实时价格
        current_price = float(
            ts.get_realtime_quotes(stk_code)['price'].values[0])

    return current_price
Beispiel #3
0
    def init_finance_table(self, start_date=0):
        self.authenticate()
        self.stock = jdk.normalize_code(self.stock)
        self.stock_info = jdk.get_security_info(self.stock)

        if self.stock_info is None:
            print('Error: Cannot get data or stock code not correct!')
        '''Internal usage. To get finance table'''
        
        q = jdk.query(jdk.valuation).filter(jdk.valuation.code == self.stock)
        end_date = datetime.now().date()
        
        if start_date == 0:
            df = jdk.get_fundamentals_continuously(q, end_date=end_date, count=5000)
        else:
            # get the days between start date and end date
            date_span = jdk.get_trade_days(start_date=start_date, end_date=end_date)
            if len(date_span) == 0:
                return
            df = jdk.get_fundamentals_continuously(q, end_date=end_date, count=len(date_span))

        if df is None:
            return

        self.finance_data = df.swapaxes('items', 'minor_axis')
        self.finance_data = self.finance_data[self.stock]
        del self.finance_data['day.1']
        del self.finance_data['code.1']
        del self.finance_data['id']
        return
Beispiel #4
0
def wrap_draw_line(stock, day, choice):
    name,password = read_account(config_file)
    authenticaiton(name, password)
    stock_name = jqdatasdk.normalize_code(stock)
    print(stock_name)
    file_name = draw_line(stock_name, choice, days=day)
    return file_name
Beispiel #5
0
    def run(self):
        # 抓取fund列表
        df = finance.run_query(query(finance.FUND_MAIN_INFO))
        df.index.name = 'entity_id'
        df = df.reset_index()
        # 上市日期
        df.rename(columns={'start_date': 'timestamp'}, inplace=True)
        df['timestamp'] = pd.to_datetime(df['timestamp'])
        df['list_date'] = df['timestamp']
        df['end_date'] = pd.to_datetime(df['end_date'])

        df['entity_id'] = df.main_code.apply(lambda x: normalize_code(x))
        df['entity_id'] = df['entity_id'].apply(
            lambda x: to_entity_id(entity_type='fund', jq_code=x))

        df['id'] = df['entity_id']
        df['entity_type'] = 'fund'
        df['exchange'] = df['entity_id'].apply(
            lambda x: get_entity_exchange(x))
        df['code'] = df['entity_id'].apply(lambda x: get_entity_code(x))
        df['category'] = 'fund'
        # df['choice_code'] = df.apply(lambda x:x.main_code+'.'+x.exchange.upper(),axis=1)
        # loginResult = c.start("ForceLogin=1", '')
        # df['underlying_index_code'] = df.apply(lambda x:c.css(x.choice_code, "BMINDEXCODE", "Rank=1").Data if x.operate_mode == 'ETF' else None,axis=1)
        # df['underlying_index_code'] = df['underlying_index_code'].apply(lambda x:[i for i in x.values()][0][0].lower().replace(".","_") if x else None)
        # c.stop()
        df_to_db(df,
                 data_schema=FundDetail,
                 provider=self.provider,
                 force_update=self.force_update)

        # self.logger.info(df_index)
        self.logger.info("persist etf list success")
        logout()
Beispiel #6
0
    def run(self):
        # 抓取fund列表
        df = finance.run_query(query(finance.FUND_MAIN_INFO))
        df.index.name = 'entity_id'
        df = df.reset_index()
        # 上市日期
        df.rename(columns={'start_date': 'timestamp'}, inplace=True)
        df['timestamp'] = pd.to_datetime(df['timestamp'])
        df['list_date'] = df['timestamp']
        df['end_date'] = pd.to_datetime(df['end_date'])

        df['entity_id'] = df.main_code.apply(lambda x: normalize_code(x))
        df['entity_id'] = df['entity_id'].apply(
            lambda x: to_entity_id(entity_type='fund', jq_code=x))

        df['id'] = df['entity_id']
        df['entity_type'] = 'fund'
        df['exchange'] = df['entity_id'].apply(
            lambda x: get_entity_exchange(x))
        df['code'] = df['entity_id'].apply(lambda x: get_entity_code(x))

        df['category'] = 'fund'

        df_to_db(df,
                 data_schema=FundDetail,
                 provider=self.provider,
                 force_update=self.force_update)

        # self.logger.info(df_index)
        self.logger.info("persist etf list success")
        logout()
Beispiel #7
0
 def get_1min_bars(self, stock_id: str, count: int, end_date: str):
     return jq.get_bars(
         jq.normalize_code(stock_id),
         count,
         unit='1m',
         fields=['date', 'open', 'close', 'high', 'low', 'volume', 'money'],
         include_now=False,
         end_dt=end_date)
Beispiel #8
0
    def init_light(self):
        self.authenticate()
        self.stock = jdk.normalize_code(self.stock)
        self.stock_info = jdk.get_security_info(self.stock)
        
        if self.stock_info is None:
            print('Error: Cannot get data or stock code not correct!')

        self.finance_table = self.__generate_table_name() + '_finance'
        self.price_table = self.__generate_table_name() + '_price'
Beispiel #9
0
def get_current_price_JQ(stk_code):

    # 使用聚宽数据接口替代
    if stk_code in ['sh', 'sz', 'cyb']:
        stk_code_normal = {
            'sh': '000001.XSHG',
            'sz': '399001.XSHE',
            'cyb': '399006.XSHE'
        }[stk_code]

    else:
        stk_code_normal = jq.normalize_code(stk_code)

    current_price = float(jq.get_price(stk_code_normal, count=1, end_date=get_current_date_str())['close'].values[0])

    return current_price
Beispiel #10
0
    def to_jq_symbol(code: str) -> str:
        # 沪深300指数
        if code.startswith("000300"):
            return "000300.XSHG"

        if code.endswith(".XSHG") \
            or code.endswith(".XSHE"):
            return code

        jq_code = jq.normalize_code(code)

        if jq_code is None:
            if code.startswith("6"):
                return f"{code}.XSHG"
            else:
                return f"{code}.XSHE"
        return jq_code
Beispiel #11
0
    def init(self):
        '''
        Get price, open, close, high, low, volume. And finantial data, TTM, PB, etc. 
        '''
        self.authenticate()
        self.stock = jdk.normalize_code(self.stock)
        self.stock_info = jdk.get_security_info(self.stock)

        if self.stock_info is None:
            print('Error: Cannot get data or stock code not correct!')

        self.finance_table = self.__generate_table_name() + '_finance'
        self.price_table = self.__generate_table_name() + '_price'

        price_data = jdk.get_price(self.stock, start_date=self.stock_info.start_date, end_date=datetime.now())
        # remove NaN data
        self.price_data = price_data.dropna()
        self.price_data.index.name = 'date'

        print('%s[%s] from %s - %s ' % (self.stock_info.display_name, self.stock, 
               self.stock_info.start_date, self.stock_info.end_date))
Beispiel #12
0
def _get_bar_range(jq: jq, code: str, season_date: datetime):
    """
    返回前3个月的涨幅,后两个月的最大涨幅
    """
    query_end_date = season_date + timedelta(days=63)

    if datetime.now() < query_end_date:
        return None

    df = jq.get_bars(jq.normalize_code(code),
                     6,
                     unit='1M',
                     fields=['date', 'open', 'high', 'low', 'close', 'volume'],
                     include_now=True,
                     end_dt=query_end_date)
    if df is None:
        return None
    size = df.shape[0]
    if size != 6:
        return None

    ##前3个月的涨幅
    ranges = []
    for i in range(1, 4):
        _close = float(df.at[i, 'close'])
        _close_pre = float(df.at[i - 1, 'close'])
        v = (_close - _close_pre) / _close_pre
        ranges.append(v)

    ###后两个月之内的最大涨幅
    close = float(df.at[3, 'close'])
    high = close
    for i in range(4, 6):
        _high = float(df.at[i, 'high'])
        if _high > high:
            high = _high
    max_range = (high - close) / close
    return ranges[0], ranges[1], ranges[2], max_range
Beispiel #13
0
def get_k_data_JQ(stk_code, count=None, start_date=None, end_date=get_current_date_str(), freq='daily'):
    """
    使用JQData来下载stk的历史数据
    :param stk_code:
    :param amount:
    :return:
    """
    if stk_code in ['sh', 'sz', 'cyb']:

        stk_code_normal = {
            'sh': '000001.XSHG',
            'sz': '399001.XSHE',
            'cyb': '399006.XSHE'
        }[stk_code]
        df = jqdatasdk.get_price(stk_code_normal, frequency=freq, count=count, start_date=start_date,
                                 end_date=end_date)
    else:
        df = jqdatasdk.get_price(jqdatasdk.normalize_code(stk_code), frequency=freq, count=count,
                                 end_date=end_date, start_date=start_date)

    df['datetime'] = df.index
    df['date'] = df.apply(lambda x: str(x['datetime'])[:10], axis=1)

    return df
Beispiel #14
0
                      '000760.SZ': ['2010-01-01', '', '被st了的股票', 1], '000752.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '000737.SZ': ['2010-01-01', '', '被st了的股票', 1], '000727.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '000707.SZ': ['2010-01-01', '', '被st了的股票', 1], '000611.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '000585.SZ': ['2010-01-01', '', '被st了的股票', 1], '000571.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '000509.SZ': ['2010-01-01', '', '被st了的股票', 1], '000504.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '000422.SZ': ['2010-01-01', '', '被st了的股票', 1], '000410.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '000409.SZ': ['2010-01-01', '', '被st了的股票', 1], '000010.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '002290.SZ': ['2010-01-01', '', '被st了的股票', 1], '002207.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '002102.SZ': ['2010-01-01', '', '被st了的股票', 1], '000971.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '000572.SZ': ['2010-01-01', '', '被st了的股票', 1], '000939.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '000981.SZ': ['2010-01-01', '', '被st了的股票', 1], '002604.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '002450.SZ': ['2010-01-01', '', '被st了的股票', 1], '000670.SZ': ['2010-01-01', '', '被st了的股票', 1],
                      '002260.SZ': ['2010-01-01', '', '被st了的股票', 1], '000787.SZ': ['2010-01-01', '', '被st了的股票', 1]}
    lst = []
    n=0
    for x, y in remove_st_data.items():
        print(x)
        code = jqdatasdk.normalize_code(x)
        n+=1
        # print()

        # finance.run_query(query(finance.STK_NAME_HISTORY).filter(finance.STK_NAME_HISTORY.code == code))

        q = query(finance.STK_STATUS_CHANGE).filter(finance.STK_STATUS_CHANGE.code == code)
        df = finance.run_query(q)
        lst.append(df)
    ret = pd.concat(lst)
    print(ret)
    print(n)
    ret.to_excel('c://e/data/change.xlsx', encoding='gbk')
Beispiel #15
0
# encoding=utf-8
try:
    # 获取实时价格
    current_price = float(ts.get_realtime_quotes(stk_code)['price'].values[0])

except:
    # 使用聚宽数据接口替代
    if stk_code in ['sh', 'sz', 'cyb']:
        stk_code_normal = {
            'sh': '000001.XSHG',
            'sz': '399001.XSHE',
            'cyb': '399006.XSHE'
        }[stk_code]

    else:
        stk_code_normal = normalize_code(stk_code)

    current_price = float(jq.get_price(stk_code_normal, count=1, end_date=get_current_date_str())['close'].values[0])

# 计算实时偏离度
list_history = dict['latest_data']
list_history.append(current_price)

M_diff = (current_price - np.mean(list_history)) / current_price


M_list = dict['history_M_diverge_data']
M_list.append(M_diff)

r_list = [relativeRank(dict['history_M_diverge_data'], x) for x in M_list]
Beispiel #17
0
 def get_normalize_code(self, code):
     return jqs.normalize_code(code)
Beispiel #18
0
# encoding=utf-8
Beispiel #19
0
        '日期': str,
        '股票代码': str
    }).dropna(how='all')
except:
    df_pos = pd.read_csv(open(fp, 'rb'),
                         encoding='gbk',
                         dtype={
                             '日期': str,
                             '股票代码': str
                         }).dropna(how='all')
df_pos = df_pos[~df_pos['股票代码'].isnull()]
df_pos['股票代码'] = ["{:0>6d}".format(int(x)) for x in df_pos['股票代码'].tolist()]

# ============行情数据===========================
holdings = df_pos['股票代码'].unique()
holdings = [jq.normalize_code(x) for x in holdings if x[0] in ['0', '6', '3']]
prices = jq.get_price(holdings, end_date=datetime.datetime.now(), count=100)
# series
close = prices['close'].iloc[-1]
hi = prices['high'].iloc[-1]
lo = prices['low'].iloc[-1]
open = prices['open'].iloc[-1]
# dataframe
vol = prices['volume']

# ===========计算放量上影线================================
#  上影线:(最高-收盘)/(最高-最低)
#  放量: 当日成交量/20日平均成交量
#  上影线*放量 > 3,  表明放量至少大于三倍,如果上影线为0.5,则需要放量6倍
syx = (hi - close) / (hi - lo)
fangda = vol.iloc[-1] / vol.iloc[-20:].mean()
Beispiel #20
0
    futureID= 'IC2009.CCFX'
    jqID= jq.normalize_code(futureID)
    dataTable= myjqcfg.futureTickDT
    tickPdData= myapi.getDateData(jqID, intDate)
    
    indexID= '000001.XSHG'
    jq.get_security_info(indexID).type
    
    
    
    """

    codelist = [
        '510500', '510300', '510330', 'IF2003', 'IF2006', 'IF2009', 'IC2003',
        'IC2006', 'IC2009'
    ]
    codelist = ['000300.SH', '000905.SH']
    jqIDList = jq.normalize_code(codelist)
    ld = jq.get_trade_days(start_date='20200101',
                           end_date='20200623',
                           count=None)
    for dt in ld:
        intDate = int(dt.strftime("%Y%m%d"))
        print('dealing %d, time elapsed: %.2f min' % (intDate,
                                                      (ti.time() - t0) / 60))
        for jqID in jqIDList:
            tickPdData = myapi.getDateData(jqID, intDate)

    myapi.close()
    print('All done, time elapsed: %.2f min' % ((ti.time() - t0) / 60))
Beispiel #21
0
def get_k_data_JQ(start_date=None, end_date=None, freq='daily'):
    """
    获得A股所有股票日数据

    Args:
        start_date (str): 起始日
        end_date (str): 结束日
    """

    #所有股票代码等
    stk = open('./codes-joinquan.csv', 'r', encoding='utf-8').readlines()

    stk_code = [jqdatasdk.normalize_code(x) for x in stk]
    log.info("stk_code {}".format(stk_code))
    #df = jqdatasdk.get_price(stk_code, frequency=freq,
    #                            end_date=end_date, start_date=start_date)
    #print(df.axes)
    #print(df.head)

    sleep_time=0.4
    # 遍历所有股票ID
    #for code in stock_list.ts_code:
    for code in stk_code:
        code = code.strip('\n')
        log.info(code)
        t0 = time.time()

        df = jqdatasdk.get_price(code, frequency=freq,
                                end_date=end_date, start_date=start_date, fq='pre')
        log.info(df.axes)
        log.info(df.head())
        log.info(df.tail())
        log.info(df.columns)
        log.info(df.index)

        df['date'] = df.index#.to_pydatetime()

        #log.info(df['date'])
        log.info(df.axes)
        log.info(df.head())
        log.info(df.columns)
        log.info(df.dtypes)
        #log.info(df.info())
        #查看缺失及每列数据类型
        
        data = json.loads(df.T.to_json()).values()
        #log.info(data)
        for row in data:
            #log.info(type(row['date']))
            row['date'] = datetime.fromtimestamp(row['date']/1000 - 60*60*8)# ns to s
            #row['date'] = datetime.utcfromtimestamp(row['date']/1000)# ns to s; same with up line


        elapsed = time.time() - t0
        log.info("get data {} rows for {} used {:.2f}s ".format(len(data), code, elapsed))


        t1 = time.time()

        # D5=MA(df.close,5)#5日均线
        # df['D5']=pd.DataFrame({'D5':D5})
        # D10=MA(df.close,10)#10日均线
        # df['D10']=pd.DataFrame({'D10':D10})
        # D20=MA(df.close,20)#20日均线
        # df['D20']=pd.DataFrame({'D20':D20})


        collection=database[code]    #建立以股票名命名的集合
        collection.insert_many(data)    #存储到MongoDB数据库中
        elapsed = time.time() - t1
        log.info("collection.insert_many used: {:.2f}s".format(elapsed))
        # 对股票每一天数据进行保存,注意唯一性
        # 这里也可以批量创建,速度更快,但批量创建容易丢失数据
        # 这里为了保证数据的绝对稳定性,选择一条条创建
        #for row in data:
        #    daily.update({"_id": f"{row['ts_code']}-{row['trade_date']}"}, row, upsert=True)

        time.sleep(sleep_time)     #暂停,tushare对积分不足用户限制每分钟200次访问,积分很重要
        if np.size(df,0)<60:
            time.sleep(sleep_time)
            continue
def importStockDataDailyJQ(codes=[], names=[], asset='E', adj='qfq'):
    db = cx_Oracle.connect('c##stock', 'didierg160', 'myoracle')  #创建连接
    cr = db.cursor()

    code_tail = ""
    if asset == "INDEX":
        code_tail = "zs"

    for code, name in zip(codes, names):
        start_date = ""

        if adj == "qfq":
            if isXR(code=code):
                sql = "delete tb_stock_data_daily where code = '" + code + code_tail + "'"
                cr.execute(sql)

            #time.sleep(1)

        start_date = gsd.get_code_max_shi_jian(code=code + code_tail)

        if start_date == "None":
            start_date = ""

        tsFaile = 1

        while tsFaile != 0:
            try:
                #if tsFaile >=2 :
                #    cons = ts.get_apis()

                #df = ts.bar(code, conn=cons, adj=adj,asset=asset, start_date=start_date, end_date='',retry_count = 2)
                #print(df)

                import datetime
                df = jq.get_price(
                    jq.normalize_code(code),
                    start_date=start_date,
                    end_date=datetime.datetime.now().strftime("%Y-%m-%d"),
                    skip_paused=True)
                df = df.dropna()
                df = df.sort_index(ascending=False)
                #print(df)

                tsFaile = 0
            except Exception as e:
                #                 ts.close_apis(conn=cons)
                if "找不到" in str(e):
                    tsFaile = 4
                else:
                    time.sleep(5)
                print(code, start_date, "importStockDataDaily fail:", tsFaile,
                      e)
                if tsFaile <= 3:
                    tsFaile += 1
                else:
                    break

        if tsFaile > 0:
            continue

        df["datetime"] = df.index
        df = df.reset_index(drop=True)
        df_shift = df.shift(-1)

        for row, row_s in zip(df.itertuples(), df_shift.itertuples()):
            if round(float(getattr(row, "volume"))) < 1:
                continue

#             if len(getattr(row,"datetime")) <10 :
#                 continue

            shi_jian = str(getattr(row, "datetime"))[0:10]

            if len(shi_jian) < 10:
                continue

            if shi_jian == start_date:
                continue

            if str(getattr(row_s, "close")) == "nan":
                price_last_day = "null"
                amount_last_day = "null"
                zhang_die = "null"
                zhang_die_rate = "null"
            else:
                price_last_day = getattr(row_s, "close")
                amount_last_day = str(getattr(row_s, "money"))
                zhang_die = getattr(row, "close") - getattr(row_s, "close")
                zhang_die_rate = getattr(row, "close") / getattr(
                    row_s, "close") - 1

            sql = "insert into tb_stock_data_daily "
            sql += "(                   "
            sql += "  code            , "
            sql += "  name            , "
            sql += "  price_today_open, "
            sql += "  price           , "
            sql += "  max_price       , "
            sql += "  min_price       , "
            sql += "  vol             , "
            sql += "  amount          , "
            sql += "  amount_last_day , "
            sql += "  shi_jian        , "
            sql += "  price_last_day  , "
            sql += "  zhang_die       , "
            sql += "  zhang_die_rate    "
            sql += ")                   "
            sql += "values              "
            sql += "(                   "
            sql += " '" + code + code_tail + "',"
            sql += " '" + name + "',"
            sql += "  " + str(getattr(row, "open")) + ","
            sql += "  " + str(getattr(row, "close")) + ","
            sql += "  " + str(getattr(row, "high")) + ","
            sql += "  " + str(getattr(row, "low")) + ","
            sql += "  " + str(getattr(row, "volume")) + ","
            sql += "  " + str(getattr(row, "money")) + ","
            sql += "  " + amount_last_day + ","
            sql += "  to_date('" + shi_jian + " 15:00:00','yyyy-mm-dd hh24:mi:ss'),"
            sql += "  " + str(price_last_day) + ","
            sql += "  " + str(zhang_die) + ","
            sql += "  " + str(zhang_die_rate) + " "
            sql += ")"

            try:
                cr.execute(sql)
            except Exception as e:
                print(sql)

        #time.sleep(1)
        db.commit()
        now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        print(now, code, "done")
    db.commit()
    cr.close()
    db.close()
Beispiel #23
0
 def normalize_code(self, code):
     '''Normalize code'''
     return normalize_code(code)
Beispiel #24
0
 def normalizecode(self, codes):
     return jq.normalize_code(codes)
Beispiel #25
0
    def record(self, entity, start, end, size, timestamps):
        if not end:
            end = to_time_str(now_pd_timestamp())

        fq = fq_ref_date = None
        if self.adjust_type == AdjustType.hfq:
            fq = 'post'
            fq_ref_date = '2000-01-01'

        elif self.adjust_type == AdjustType.qfq:
            fq = 'pre'
            fq_ref_date = to_time_str(now_pd_timestamp())

        security = normalize_code(entity.code)
        if not self.end_timestamp:
            df = get_price(
                security,
                start_date=start,
                end_date=end,
                frequency=self.jq_trading_level,
                fields=['open', 'close', 'low', 'high', 'volume', 'money'],
                fq=fq)
        else:
            end_timestamp = to_time_str(self.end_timestamp)
            df = get_price(
                security,
                count=size,
                frequency=self.jq_trading_level,
                fields=['open', 'close', 'low', 'high', 'volume', 'money'],
                end_date=end_timestamp,
                fq=fq)

        if pd_is_not_null(df):
            df['name'] = entity.name
            df.index.name = 'timestamp'
            df.rename(columns={
                'money': 'turnover',
                'date': 'timestamp'
            },
                      inplace=True)

            df['entity_id'] = entity.id
            df['timestamp'] = pd.to_datetime(df.index)
            df['provider'] = 'joinquant'
            df['level'] = self.level.value
            df['code'] = entity.code

            # 判断是否需要重新计算之前保存的前复权数据
            if self.adjust_type == AdjustType.qfq and df.open.dropna(
            ).shape[0] != 0:
                check_df = df.head(1)
                check_date = check_df['timestamp'][0]
                current_df = get_kdata(entity_id=entity.id,
                                       provider=self.provider,
                                       start_timestamp=check_date,
                                       end_timestamp=check_date,
                                       limit=1,
                                       level=self.level,
                                       adjust_type=self.adjust_type)
                if pd_is_not_null(current_df):
                    old = current_df.iloc[0, :]['close']
                    new = check_df['close'][0]
                    # 相同时间的close不同,表明前复权需要重新计算
                    if round(old, 2) != round(new, 2):
                        qfq_factor = new / old
                        last_timestamp = pd.Timestamp(check_date)
                        self.recompute_qfq(entity,
                                           qfq_factor=qfq_factor,
                                           last_timestamp=last_timestamp)

            def generate_kdata_id(se):
                if self.level >= IntervalLevel.LEVEL_1DAY:
                    return "{}_{}".format(
                        se['entity_id'],
                        to_time_str(se['timestamp'], fmt=TIME_FORMAT_DAY))
                else:
                    return "{}_{}".format(
                        se['entity_id'],
                        to_time_str(se['timestamp'], fmt=TIME_FORMAT_ISO8601))

            df['id'] = df[['entity_id', 'timestamp']].apply(generate_kdata_id,
                                                            axis=1)
            df_to_db(df=df,
                     data_schema=self.data_schema,
                     provider=self.provider,
                     force_update=self.force_update)
        return None
###### 有息负债  ################
###### 有息负债  ################
###### 有息负债  ################
# shortterm_loan	短期借款	decimal(20,4)
# non_current_liability_in_one_year	一年内到期的非流动负债	decimal(20,4)
# longterm_loan	长期借款	decimal(20,4)
# bonds_payable	应付债券	decimal(20,4)
import pandas
# qianyuandianli=pandas.DataFrame(columns=['A', 'B', 'C', 'D','A', 'B', 'C', 'D','A'])
from jqdatasdk import finance
codeshuidian = [
    'sh600900', 'sh600025', 'sh600886', 'sh600236', '002039', 'sh600674',
    'sz000722', 'sz000883', '000791.SZ', '000993', '000601', '600868'
]
for code in codeshuidian:
    codeqianyuandianli = jqdatasdk.normalize_code(code)
    # print("\n*********",code,"***********************")
    qianyuandianli1 = finance.run_query(
        jqdatasdk.query(
            finance.STK_BALANCE_SHEET.shortterm_loan,
            finance.STK_BALANCE_SHEET.longterm_loan,
            finance.STK_BALANCE_SHEET.non_current_liability_in_one_year,
            finance.STK_BALANCE_SHEET.bonds_payable,
            finance.STK_BALANCE_SHEET.total_assets,
            finance.STK_BALANCE_SHEET.code, finance.STK_BALANCE_SHEET.pub_date,
            finance.STK_BALANCE_SHEET.start_date,
            finance.STK_BALANCE_SHEET.end_date,
            finance.STK_BALANCE_SHEET.company_name).filter(
                finance.STK_BALANCE_SHEET.code == codeqianyuandianli,
                finance.STK_BALANCE_SHEET.pub_date >= '2010-01-01',
                finance.STK_BALANCE_SHEET.report_type == 0).limit(50))