Python tushare.get_today_all() Examples

The following are 12 code examples of tushare.get_today_all(). 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: DyStockDataGateway.py    From DevilYuan with MIT License 6 votes vote down vote up
def _getStockCodesFromTuShare(self):
        self._info.print("开始从TuShare获取股票代码表...")

        try:
            df = ts.get_today_all() # it's slow because TuShare will get one page by one page
        except Exception as ex:
            self._info.print("从TuShare获取股票代码表异常: {}".format(ex), DyLogData.error)
            return None

        if df is None or df.empty:
            self._info.print("从TuShare获取股票代码表为空", DyLogData.error)
            return None

        codes = {}
        data = df[['code', 'name']].values.tolist()
        for code, name in data:
            if code[0] == '6':
                codes[code + '.SH'] = name
            else:
                codes[code + '.SZ'] = name

        self._info.print("从TuShare获取股票代码表成功")
        return codes 
Example #2
Source File: data_download.py    From stock with Apache License 2.0 6 votes vote down vote up
def download_realtime_stock_price():
    """
    # 下载股票的实时行情
    :return:
    """
    try:
        engine = db.get_w_engine()

        df_price = ts.get_today_all()

        stock_time = GetNowTime()
        if stock_time[11:] > "15:00:00":
            stock_time = stock_time[:11] + "15:00:00"
        df_price['date'] = stock_time

        # df_price.to_sql(STOCK_REALTIME_TABLE, engine, if_exists='append', index=False)
        to_sql(STOCK_REALTIME_TABLE, engine, df_price, type='replace')

    except Exception as e:
        print(e)

#######################
##  private methods  ##
####################### 
Example #3
Source File: DyStockDataGateway.py    From DevilYuan with MIT License 6 votes vote down vote up
def _getStockCodesFromTuShare(self):
        try:
            df = ts.get_today_all() # it's slow because TuShare will get one page by one page
        except Exception as ex:
            return None

        if df is None or df.empty:
            return None

        codes = {}
        data = df[['code', 'name']].values.tolist()
        for code, name in data:
            if code[0] == '6':
                codes[code + '.SH'] = name
            else:
                codes[code + '.SZ'] = name

        return codes 
Example #4
Source File: QATushare.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def QA_fetch_get_stock_realtime():
    data = ts.get_today_all()
    data_json = QA_util_to_json_from_pandas(data)
    return data_json 
Example #5
Source File: 18h_daily_job.py    From stock with Apache License 2.0 5 votes vote down vote up
def stat_today_all(tmp_datetime):
    datetime_str = (tmp_datetime).strftime("%Y-%m-%d")
    datetime_int = (tmp_datetime).strftime("%Y%m%d")
    print("datetime_str:", datetime_str)
    print("datetime_int:", datetime_int)
    data = ts.get_today_all()
    # 处理重复数据,保存最新一条数据。最后一步处理,否则concat有问题。
    if not data is None and len(data) > 0:
        # 插入数据库。
        # del data["reason"]
        data["date"] = datetime_int  # 修改时间成为int类型。
        data = data.drop_duplicates(subset="code", keep="last")
        data.head(n=1)
        common.insert_db(data, "ts_today_all", False, "`date`,`code`")
    else:
        print("no data .")

    time.sleep(5)  # 停止5秒

    data = ts.get_index()
    # 处理重复数据,保存最新一条数据。最后一步处理,否则concat有问题。
    if not data is None and len(data) > 0:
        # 插入数据库。
        # del data["reason"]
        data["date"] = datetime_int  # 修改时间成为int类型。
        data = data.drop_duplicates(subset="code", keep="last")
        data.head(n=1)
        common.insert_db(data, "ts_index_all", False, "`date`,`code`")
    else:
        print("no data .")

    print(datetime_str)


