{"id":7973,"library":"baostock","title":"Baostock","description":"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.","status":"active","version":"0.9.1","language":"en","source_language":"en","source_url":"https://github.com/baostock/baostock","tags":["finance","stock","market data","China","quantitative analysis"],"install":[{"cmd":"pip install baostock","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Used for making HTTP requests to the Baostock API.","package":"requests"},{"reason":"Required for data manipulation and returning query results as DataFrames.","package":"pandas"},{"reason":"Fundamental package for numerical operations, often used by pandas.","package":"numpy"},{"reason":"Used for parsing HTML content, likely for session management or specific data extraction.","package":"beautifulsoup4"}],"imports":[{"note":"The library is designed for a single import alias 'bs' for all core functions.","wrong":"from baostock import login","symbol":"baostock","correct":"import baostock as bs"}],"quickstart":{"code":"import baostock as bs\nimport pandas as pd\nimport os\n\n# Baostock login credentials can be set as environment variables (recommended for production)\n# For local testing, replace with actual username/password or remove os.environ.get if hardcoding (not recommended)\nUSERNAME = os.environ.get('BAOSTOCK_USERNAME', 'your_username')\nPASSWORD = os.environ.get('BAOSTOCK_PASSWORD', 'your_password')\n\nif not USERNAME or not PASSWORD or USERNAME == 'your_username':\n    print(\"Warning: Please set BAOSTOCK_USERNAME and BAOSTOCK_PASSWORD environment variables or replace placeholders.\")\n    print(\"Attempting login with placeholder credentials, which will likely fail.\")\n    # Using placeholder for runnable example if env vars not set, but it will likely fail a real login\n    USERNAME = \"PLACEHOLDER_USER\"\n    PASSWORD = \"PLACEHOLDER_PASS\"\n\n# Login to Baostock service\nprint(\"Attempting to log in to Baostock...\")\nlg = bs.login(USERNAME, PASSWORD)\n\nif lg.error_code == '0':\n    print(f\"Login success! User ID: {lg.uid}\")\nelse:\n    print(f\"Login failed! Code: {lg.error_code}, Msg: {lg.error_msg}\")\n    # For a real application, you might want to exit here: import sys; sys.exit(1)\n\n# Only proceed if login was successful or if you want to test query failure\nif lg.error_code == '0':\n    # Query historical K-data for a stock (e.g., 'sh.600000' for Pudong Development Bank)\n    # Fields: date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNCM,isST\n    print(\"Querying historical K-data for sh.600000...\")\n    rs = bs.query_history_k_data_plus(\"sh.600000\",\n        \"date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNCM,isST\",\n        start_date='2023-01-01', end_date='2023-01-31',\n        frequency=\"d\", adjustflag=\"2\") # frequency=\"d\" means daily, adjustflag=\"2\" means front-adjust\n\n    data_list = []\n    if rs.error_code == '0':\n        while rs.next():\n            data_list.append(rs.get_row_data())\n\n    result = pd.DataFrame(data_list, columns=rs.fields)\n\n    print(\"\\nSample K-data for sh.600000:\")\n    print(result.head())\n\n    # Logout\n    bs.logout()\n    print(\"\\nLogout successful.\")\nelse:\n    print(\"Skipping data query due to login failure.\")","lang":"python","description":"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."},"warnings":[{"fix":"Verify username and password, check network connectivity, and refer to `lg.error_msg` for specific issues. Consider retries for transient network errors.","message":"Login failures are common due to incorrect credentials, network issues, or Baostock service instability. Always check the `error_code` and `error_msg` returned by `bs.login()`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"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.","message":"Data retrieved for certain tickers or time ranges might be incomplete or empty, especially for delisted stocks or periods far in the past/future. The `query_history_k_data_plus` method does not always raise an error for empty results.","severity":"gotcha","affected_versions":"All versions"},{"fix":"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`.","message":"The Baostock service might occasionally be slow or unresponsive, leading to connection timeouts or delays. The library's underlying `requests` calls might hang or fail.","severity":"gotcha","affected_versions":"All versions"},{"fix":"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.","message":"Repeated, rapid requests can lead to IP-based rate limiting or temporary bans from the Baostock server, causing requests to fail with generic errors or connection issues.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Double-check your Baostock account credentials. Ensure no leading/trailing spaces or typos. If using environment variables, verify they are correctly set.","cause":"Incorrect username or password provided during `bs.login()`.","error":"Login failed! Code: 10001, Msg: User name or password error!"},{"fix":"Ensure `bs.login()` is called and returns a successful response (`lg.error_code == '0'`) before attempting any data retrieval operations.","cause":"An attempt was made to query data (e.g., `bs.query_history_k_data_plus()`) before successfully logging into the Baostock service with `bs.login()`.","error":"_bs_client is not login!"},{"fix":"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.","cause":"Network issues, firewall blocking, or the Baostock server prematurely closing the connection. This can also happen if the server is under heavy load or temporarily down.","error":"requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))"},{"fix":"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()`.","cause":"No data was returned for the specified stock code, date range, or query parameters. This often happens for delisted stocks, incorrect stock codes, or periods without available data.","error":"DataFrame is empty after query, e.g., print(result.empty) -> True"}]}