Skip to main content

股票搜索工具 - 支持中国A股和美股的搜索,具有本地缓存和增量更新功能

Project description

Stock Seek

股票价格历史数据搜索工具 | 支持 A股和美股

PyPI version License: MIT Python Versions Downloads


Stock Seek 是一个高效的股票价格搜索工具,支持根据历史价格(最高价、最低价、开盘价、收盘价)在 A股和美股历史数据中搜索匹配的股票。

核心功能:本地缓存 + 增量更新 + 定时自动更新


特性

  • 多市场支持:A股(沪深)、美股(NYSE/NASDAQ)
  • 多数据源:新浪、百度财经
  • 高效存储:Parquet 列式存储,节省空间且查询快
  • 增量更新:仅获取最新数据,避免重复下载
  • 全量重试:全量更新首轮失败标的会在任务末尾统一重试一次
  • 多模式并发:支持多线程和多进程两种并发模式,多进程模式可避免第三方库资源竞争问题
  • 定时任务:支持交易日自动更新(可配置)
  • 丰富搜索:支持按价格、位置、类型多维度搜索
  • 简单 API:易于集成到其他 Python 项目

安装

方式一:pip 安装(推荐)

pip install stock-seek

方式二:conda 安装

conda install -c conda-forge stock-seek

方式三:源码安装

git clone https://github.com/garen/stock-seek.git
cd stock-seek
pip install -e .

快速开始

1. 更新股票数据

# 首次使用,全量更新 A股数据(多线程模式)
stock-seek update -t 8

# 多进程模式(可避免某些数据源的并发资源竞争问题)
stock-seek update -t 8 -m process

# 增量更新(后续使用,只获取最新数据)
stock-seek update_inc

# 更新美股
stock-seek update_us -t 6
stock-seek update_us_inc

2. 搜索股票

# 搜索 2 天前最高价为 15.8 的 A股
stock-seek find -p 15.8 -pos 2 -t high

# 搜索 5 天前最低价为 12.5 的 A股(交互模式)
stock-seek find -p 12.5 -pos 5 -t low -i

# 搜索 3 天前收盘价为 150 的美股
stock-seek find_us -p 150 -pos 3 -t close

3. 查看缓存数据

# 查看 A股缓存
stock-seek print_cache -s 600519

# 查看美股缓存
stock-seek print_cache_us -s AAPL

4. 查询股票历史数据

# 查询 A股历史数据(从本地缓存)
stock-seek query -c 600519                          # 返回全部数据
stock-seek query -c 600519 -s 20240101              # 从指定日期到最新
stock-seek query -c 600519 -e 20240301              # 从最旧到指定日期
stock-seek query -c 600519 -s 20240101 -e 20240301  # 日期范围

# 查询美股历史数据
stock-seek query -c AAPL --us                        # 返回全部数据
stock-seek query -c AAPL -s 20240101 --us           # 日期范围

5. 导出/导入缓存数据

# 导出缓存到zip文件
stock-seek export                          # 导出到 stock_seek_backup.zip
stock-seek export -o my_backup.zip         # 指定输出文件
stock-seek export --no-token               # 不包含百度Token配置

# 从zip文件导入缓存
stock-seek import -i my_backup.zip

### 6. 清空本地缓存

