Baostock is a Python library designed to provide free historical data for the China stock market, sourced from Baostock.com. It allows users to retrieve various types of data, including daily K-line data, stock basic information, and transaction details, making it a valuable tool for quantitative analysis and research. The current version is 0.9.1, and releases typically occur to fix bugs or adapt to changes in the Baostock data service.
pip install baostockVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to log into the Baostock service, query historical daily K-line data for a specific stock ('sh.600000'), display the first few rows of the resulting DataFrame, and finally log out. Ensure `BAOSTOCK_USERNAME` and `BAOSTOCK_PASSWORD` environment variables are set or replace the placeholders with your actual Baostock credentials.
Verify username and password, check network connectivity, and refer to `lg.error_msg` for specific issues. Consider retries for transient network errors.
Validate the resulting DataFrame's size and content. Cross-reference with other data sources if data completeness is critical. Ensure the stock code and date range are valid.
Implement error handling with retries and exponential backoff. You might need to adjust network timeout settings if `requests` library allows it or handle `requests.exceptions.Timeout`.
Introduce delays (`time.sleep()`) between successive queries, especially when fetching data for multiple stocks or long historical periods. Optimize data fetching to minimize the number of API calls.
Double-check your Baostock account credentials. Ensure no leading/trailing spaces or typos. If using environment variables, verify they are correctly set.
Ensure `bs.login()` is called and returns a successful response (`lg.error_code == '0'`) before attempting any data retrieval operations.
Check your internet connection and firewall settings. Try again after some time. If persistent, this might indicate a problem with the Baostock service itself or a transient network issue between you and the server.
Verify the stock code is correct (e.g., 'sh.600000' or 'sz.000001'). Adjust the `start_date` and `end_date` to ensure data should exist. Check if the stock was active during the queried period. Ensure `rs.error_code` is '0' before processing `rs.next()`.