杰瑞科技汇

tushare python 3.7

Of course! Here is a comprehensive guide on how to use the Tushare library with Python 3.7, covering installation, basic setup, and practical examples.

tushare python 3.7-图1
(图片来源网络,侵删)

What is Tushare?

Tushare is a popular and powerful Python library for obtaining financial data from Chinese markets. It provides access to a vast amount of data, including:

  • Stock Data: Historical daily/minute quotes, real-time quotes, fundamental data, financial statements, etc.
  • Index Data: CSI 300, SSE 50, and other major Chinese indices.
  • Fund Data: Mutual funds, ETFs, and bond information.
  • Macro Data: Economic indicators like CPI, PPI, GDP, etc.
  • News and Conceptual Sectors: News headlines and stock categorizations by theme.

Step 1: Installation

First, you need to install the Tushare library. Open your terminal or command prompt and run the following command:

pip install tushare

This will install the latest version of Tushare, which is fully compatible with Python 3.7.


Step 2: Getting a Tushare Token

To use Tushare's API, you need a token. This token is used to identify you and track your usage (as most data sources have limits).

tushare python 3.7-图2
(图片来源网络,侵删)
  1. Sign Up: Go to the Tushare Pro website and register for an account.
  2. Get Token: After logging in, navigate to the "个人主页" (Personal Homepage) section. You will find your unique token there.

Note: The free token has a certain number of points per day, which replenishes every day. For heavy usage, you may need to purchase a paid plan.


Step 3: Initial Setup and Authentication

In your Python script, you need to initialize the Tushare library with your token.

import tushare as ts
# Set your Tushare token
# Replace 'YOUR_TOKEN_HERE' with the actual token you got from the website
ts.set_token('YOUR_TOKEN_HERE')
# Initialize the API interface
# The 'pro' version is recommended as it's more stable and has more data
pro = ts.pro_api()
print("Tushare API initialized successfully!")

Step 4: Practical Examples

Now that you're set up, let's fetch some common data.

Example 1: Get Daily Stock Data (e.g., Tencent - 00700.HK)

Tushare can get data for Hong Kong stocks as well. Tencent's stock code in HK is 00700.

tushare python 3.7-图3
(图片来源网络,侵删)
import tushare as ts
import pandas as pd
# Set token and initialize pro API
ts.set_token('YOUR_TOKEN_HERE')
pro = ts.pro_api()
# Define the stock code and date range
stock_code = '00700.HK'
start_date = '20250101'
end_date = '20251231'
try:
    # Get daily stock data
    df_daily = pro.daily(ts_code=stock_code, start_date=start_date, end_date=end_date)
    # Display the first 5 rows
    print(f"Daily data for {stock_code}:")
    print(df_daily.head())
    # Save to a CSV file
    df_daily.to_csv(f'tencent_daily_{start_date}_{end_date}.csv', index=False)
    print(f"\nData saved to tencent_daily_{start_date}_{end_date}.csv")
except Exception as e:
    print(f"An error occurred: {e}")

Example 2: Get a List of All A-Shares in Shanghai Stock Exchange

This is a very common task to get a universe of stocks to analyze.

import tushare as ts
ts.set_token('YOUR_TOKEN_HERE')
pro = ts.pro_api()
try:
    # Get stock list for Shanghai Stock Exchange (SSE)
    # market='SSE' for Shanghai, 'SZSE' for Shenzhen
    df_stock_list = pro.stock_basic(exchange='SSE', list_status='L')
    print(f"Found {len(df_stock_list)} stocks in SSE.")
    print("First 5 stocks:")
    print(df_stock_list[['ts_code', 'symbol', 'name', 'area', 'industry']].head())
except Exception as e:
    print(f"An error occurred: {e}")

Example 3: Get Historical Daily Data for Multiple Stocks

You can fetch data for a list of stock codes at once, which is much more efficient than looping.

import tushare as ts
ts.set_token('YOUR_TOKEN_HERE')
pro = ts.pro_api()
# Define a list of stock codes you are interested in
stock_list = ['000001.SZ', '000002.SZ', '600000.SH'] # Ping An Bank, Vanke, Pudong Development Bank
start_date = '20250101'
end_date = '20251231'
try:
    # Get daily data for multiple stocks
    # The API call is similar, but you don't specify ts_code
    df_multi = pro.daily(ts_code=','.join(stock_list), start_date=start_date, end_date=end_date)
    print(f"Daily data for multiple stocks from {start_date} to {end_date}:")
    print(df_multi.head())
    # You can use pandas to pivot the data for easier analysis
    # For example, to get the close price for each stock in columns
    df_pivot = df_multi.pivot(index='trade_date', columns='ts_code', values='close')
    print("\nPivoted data (Close Prices):")
    print(df_pivot.head())
except Exception as e:
    print(f"An error occurred: {e}")

Example 4: Get Real-time Quotes

For real-time data, you use the hq (high-frequency quote) interface.

import tushare as ts
ts.set_token('YOUR_TOKEN_HERE')
pro = ts.pro_api()
# A list of stock codes for real-time quotes
codes = ['000001.SZ', '600519.SH'] # Ping An Bank, Moutai (Kweichow Moutai)
try:
    # Get real-time quotes
    df_realtime = pro.hq(ts_code=','.join(codes))
    print("Real-time quotes:")
    print(df_realtime)
except Exception as e:
    print(f"An error occurred: {e}")

Best Practices and Tips for Python 3.7

  1. Error Handling: Always wrap your API calls in a try...except block. Network issues, invalid stock codes, or exceeding API limits can cause errors.

  2. Data Rate Limits: Be mindful of the free API limits. If you need to make many requests in a short time, add a small delay (time.sleep(0.5)) between calls to avoid being temporarily blocked.

  3. Using Pandas: Tushare returns data as a Pandas DataFrame, which is the standard for data analysis in Python. Learn to use Pandas effectively for filtering, grouping, and manipulating your data.

  4. Caching Data: For frequently accessed historical data, consider saving it to a local CSV or database file. This saves API points and speeds up your scripts on subsequent runs.

  5. Check the Official Documentation: The Tushare API is extensive. The best resource for all available functions and parameters is the official Tushare Pro API Documentation. You can find all the function names (e.g., daily, weekly, moneyflow, index_member) and their required/optional parameters there.

Troubleshooting Common Issues

  • tushare.error.TushareException: API接口不存在 (API interface does not exist):

    • Cause: You might be using an old function name or an incorrect parameter.
    • Solution: Double-check the function name and parameters in the official Tushare documentation.
  • tushare.error.TushareException: 请求频率超限 (Request frequency exceeded):

    • Cause: You have made too many API calls in a short period.
    • Solution: Add a time.sleep() between your requests or wait for the limit to reset.
  • tushare.error.TushareException: Invalid token (Invalid token):

    • Cause: Your token is incorrect, expired, or you've run out of daily points.
    • Solution: Check your token on the Tushare website. If it's a free token, wait for the points to reset at midnight.

This guide should give you a solid foundation for using Tushare with Python 3.7. Happy coding

分享:
扫描分享到社交APP
上一篇
下一篇