# main函数入口 
Example #6
Source File: calcu_3year_average_pe.py    From chinese-stock-Financial-Index with Apache License 2.0 5 votes vote down vote up
def filter_by_roe(min):  # 筛选出最近5年ROE都高于min的公司
    path = os.path.join(current_folder, '3年平均利润及其他财务指标%s.csv' % today)
    if not os.path.exists(path):  # 没有就生成3年平均利润列表
        calcu_all_stocks_3year_roe_and_average_profit(
            calcu_average_profit_end_year)

    gplb = pd.read_csv(path, index_col=0, encoding='utf-8')
    gplb = gplb[gplb['当年roe'] > min]
    gplb = gplb[gplb['上1年roe'] > min]
    gplb = gplb[gplb['上2年roe'] > min]
    gplb = gplb[gplb['上3年roe'] > min]
    gplb = gplb[gplb['上4年roe'] > min]

    # 获取当前股票价格
    price_path = os.path.join(current_folder, today + '股票价格.csv')
    if not os.path.exists(price_path):
        ts.get_today_all().set_index('code').to_csv(
            price_path, encoding="utf-8")

    current_price = pd.read_csv(price_path, encoding="utf-8", index_col=0)
    current_price = current_price[['trade']]
    current_price.columns = ['价格']
    gplb = gplb[[
        '名字', '行业', '地区', '流通股本', '总股本', '总资产(万)', '流动资产', '固定资产', '每股净资',
        '市净率', '上市日期', '平均利润', '当年roe', '上1年roe', '上2年roe', '上3年roe', '上4年roe'
    ]]

    data = pd.merge(gplb, current_price, left_index=True, right_index=True)
    # 因为这里的平均利润单位是万元,而总股本单位是亿,价格单位是元
    data['平均市盈率'] = data['总股本'] * data['价格'] * 10000 / data['平均利润']
    data['平均市盈率'] = data['平均市盈率'].round(1)
    data['市净率'] = data['市净率'].round(1)

    high_roe_file = os.path.join(current_folder,
                                 today + f'-最近5年ROE都高于{min}%的公司.xlsx')
    data.to_excel(high_roe_file, encoding='utf-8') 
Example #7
Source File: basic.py    From anack with GNU General Public License v3.0 5 votes vote down vote up
def k_today():

    return ts.get_today_all() 
