在 Jupyter Notebook 环境下,使用 Python 3.12.7 配合 AKShare 库可以高效获取金融数据。首先确保环境已安装最新版 AKShare。
安装与验证
在终端或 Notebook 单元格中执行以下命令:
!pip install akshare --upgrade -i https://pypi.tuna.tsinghua.edu.cn/simple
安装完成后,导入库并检查版本,确认无报错:
import akshare as ak
print("AKShare 版本:", ak.__version__)
基础数据获取
以贵州茅台(600519)为例,直接调用接口获取日线数据。注意日期格式需为 YYYYMMDD,且代码块需处理可能的网络异常。
try:
import akshare as ak
print("\n尝试使用 AKShare 获取 A 股数据示例:")
a_stock = ak.stock_zh_a_hist(
symbol="600519",
period="daily",
start_date="20250101",
end_date="20250507"
)
print(a_stock.head())
except ImportError:
print("\n提示:安装 AKShare 可获得中国证券市场数据 -> pip install akshare")
except Exception as e:
print(f"AKShare 获取失败:{str(e)}")
运行后应能看到包含开盘、收盘等字段的 DataFrame。若遇到网络波动,建议增加重试机制。
封装稳健的数据获取函数
实际开发中,我们通常需要更健壮的处理逻辑,包括自动重试、列名标准化及复权处理。下面是一个生产级封装示例:
import akshare as ak
import pandas as pd
# 设置显示参数,避免输出被截断
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
def ():
_ ():
:
df = ak.stock_zh_a_hist(
symbol=symbol,
period=,
start_date=start_date,
end_date=end_date,
adjust=
)
df[] = pd.to_datetime(df[])
df.set_index(, inplace=)
df = df.rename(columns={
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
:
})
df.sort_index()
Exception e:
()
ConnectionError()
:
data = get_a_stock_data(, , )
()
(data.head())
()
(data.describe())
Exception e:
(, (e))
()
()
()
()


