Baostock

0.9.1 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import baostock as bs
import pandas as pd
import os

# Baostock login credentials can be set as environment variables (recommended for production)
# For local testing, replace with actual username/password or remove os.environ.get if hardcoding (not recommended)
USERNAME = os.environ.get('BAOSTOCK_USERNAME', 'your_username')
PASSWORD = os.environ.get('BAOSTOCK_PASSWORD', 'your_password')

if not USERNAME or not PASSWORD or USERNAME == 'your_username':
    print("Warning: Please set BAOSTOCK_USERNAME and BAOSTOCK_PASSWORD environment variables or replace placeholders.")
    print("Attempting login with placeholder credentials, which will likely fail.")
    # Using placeholder for runnable example if env vars not set, but it will likely fail a real login
    USERNAME = "PLACEHOLDER_USER"
    PASSWORD = "PLACEHOLDER_PASS"

# Login to Baostock service
print("Attempting to log in to Baostock...")
lg = bs.login(USERNAME, PASSWORD)

if lg.error_code == '0':
    print(f"Login success! User ID: {lg.uid}")
else:
    print(f"Login failed! Code: {lg.error_code}, Msg: {lg.error_msg}")
    # For a real application, you might want to exit here: import sys; sys.exit(1)

# Only proceed if login was successful or if you want to test query failure
if lg.error_code == '0':
    # Query historical K-data for a stock (e.g., 'sh.600000' for Pudong Development Bank)
    # Fields: date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNCM,isST
    print("Querying historical K-data for sh.600000...")
    rs = bs.query_history_k_data_plus("sh.600000",
        "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNCM,isST",
        start_date='2023-01-01', end_date='2023-01-31',
        frequency="d", adjustflag="2") # frequency="d" means daily, adjustflag="2" means front-adjust

    data_list = []
    if rs.error_code == '0':
        while rs.next():
            data_list.append(rs.get_row_data())

    result = pd.DataFrame(data_list, columns=rs.fields)

    print("\nSample K-data for sh.600000:")
    print(result.head())

    # Logout
    bs.logout()
    print("\nLogout successful.")
else:
    print("Skipping data query due to login failure.")

view raw JSON →