Example #8
Source File: online_data.py    From stock with Apache License 2.0 5 votes vote down vote up
def getLiveChinaStockPrice(stockCode):
    
    try:
        exchange = "sh" if (int(stockCode) // 100000 == 6) else "sz"
        dataUrl = "http://hq.sinajs.cn/list=" + exchange + stockCode
        stdout = urllib2.urlopen(dataUrl)
        stdoutInfo = stdout.read().decode('gb2312').encode('utf-8')
        
        # 正则表达式说明
        # 搜索 “ ”双引号内的字符串,包含换行符,将匹配的字符串分为三组:用()表示
        # group(2):取第二组数据
        tempData = re.search('''(")(.+)(")''', stdoutInfo).group(2)
        stockInfo = tempData.split(",")
        
        #bb[0]:股票名  bb[1]:今日开盘价    bb[2]:昨日收盘价    bb[3]:当前价格   bb[4]:今日最高价    bb[5]:今日最低价
        #bb[6]:买一报价 bb[7]:卖一报价     bb[8]:成交股票数/100 bb[9]:成交金额/w bb[10]:买一申请股数 bb[11]:买一报价
        #bb[12]:买二股数 bb[13]:买二报价   bb[14]:买三股数      bb[15]:买三报价  bb[16]:买四申请股数 bb[17]:买四报价
        #bb[18]:买五股数 bb[19]:买五报价   bb[20]:卖一股数      bb[21]:卖一报价  bb[22]:卖二申请股数 bb[23]:卖二报价
        #bb[24]:卖三股数 bb[25]:卖三报价   bb[26]:卖四股数      bb[27]:卖四报价  bb[28]:卖五股数     bb[29]:卖五报价
        #bb[30]:日期     bb[31]:时间     bb[8]:不知道
        
        return st.Stock(stockInfo)
        
    except Exception as e:
        print(">>>>>> Exception: " + str(e))
    finally:
        None    

# 获取A股所有股票的实时股价
# 通过 ts.get_today_all 获取 
Example #9
Source File: online_data.py    From stock with Apache License 2.0 5 votes vote down vote up
def get_real_price_dataframe():
    df = ts.get_today_all()
    return df 
Example #10
Source File: main.py    From stock with Apache License 2.0 5 votes vote down vote up
def get_stock_price(code, include_realtime_price):
    """
    获取个股股价
    :param code: 股票代码
    :param include_realtime_price: 是否含实时股价
    :return:
    """

    # 获取历史股价
    df = ts.get_hist_data(code)
    df = df[['close']]
    df['date'] = df.index

    if include_realtime_price:
        df_today = ts.get_today_all()
        df_code = df_today[df_today['code']==code]
        df_code = df_code[['trade']]
        df_code['date'] = GetNowDate()
        df_code.rename(columns={'trade': 'close'}, inplace=True)
        df = pd.concat([df, df_code], ignore_index=True)

    df.sort(columns='date', inplace=True)
    df = df.drop_duplicates(['date'])
    df.index = range(len(df))
    print '\n'
    # print df.head()
    print df.tail()
    return df 
Example #11
Source File: stock_price.py    From HeatMap_for_TuShare with MIT License 5 votes vote down vote up
def plot_days():
    if request.method == 'GET' :
        today = ts.get_today_all()
        code_info = ts.get_industry_classified()

        today['code'] = today['code'].astype(unicode)
        one_day = gd.get_data_real_time(code_info, today)
        body = heatmap.get_heatmap('Today', one_day)
        return render_template('heatmap.html', body=body) 
Example #12
Source File: calcu_3year_average_pe.py    From chinese-stock-Financial-Index with Apache License 2.0 4 votes vote down vote up
def filter_stock_by_average_pe(min, max):
    path = os.path.join(current_folder, '3年平均利润及其他财务指标%s.csv' % today)
    if not os.path.exists(path):  # 没有就生成3年平均利润列表
        calcu_all_stocks_3year_roe_and_average_profit(
            calcu_average_profit_end_year)

    gplb = pd.read_csv(path, index_col=0, encoding='utf-8')

    # 获取当前股票价格
    price_path = os.path.join(current_folder, today + '股票价格.csv')
    if not os.path.exists(price_path):
        ts.get_today_all().set_index('code').to_csv(
            price_path, encoding="utf-8")

    current_price = pd.read_csv(price_path, encoding="utf-8", index_col=0)
    current_price = current_price[['trade']]
    current_price.columns = ['价格']
    gplb = gplb[[
        '名字', '行业', '地区', '流通股本', '总股本', '总资产(万)', '流动资产', '固定资产', '每股净资',
        '市净率', '上市日期', '平均利润'
    ]]

    data = pd.merge(gplb, current_price, left_index=True, right_index=True)
    # 因为这里的平均利润单位是万元,而总股本单位是亿,价格单位是元
    data['平均市盈率'] = data['总股本'] * data['价格'] * 10000 / data['平均利润']
    print('\n%s:' % today)
    print()
    print('%d个公司' % data.shape[0])
    print('3年市盈率中位数%.1f' % round(data['平均市盈率'].median(), 1))
    print('市净率中位数%.1f' % round(data['市净率'].median(), 1))
    data = data[data['平均市盈率'] < max]
    data = data[data['平均市盈率'] > min]
    data['平均市盈率'] = data['平均市盈率'].round(1)
    data['平均利润'] = data['平均利润'].round()
    data['市净率'] = data['市净率'].round(1)
    data['固定资产'] = data['固定资产'].round()
    data['流动资产'] = data['流动资产'].round()
    data['总股本'] = data['总股本'].round()
    data['流通股本'] = data['流通股本'].round()
    average_pe_file = os.path.join(
        current_folder, today + '-3年平均市盈率在%s和%s之间的公司.xlsx' % (min, max))
    data.to_excel(average_pe_file, encoding='utf-8')