```bash
# 清空所有缓存数据(需确认)
stock-seek clear --all --confirm

# 只清空数据缓存
stock-seek clear --cache --confirm

# 只清空更新日志
stock-seek clear --log --confirm

定时任务部署

启动调度器

# 前台运行
stock-seek scheduler start

# 后台运行
stock-seek scheduler start -d

查看状态

stock-seek scheduler status

配置调度时间

# A股调度时间(默认 16:00)
stock-seek scheduler config --china-time "16:30"

# 美股调度时间(默认 05:00)
stock-seek scheduler config --us-time "05:30"

# 配置并发模式和并发数
stock-seek scheduler config --mode process --workers 8

手动触发更新

# 触发 A股更新
stock-seek scheduler trigger

# 触发美股更新
stock-seek scheduler trigger --us

开机自启动

Linux (systemd)

创建服务文件 /etc/systemd/system/stock-seek-scheduler.service

[Unit]
Description=Stock Seek Scheduler Service
After=network.target

[Service]
Type=simple
User=your_username
WorkingDirectory=/path/to/project
ExecStart=/path/to/python -m stock_seek.scheduler.service
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

启用服务:

sudo systemctl enable stock-seek-scheduler
sudo systemctl start stock-seek-scheduler

Windows (计划任务)

# 创建开机启动计划任务
schtasks /create /tn "StockSeekScheduler" /tr "python -m stock_seek.scheduler.service" /sc onlogon /ru YOUR_USERNAME

查看日志

# 实时查看日志
tail -f ~/.stock_cache/stock_seek.log

# 查看日志文件位置
ls ~/.stock_cache/stock_seek.log*

Python API

基础使用

import stock_seek

# 更新数据
stock_seek.update_cache(source="bd", max_workers=8)

# 搜索股票
results = stock_seek.search_stock(
    price=15.8,
    position=2,
    search_type="high"
)

# 打印结果
for r in results:
    print(f"{r['code']} {r['name']} - 价格: {r['price']}")

增量更新

# 增量更新(自动判断全量/增量)
stock_seek.update_cache_incrementally()

获取股票数据

# 获取单只股票历史数据
df = stock_seek.get_stock_data("600519")
print(df.tail())

# 查询股票历史数据(从远程API)
df = stock_seek.query_stock_data("600519", "20240101", "20240301")
print(df)

配置缓存目录

from pathlib import Path

stock_seek.set_cache_dir(Path("/path/to/cache"))

配置参考

数据源

数据源 命令参数 说明
新浪 -s xl 默认,稳定性好
百度财经 -s bd 需要配置 Token

并发模式

全量更新支持两种并发模式,适用于不同场景:

模式 参数 说明
多线程(默认) -m thread 线程级并发,共享网络连接,适合低并发需求
多进程 -m process 进程级并发,每个进程独立网络连接,可避免第三方库资源竞争问题
# 多线程模式(默认)
stock-seek update -t 8 -m thread

# 多进程模式
stock-seek update -t 8 -m process

提示:如果在使用某些数据源时遇到 ConnectionResetErrorMax retries exceeded 等资源竞争相关报错,建议切换到多进程模式。

配置百度财经Token

# 设置Token
stock-seek config --baidu-cookie "你的Cookie" --baidu-acs-token "你的acs-token"

# 查看当前配置状态
stock-seek config --baidu-show

配置历史数据年数

# 设置A股历史数据年数(默认2年)
stock-seek config --china-years 2

# 设置美股历史数据年数(默认2年)
stock-seek config --us-years 3

注意:修改历史数据年数后需要执行全量更新才能生效

缓存目录

~/.stock_cache/
├── parquet/           # A股数据
├── parquet_us/        # 美股数据
├── stock_code_name.json
├── update_log.json    # 更新记录
├── scheduler_config.json  # 调度配置
└── app_config.json    # 应用配置

调度配置

配置文件:~/.stock_cache/scheduler_config.json

{
  "enabled": true,
  "china_schedule_time": "16:00",
  "us_schedule_time": "05:00",
  "smart_update": true,
  "source": "bd",
  "max_workers": 8,
  "mode": "thread",
  "trading_days_only": true
}

应用配置

配置文件:~/.stock_cache/app_config.json

{
  "a_share_history_years": 2,
  "us_stock_history_years": 2
}

常见问题

Q: 定时任务在电脑重启后还能执行吗?

需要配置开机自启动。详见上文「开机自启动」章节。

Q: 日历数据过期了怎么办?

调度器会自动检测并尝试升级 exchange-calendars 包。如自动升级失败,会输出提示命令,请手动执行:

pip install --upgrade exchange-calendars
# 或
conda install -y exchange-calendars

Q: A股调休工作日判断不准确?

exchange-calendars 对中国调休工作日支持有限。如遇特殊情况,可手动触发更新:

stock-seek scheduler trigger

Q: 如何查看更新是否成功?

# 查询最近一次更新记录
stock-seek history --last

# 查看最近一次记录中的完整失败标的与重试统计(JSON)
python - <<'PY'
import json
from pathlib import Path
p = Path.home() / '.stock_cache' / 'update_log.json'
rows = json.loads(p.read_text(encoding='utf-8')) if p.exists() else []
if not rows:
    print('暂无更新记录')
else:
    d = rows[-1].get('details', {})
    print('首次失败数量:', d.get('首次失败数量', 0))
    print('重试数量:', d.get('重试数量', 0))
    print('重试成功数量:', d.get('重试成功数量', 0))
    print('重试后失败数量:', d.get('重试后失败数量', 0))
    print('首次失败标的:', d.get('首次失败标的', []))
    print('重试后失败标的:', d.get('重试后失败标的', []))
PY

项目结构

stock_seek/
├── api/                    # 高级 API
├── cache/                  # 缓存管理
│   ├── cache_manager.py    # 缓存管理器
│   └── update_log_manager.py
├── cli/                    # 命令行入口
│   └── main.py
├── core/                   # 核心模块
│   ├── config.py
│   ├── exceptions.py
│   └── searcher.py
├── fetchers/               # 数据获取
│   ├── base_fetcher.py
│   ├── china_fetcher.py
│   ├── us_fetcher.py
│   └── baidu_fetcher.py
├── scheduler/              # 定时任务
│   ├── cache_watcher.py
│   ├── config_store.py
│   ├── scheduler_manager.py
│   ├── service.py
│   └── trade_calendar.py
└── utils/
    ├── data_api.py
    ├── helpers.py
    └── logger.py

贡献

欢迎提交 Issue 和 Pull Request!

# 克隆仓库
git clone https://github.com/garen/stock-seek.git

# 创建开发分支
git checkout -b feature/your-feature

# 安装开发依赖
pip install -e .[dev]

# 运行测试
pytest

# 代码格式化和检查
black .
ruff check .

许可证

MIT License


致谢

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

stock_seek-1.1.5.tar.gz (44.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

stock_seek-1.1.5-py3-none-any.whl (53.4 kB view details)

Uploaded Python 3

File details

Details for the file stock_seek-1.1.5.tar.gz.

File metadata

  • Download URL: stock_seek-1.1.5.tar.gz
  • Upload date:
  • Size: 44.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.19

File hashes

Hashes for stock_seek-1.1.5.tar.gz
Algorithm Hash digest
SHA256 90f3ec71c98bf6baf2b9aaad2499d4a791ca8221589a8be04a77bb8597803ffb
MD5 3b5ede6e4177a684b0756cdba605f1e4
BLAKE2b-256 5b3052898d80e27bdf7a6ab2764166f3acce7cbcd5803f83b6e7b46c6decc6a2

See more details on using hashes here.

File details

Details for the file stock_seek-1.1.5-py3-none-any.whl.

File metadata

  • Download URL: stock_seek-1.1.5-py3-none-any.whl
  • Upload date:
  • Size: 53.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.19

File hashes

Hashes for stock_seek-1.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 c01f1bddf2a497494d414a297efcf0766bd48fc6a6501e694b931c5bdbb776b9
MD5 27f1192ac99aa65e22f54a3e239ad009
BLAKE2b-256 b56435e15641dc70334b2e812f766c99b1fb1baf3f82fbb3e0530ea8138deb7f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page