Python tushare.get_k_data() Examples

The following are 21 code examples of tushare.get_k_data(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tushare , or try the search function .
Example #1
Source File: Fetch_Data_Stock_CHN_Daily.py    From StockRecommendSystem with MIT License 6 votes vote down vote up
def getSingleStockByTime(symbol, from_date, till_date):
    start = from_date.split('-')
    start_y, start_m, start_d = start[0], start[1], start[2] # starting date

    end = till_date.split('-')
    end_y, end_m, end_d = end[0], end[1], end[2] # until now
    
    repeat_times = 1
    message = ""
    df = pd.DataFrame()

    for _ in range(repeat_times): 
        try:
            data = ts.get_k_data(symbol)#, from_date, till_date)
            data.sort_index(ascending=True, inplace=True)
            return data, ""
        except Exception as e:
            message = symbol + " fetch exception: " + str(e)
            continue   
    return df, message 
Example #2
Source File: tushare_saver.py    From OnePy with MIT License 6 votes vote down vote up
def _load_from_api(self, code, start, end, ktype, autype, index):
        d = dict(code=code, ktype=ktype)

        if start:
            d["start"] = start

        if end:
            d["end"] = end

        df = ts.get_k_data(**d)
        df.reset_index(drop=True, inplace=True)
        j = df.to_json()
        data = json.loads(j)

        df_len = len(df)

        return data, df_len 
Example #3
Source File: trendline.py    From tushare with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def jdrs(df, n=20):
    """
    阶段弱势指标	jdrs(20)
    JDRS=(统计N天中个股收盘价<开盘价,且指数收盘价>开盘价的天数)/(统计N天中指数收盘价>开盘价的天数)
    """
    ind = ts.get_k_data("sh000001", start=df.date.iloc[0], end=df.date.iloc[-1])
    sd = df.copy()
    sd.set_index('date', inplace=True)
    ind.set_index('date', inplace=True)
    _jdrs = pd.DataFrame(index=df.date)
    q = ind.close - ind.open
    _jdrs['p'] = sd.close - sd.open
    _jdrs['q'] = q
    _jdrs['m'] = _jdrs.apply(lambda x: 1 if (x.p < 0 and x.q > 0) else np.nan, axis=1)
    q[q < 0] = np.nan
    _jdrs['t'] = q
    _jdrs['jdrs'] = _jdrs.m.rolling(n).count() / _jdrs.t.rolling(n).count()
    _jdrs.drop(columns=['p', 'q', 'm', 't'], inplace=True)
    _jdrs.reset_index(inplace=True)
    return _jdrs 
Example #4
Source File: trendline.py    From tushare with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def jdqs(df, n=20):
    """
    阶段强势指标	jdqs(20)
    JDQS=(统计N天中个股收盘价>开盘价,且指数收盘价<开盘价的天数)/(统计N天中指数收盘价<开盘价的天数)
    """
    ind = ts.get_k_data("sh000001", start=df.date.iloc[0], end=df.date.iloc[-1])
    sd = df.copy()
    sd.set_index('date', inplace=True)   # 可能出现停盘等情况,所以将date设为index
    ind.set_index('date', inplace=True)
    _jdrs = pd.DataFrame(index=df.date)
    q = ind.close - ind.open
    _jdrs['p'] = sd.close - sd.open
    _jdrs['q'] = q
    _jdrs['m'] = _jdrs.apply(lambda x: 1 if (x.p > 0 and x.q < 0) else np.nan, axis=1)
    q[q > 0] = np.nan
    _jdrs['t'] = q
    _jdrs['jdrs'] = _jdrs.m.rolling(n).count() / _jdrs.t.rolling(n).count()
    _jdrs.drop(columns=['p', 'q', 'm', 't'], inplace=True)
    _jdrs.reset_index(inplace=True)
    return _jdrs 
Example #5
Source File: trendline.py    From tushare with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dptb(df, n=7):
    """
    大盘同步指标	dptb(7)
    DPTB=(统计N天中个股收盘价>开盘价,且指数收盘价>开盘价的天数或者个股收盘价<开盘价,且指数收盘价<开盘价)/N
    """
    ind = ts.get_k_data("sh000001", start=df.date.iloc[0], end=df.date.iloc[-1])
    sd = df.copy()
    sd.set_index('date', inplace=True)  # 可能出现停盘等情况,所以将date设为index
    ind.set_index('date', inplace=True)
    _dptb = pd.DataFrame(index=df.date)
    q = ind.close - ind.open
    _dptb['p'] = sd.close - sd.open
    _dptb['q'] = q
    _dptb['m'] = _dptb.apply(lambda x: 1 if (x.p > 0 and x.q > 0) or (x.p < 0 and x.q < 0) else np.nan, axis=1)
    _dptb['jdrs'] = _dptb.m.rolling(n).count() / n
    _dptb.drop(columns=['p', 'q', 'm'], inplace=True)
    _dptb.reset_index(inplace=True)
    return _dptb 
Example #6
Source File: Fetch_Data_Stock_CHN_Monthly.py    From StockRecommendSystem with MIT License 6 votes vote down vote up
def getSingleStockByTime(symbol, from_date, till_date):
    start = from_date.split('-')
    start_y, start_m, start_d = start[0], start[1], start[2] # starting date

    end = till_date.split('-')
    end_y, end_m, end_d = end[0], end[1], end[2] # until now
    
    repeat_times = 1
    message = ""
    df = pd.DataFrame()

    for _ in range(repeat_times): 
        try:
            data = ts.get_k_data(symbol, ktype='M')
            data.sort_index(ascending=True, inplace=True)
            return data, ""
        except Exception as e:
            message = symbol + " fetch exception: " + str(e)
            continue   
    return df, message 
Example #7
Source File: Filter_Stock_Cashflow_CHN.py    From StockRecommendSystem with MIT License 5 votes vote down vote up
def get_single_stock_data_daily(root_path, symbol):
    '''
    All data is from quandl wiki dataset
    Feature set: [Open  High    Low  Close    Volume  Ex-Dividend  Split Ratio Adj. Open  Adj. High  Adj. Low
    Adj. Close  Adj. Volume]
    '''
    #df, lastUpdateTime = queryStock(root_path, "DB_STOCK", "SHEET_CHN", "_DAILY", symbol, "daily_update")
    try:
        df = ts.get_k_data(symbol)
        df.set_index('date', inplace=True)
        df.sort_index(ascending=True, inplace=True)
    except:
        print("stock delisted", symbol)
        return pd.DataFrame()

    if df.empty:
        print("stock delisted", symbol)
        return pd.DataFrame()

    out_path = root_path + "/Data/CSV/symbols/"

    if os.path.exists(out_path) == False:
        os.mkdir(out_path)

    out_file = out_path + symbol + ".csv"
    df.to_csv(out_file)

    return df 
Example #8
Source File: data_source.py    From rqalpha-mod-tushare with Apache License 2.0 5 votes vote down vote up
def get_tushare_k_data(instrument, start_dt, end_dt):
        order_book_id = instrument.order_book_id
        code = order_book_id.split(".")[0]

        if instrument.type == 'CS':
            index = False
        elif instrument.type == 'INDX':
            index = True
        else:
            return None

        return ts.get_k_data(code, index=index, start=start_dt.strftime('%Y-%m-%d'), end=end_dt.strftime('%Y-%m-%d')) 
Example #9
Source File: trendline.py    From tushare with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tapi(df, n=6):
    """ # TODO: 由于get_k_data返回数据中没有amount,可以用get_h_data中amount,算法是正确的
    加权指数成交值	tapi(6)
    TAPI=每日成交总值/当日加权指数=a/PI;A表示每日的成交金额,PI表示当天的股价指数即指收盘价
    """
    _tapi = pd.DataFrame()
    # _tapi['date'] = df.date
    _tapi['tapi'] = df.amount / df.close
    _tapi['matapi'] = _ma(_tapi.tapi, n)
    return _tapi 
Example #10
Source File: Fetch_Data_Stock_CHN_Weekly.py    From StockRecommendSystem with MIT License 5 votes vote down vote up
def getSingleStock(symbol):
    repeat_times = 1
    message = ""
    df = pd.DataFrame()

    for _ in range(repeat_times): 
        try:
            data = ts.get_k_data(symbol, ktype='W')
            data.sort_index(ascending=True, inplace=True)
            return data, ""
        except Exception as e:
            message = symbol + " fetch exception: " + str(e)
            continue   
    return df, message 
Example #11
Source File: Fetch_Data_Stock_CHN_Monthly.py    From StockRecommendSystem with MIT License 5 votes vote down vote up
def getSingleStock(symbol):
    repeat_times = 1
    message = ""
    df = pd.DataFrame()

    for _ in range(repeat_times): 
        try:
            data = ts.get_k_data(symbol, ktype='M')
            data.sort_index(ascending=True, inplace=True)
            return data, ""
        except Exception as e:
            message = symbol + " fetch exception: " + str(e)
            continue   
    return df, message 
Example #12
Source File: indictor_test.py    From tushare with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_plot_all(self):
        data = ts.get_k_data("601398", start="2018-01-01", end="2018-05-27")

        data = data.sort_values(by=["date"], ascending=True)

        idx.plot_all(data, is_show=True, output=None) 
Example #13
Source File: data_source.py    From puppet with MIT License 5 votes vote down vote up
def get_tushare_k_data(instrument, start_dt, end_dt):
        order_book_id = instrument.order_book_id
        code = order_book_id.split(".")[0]

        if instrument.type == 'CS':
            index = False
        elif instrument.type == 'INDX':
            index = True
        else:
            return None

        return ts.get_k_data(code, index=index, start=start_dt.strftime('%Y-%m-%d'), end=end_dt.strftime('%Y-%m-%d')) 
Example #14
Source File: k_data_to_sql.py    From anack with GNU General Public License v3.0 5 votes vote down vote up
def k_data(index,mode='D'):

    if mode == 'D':
        df_to_mysql('anack_d_k_data',ts.get_k_data(index))
    elif mode == 'M':
        df_to_mysql('anack_m_k_data',ts.get_k_data(index,ktype='M'))
        
#------------------------------------------------------------------------------
#create_k_table()
#k_data('600660') 
#k_data('600660','M') 
Example #15
Source File: basic.py    From anack with GNU General Public License v3.0 5 votes vote down vote up
def k_day(index,mode='D'):

    if mode == 'D':
        return ts.get_k_data(index)
    elif mode == 'M':
        return ts.get_k_data(index,ktype='M') 
Example #16
Source File: server.py    From mt4plus with GNU General Public License v2.0 5 votes vote down vote up
def get(self):
        symbol = self.get_argument("symbol")#股票代码
        period = self.get_argument("period")#时间周期,单位-分钟
        period_allow_list = ["5","15","30","60","1440","M","W"]
        if period not in period_allow_list:
            return 
       
        data = None
        if period =="1440":
            data = ts.get_hist_data(symbol)
        else:
            data = ts.get_k_data(symbol,ktype=period)
        print "=========",symbol,":",period
        resultlist = []
        lens = len(data)
        for unit in data.iterrows():
            obj  = {}
            dates = None
            if period =="1440":
                dates = unit[1].name
            else:
                dates = unit[1]['date']
            print "len",len(dates)
#             长度等于10的是%Y-%m-%d格式,16的是%Y-%m-%d %H:%M 格式
            dataformate = "%Y-%m-%d %H:%M"
            date_len = len(dates)
            if date_len == 10 :
                dataformate = "%Y-%m-%d"
            d=datetime.datetime.strptime(dates,dataformate)
            obj["date"]=int(time.mktime(d.timetuple()))
            obj["open"]=unit[1]['open']
            obj["close"]=unit[1]['close']
            obj["high"]=unit[1]['high']
            obj["low"]=unit[1]['low']
            obj["volume"]=unit[1]['volume']
            resultlist.append(obj)
        
        resultlist.sort(key=lambda obj:obj.get('date'), reverse=False) 
        
        s = json.dumps(resultlist)
        self.write(s) 
Example #17
Source File: data_download.py    From stock with Apache License 2.0 5 votes vote down vote up
def download_kline_by_date_range(code, date_start, date_end):
    """
    根据日期范围下载股票行情
    :param code:股票代码,即6位数字代码,或者指数代码(sh=上证指数 sz=深圳成指 hs300=沪深300指数 sz50=上证50 zxb=中小板 cyb=创业板)
    :param date_start:
    :param date_end:
    :return:
    """
    try:
        if len(code)==6:
            df_qfq = ts.get_k_data(str(code), start=date_start, end=date_end, autype='qfq') # 前复权
            df_hfq = ts.get_k_data(str(code), start=date_start, end=date_end, autype='hfq')  # 后复权
        else:
            df_qfq = ts.get_k_data(str(code), start=date_start, end=date_end)
        if len(df_qfq)==0 or (len(code)==6 and len(df_hfq)==0):
            return pd.DataFrame()

        if len(code)==6:
            df_qfq['close_hfq'] = df_hfq['close']
        else:
            df_qfq['close_hfq'] = df_qfq['close']  # 指数后复权=前复权

        print(df_qfq.head())

        return df_qfq
    except Exception as e:
        print(str(e))
        return pd.DataFrame() 
Example #18
Source File: Fetch_Data_Stock_CHN_Daily.py    From StockRecommendSystem with MIT License 5 votes vote down vote up
def getSingleStock(symbol):
    repeat_times = 1
    message = ""
    df = pd.DataFrame()

    for _ in range(repeat_times): 
        try:
            data = ts.get_k_data(symbol)
            data.sort_index(ascending=True, inplace=True)
            return data, ""
        except Exception as e:
            message = symbol + " fetch exception: " + str(e)
            continue   
    return df, message 
Example #19
Source File: DyStockDataGateway.py    From DevilYuan with MIT License 5 votes vote down vote up
def _getFundDaysFromTuShare(self, code, startDate, endDate, fields, name=None):
        """
            从tushare获取基金(ETF)日线数据。
            # !!!TuShare没有提供换手率,复权因子和成交额,所以只能假设。
            # 策略针对ETF的,需要注意。
        """
        tuShareCode = code[:-3]

        try:
            # 以无复权方式从腾讯获取OHCLV,成交量是手(整数化过)
            # 此接口支持ETF日线数据
            df = ts.get_k_data(tuShareCode, startDate, endDate, autype=None).sort_index()
        except Exception as ex:
            self._info.print("从TuShare获取{}({})日线数据[{}, {}]失败: {}".format(code, name, startDate, endDate, ex), DyLogData.error)
            return None

        df['volume'] = df['volume']*100

        # !!!TuShare没有提供换手率,复权因子和成交额,所以只能假设。
        # 策略针对ETF的,需要注意。
        df['turnover'] = 0
        df['factor'] = 1
        df['amount'] = 0
        df.index.name = None

        # change to Wind's indicators
        df.rename(columns={'date': 'datetime', 'amount': 'amt', 'turnover': 'turn', 'factor': 'adjfactor'}, inplace=True)

        # 把日期的HH:MM:SS转成 00:00:00
        df['datetime'] = pd.to_datetime(df['datetime'], format='%Y-%m-%d')

        # select according @fields
        df = df[['datetime'] + fields]

        return df 
Example #20
Source File: DyStockDataGateway.py    From DevilYuan with MIT License 4 votes vote down vote up
def _getFundDaysFromTuShare(self, code, startDate, endDate, fields, name=None):
        """
            从tushare获取基金(ETF)日线数据。
            # !!!TuShare没有提供换手率,复权因子和成交额,所以只能假设。
            # 策略针对ETF的,需要注意。
        """
        tuShareCode = code[:-3]

        sleepTime = self.tuShareDaysSleepTimeConst + self.tuShareDaysSleepTime
        try:
            try:
                # 以无复权方式从腾讯获取OHCLV,成交量是手(整数化过)
                # 此接口支持ETF日线数据
                df = ts.get_k_data(tuShareCode, startDate, endDate, autype=None, pause=sleepTime)
                if df is None or df.empty: # If no data, TuShare return None
                    df = pd.DataFrame(columns=['date', 'open', 'high', 'close', 'low', 'volume'])
                else:
                    df = df.sort_index()
            except Exception as ex:
                self._info.print("从TuShare获取{}({})日线数据[{}, {}]失败: {}".format(code, name, startDate, endDate, ex), DyLogData.error)
                return None

            df['volume'] = df['volume']*100

            # !!!TuShare没有提供换手率,复权因子和成交额,所以只能假设。
            # 策略针对ETF的,需要注意。
            df['turnover'] = 0
            df['factor'] = 1
            df['amount'] = 0
            df.index.name = None

            # change to Wind's indicators
            df.rename(columns={'date': 'datetime', 'amount': 'amt', 'turnover': 'turn', 'factor': 'adjfactor'}, inplace=True)

            # 把日期的HH:MM:SS转成 00:00:00
            df['datetime'] = pd.to_datetime(df['datetime'], format='%Y-%m-%d')

            # select according @fields
            df = df[['datetime'] + fields]
        except Exception as ex:
            self._info.print("从TuShare获取{}({})日线数据[{}, {}]失败: {}".format(code, name, startDate, endDate, ex), DyLogData.error)
            return None

        return df 
Example #21
Source File: early_warning.py    From anack with GNU General Public License v3.0 4 votes vote down vote up
def init():
    '''
        根据target_id获取历史平均成交量、均线水平等参数,作为后续check的比对依据
        id:
        avg_price_week:周线
        avg_price_month:月线
        avg_price_year:年线
        volume_min:5日内平均每分钟成交量(用于计算量比)
    '''
    global avg_info
    global morning_open_time
    global morning_close_time
    global afternoon_open_time
    global afternoon_close_time
#    input_id = ['000651','600887','600066','600660']
    input_id = target_id
    
    avg_price_week = []    #周均线,5天
    avg_price_month = []   #月均线,22天
    avg_price_year = [] #年线,250天
    avg_volumn_min = []
    for id_name in input_id:
        a = ts.get_k_data(id_name)  #获取基础信息
        temp = a.iloc[-5:]['close']
        avg_price_week.append(temp.sum()/5)
        temp = a.iloc[-22:]['close']
        avg_price_month.append(temp.sum()/22)    
        if len(a) > 250:
            temp = a.iloc[-250:]['close']
            avg_price_year.append(temp.sum()/250)
        else:
            temp = a.iloc[:]['close']
            avg_price_year.append(temp.sum()/len(a))     
        a = a[-5:]  #计算过去5天内的平均成交量
        b = a.iloc[:]['volume']
        c = b.sum() / len(b) / 240
        avg_volumn_min.append(c)
        
    data = {'id':input_id,
            'avg_price_week':avg_price_week,
            'avg_price_month':avg_price_month,
            'avg_price_year':avg_price_year,
            'volume_min':avg_volumn_min
            }
    avg_info = pd.DataFrame(data)
    
    
    now = datetime.now()
    morning_open_time = datetime(now.year,now.month,now.day,9,30)
    morning_close_time = datetime(now.year,now.month,now.day,11,30)
    afternoon_open_time = datetime(now.year,now.month,now.day,13,00)
    afternoon_close_time = datetime(now.year,now.month,now.day,15,00)
#    return pd.DataFrame(data)