### Install akshare-proxy-patch Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/README.md Install the library using pip. ```bash pip install akshare-proxy-patch==0.5.0 ``` -------------------------------- ### Usage examples for install_yfinance_patch Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/008_configuration.md Demonstrates basic and advanced configuration for yfinance patching. ```python import akshare_proxy_patch # 基础配置 akshare_proxy_patch.install_yfinance_patch( "101.201.173.125", auth_token="your_token" ) # 高级配置 akshare_proxy_patch.install_yfinance_patch( "101.201.173.125", auth_token="your_token", retry=50, hook_domains=["finance.yahoo.com", "query1.finance.yahoo.com"] ) ``` -------------------------------- ### Define function signatures with type hints Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/010_types.md Example function signatures demonstrating the use of typing imports for data fetching and patch installation. ```python from typing import List, Dict, Tuple, Optional, Any import pandas as pd import threading # 函数签名示例 def fetch_paginated_data( url: str, base_params: Dict, timeout: int = 15 ) -> pd.DataFrame: ... def install_patch( auth_ip: str, auth_token: str = "", retry: int = 30, hook_domains: List[str] = default_hook_domains, timeout: int = 5, cookie: str = "", fast: bool = True, ) -> None: ... ``` -------------------------------- ### Request Lifecycle Example Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/012_architecture_and_internals.md Demonstrates the initialization of the patch and the internal flow of a request intercepted by the PatchedSession. ```python # 用户代码: import akshare_proxy_patch akshare_proxy_patch.install_patch("101.201.173.125", auth_token="xxx") import akshare as ak df = ak.stock_zh_a_spot_em() # 内部执行流程: # 1. install_patch() 执行 # ├─ 创建PatchedSession类 # ├─ 替换requests.Session = PatchedSession # ├─ install_fast_patch()替换fetch_paginated_data函数 # └─ 返回 # # 2. ak.stock_zh_a_spot_em() 调用 # ├─ akshare内部调用 fetch_paginated_data(url, params) # └─ 这时调用的是补丁版本 # # 3. fetch_paginated_data() 执行 # ├─ 发送首页请求 # │ └─ 调用 request_with_retry(url, params) (akshare库函数) # │ └─ 调用 requests.get(url, params) (标准库) # │ └─ 因为requests.Session=PatchedSession # │ └─ 调用PatchedSession.request() # │ ├─ 识别为目标域名 # │ ├─ 调用get_auth_config_with_cache() # │ │ ├─ 发送认证请求到101.201.173.125:47001 # │ │ └─ 获取代理配置、UA、Cookie # │ ├─ 注入代理和Headers # │ ├─ 使用curl_cffi转发请求 # │ └─ 返回响应 # │ # ├─ 解析首页,计算总页数 # ├─ 创建ThreadPoolExecutor # └─ 并发请求剩余页面 # ├─ 每个线程执行fetch_page() # │ └─ 同样经过PatchedSession.request()拦截 # └─ 收集所有结果 # # ├─ pd.concat()合并数据 # ├─ 排序和重置索引 # └─ 返回DataFrame # # 4. 用户代码接收完整的股票数据 ``` -------------------------------- ### Example target_browsers values Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/010_types.md Shows the expected format of the browser identifier list. ```python [ "chrome120", "chrome119", "edge120", "edge119", # ... 更多版本 ] ``` -------------------------------- ### Example of origin_backup Structure Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/010_types.md Illustrates the dictionary format used to map module and function names to their original implementations. ```python { ("module_name", "function_name"): original_function, ... } ``` ```python # 安装快速补丁后 { ("akshare", "fetch_paginated_data"): <原始函数>, ("akshare", "stock_individual_fund_flow_rank"): <原始函数>, ("akshare", "fund_money_fund_info_em"): <原始函数>, } ``` -------------------------------- ### Production Environment Configuration Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/008_configuration.md Example of a production-ready configuration with increased retry counts and specific domain filtering. ```python import akshare_proxy_patch # 生产环境配置 akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="production_token", retry=50, # 重试更多次 timeout=10, # 较长的超时 hook_domains=[ # 精确的域名列表 "push2.eastmoney.com/api/qt/clist/get", "push2his.eastmoney.com", ], fast=True, # 启用加速 ) ``` -------------------------------- ### Update akshare package Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/011_errors_and_troubleshooting.md Check for and install the latest version of akshare. ```bash # 检查akshare是否有新版本 pip list | grep akshare # 升级到最新版本 pip install --upgrade akshare ``` -------------------------------- ### Correct Import Ordering for Patch Installation Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/009_integration_patterns.md The patch must be installed before importing the target library to ensure hooks are applied correctly. ```python # ✗ 错误:导入顺序错误 import akshare as ak # 错误:先导入库 import akshare_proxy_patch akshare_proxy_patch.install_patch(...) # ✓ 正确 import akshare_proxy_patch akshare_proxy_patch.install_patch(...) import akshare as ak ``` -------------------------------- ### Usage of fund_cf_em Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/007_fund_functions.md Example demonstrating how to fetch and sort fund split records for a specific year. ```python import akshare_proxy_patch import akshare as ak akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", ) # 获取2025年所有基金拆分记录 df = ak.fund_cf_em(year="2025") # 按拆分日期排序(最近的在前) df_latest = ak.fund_cf_em(year="2025", rank="FSRQ", sort="desc") print(df_latest.head(20)) ``` -------------------------------- ### Querying Comprehensive Fund Data Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/007_fund_functions.md Demonstrates installing the patch with authentication and fetching multiple categories of fund data using Akshare. ```python import akshare_proxy_patch import akshare as ak import pandas as pd # 安装补丁 akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", ) # 获取多种基金数据 money_funds = ak.fund_money_fund_info_em() etf_funds = ak.fund_etf_fund_info_em() fh_records = ak.fund_fh_em(year="2025") cf_records = ak.fund_cf_em(year="2025") print(f"货币基金: {len(money_funds)} 只") print(f"ETF基金: {len(etf_funds)} 只") print(f"分红记录: {len(fh_records)} 条") print(f"拆分记录: {len(cf_records)} 条") ``` -------------------------------- ### Check akshare version Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/011_errors_and_troubleshooting.md Verify the installed version of akshare to ensure compatibility with the patch. ```python import akshare as ak print(f"akshare版本: {ak.__version__}") # 升级到最新版本 # pip install --upgrade akshare ``` -------------------------------- ### Usage of fund_fh_rank_em Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/007_fund_functions.md Example demonstrating how to fetch fund dividend rankings and filter by fund type. ```python import akshare_proxy_patch import akshare as ak akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", ) # 获取2025年分红最多的基金 df = ak.fund_fh_rank_em(year="2025") # Top 20 print(df.head(20)[["基金代码", "基金简称", "分红"]]) # 按基金类型过滤 stock_fund_fh = ak.fund_fh_rank_em(year="2025", typ="股票型") ``` -------------------------------- ### Test Connectivity and Install Patch Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/011_errors_and_troubleshooting.md Verify network connectivity to servers and apply the patch with increased retry and timeout settings. ```python import socket import akshare_proxy_patch # 步骤1:测试网络连接 def test_connectivity(host, port): try: socket.create_connection((host, port), timeout=5) print(f"✓ {host}:{port} 连接正常") return True except Exception as e: print(f"✗ {host}:{port} 连接失败: {e}") return False # 测试认证服务器 test_connectivity("101.201.173.125", 47001) # 测试数据服务器 test_connectivity("push2.eastmoney.com", 443) # 步骤2:尝试安装补丁 try: akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", retry=100, # 大幅增加重试次数 timeout=30, # 延长超时时间 ) except Exception as e: print(f"安装失败: {e}") ``` -------------------------------- ### Configure Multi-threaded Data Fetching Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/008_configuration.md Example of using ThreadPoolExecutor for concurrent page fetching with a fixed worker limit. ```python def fetch_paginated_data(url: str, base_params: Dict, timeout: int = 15): # 固定8个线程 max_workers = min(8, len(remaining_pages)) with ThreadPoolExecutor(max_workers=max_workers) as executor: # 并发执行 ... ``` -------------------------------- ### Manually enable fast mode Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/011_errors_and_troubleshooting.md Install the patch with fast mode disabled, then attempt to enable it manually afterwards. ```python import akshare_proxy_patch # 先禁用快速模式安装补丁 akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", fast=False, ) # 后续手动启用快速加速 try: akshare_proxy_patch.install_fast_patch() except Exception as e: print(f"快速模式启用失败: {e}") ``` -------------------------------- ### install_patch(auth_ip, auth_token, retry, hook_domains, timeout, cookie, fast) Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/000_INDEX.md Configures and installs the proxy patch to enable accelerated or authorized access to data sources. ```APIDOC ### install_patch(auth_ip, auth_token, retry, hook_domains, timeout, cookie, fast) #### Description Installs the proxy patch for the akshare library. This is required to route requests through the specified gateway. #### Parameters - **auth_ip** (string) - Required - The proxy gateway IP address. - **auth_token** (string) - Optional - Authorization token for the proxy. - **retry** (int) - Optional - Number of retry attempts (default: 30). - **hook_domains** (list) - Optional - List of domains to intercept. - **timeout** (int) - Optional - Request timeout in seconds (default: 5). - **cookie** (string) - Optional - Custom cookie string. - **fast** (bool) - Optional - Enable multi-threaded acceleration (default: True). ``` -------------------------------- ### akshare_proxy_patch.install_patch Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/README.md Installs a proxy patch for akshare or efinance libraries to resolve connectivity issues and enable multi-threaded acceleration. ```APIDOC ## install_patch(ip, auth_token, retry=30, hook_domains=None, fast=True) ### Description Installs the proxy patch for akshare or efinance. This must be called at the very top of the Python script before importing the target libraries. ### Parameters - **ip** (string) - Required - The gateway IP address. - **auth_token** (string) - Required - The authorization token obtained from the plugin website. - **retry** (int) - Optional - Number of retries, defaults to 30. - **hook_domains** (list) - Optional - List of domains to intercept and unblock. - **fast** (boolean) - Optional - Whether to enable multi-threaded acceleration for akshare, defaults to True. ``` -------------------------------- ### Disable fast mode Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/011_errors_and_troubleshooting.md Set the fast parameter to False during installation to bypass fast mode initialization issues. ```python import akshare_proxy_patch akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", fast=False, # 禁用快速模式 ) ``` -------------------------------- ### install_yfinance_patch(auth_ip, auth_token, retry, hook_domains) Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/003_install_yfinance_patch.md Installs a proxy patch for the yfinance library to intercept and route requests to Yahoo Finance through an authorized proxy gateway. ```APIDOC ## install_yfinance_patch(auth_ip, auth_token, retry, hook_domains) ### Description Installs a proxy patch for the yfinance library to resolve access issues for Yahoo Finance interfaces. It intercepts requests to specified domains and forwards them via an authorized proxy. ### Parameters - **auth_ip** (str) - Required - The authorized proxy gateway IP address. - **auth_token** (str) - Optional - The token authorization credential obtained from the plugin website. Defaults to "". - **retry** (int) - Optional - Number of retries upon request failure. Defaults to 30. - **hook_domains** (List[str]) - Optional - List of domains to intercept. Defaults to ["finance.yahoo.com"]. ### Returns - **None** ### Usage Example ```python import akshare_proxy_patch akshare_proxy_patch.install_yfinance_patch( "101.201.173.125", auth_token="your_token_here", retry=30 ) import yfinance as yf data = yf.download("AAPL") ``` ``` -------------------------------- ### Execute multi-process data collection Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/009_integration_patterns.md Utilizes the multiprocessing module to fetch historical stock data in parallel. Ensure the patch is installed in the main process before spawning worker processes. ```python # multiprocess_fetch.py import akshare_proxy_patch import akshare as ak from multiprocessing import Pool, cpu_count import pandas as pd # ========== 主进程安装补丁 ========== akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", fast=True, ) # ========== 获取股票代码 ========== def get_all_stock_codes(): df = ak.stock_zh_a_spot_em() return df["代码"].tolist() # ========== 单股票处理函数 ========== def fetch_stock_history(code): try: df = ak.stock_zh_a_hist( symbol=code, period="daily", start_year=2023, end_year=2024, adjust="qfq", ) df["代码"] = code return df except Exception as e: print(f"获取 {code} 失败: {e}") return None # ========== 多进程执行 ========== if __name__ == "__main__": # 获取所有股票代码 codes = get_all_stock_codes() print(f"总共 {len(codes)} 只股票") # 使用进程池 with Pool(processes=cpu_count()) as pool: results = pool.map(fetch_stock_history, codes) # 过滤和合并成功的结果 valid_results = [r for r in results if r is not None] all_df = pd.concat(valid_results, ignore_index=True) print(f"成功获取 {len(valid_results)} 只股票数据") print(f"总行数: {len(all_df)}") ``` ```bash python multiprocess_fetch.py ``` -------------------------------- ### Apply Configuration in Application Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/008_configuration.md Import settings from the config file and apply them using the install_patch function. ```python # app.py import akshare_proxy_patch from config import AUTH_IP, AUTH_TOKEN, RETRY, HOOK_DOMAINS, FAST akshare_proxy_patch.install_patch( AUTH_IP, auth_token=AUTH_TOKEN, retry=RETRY, hook_domains=HOOK_DOMAINS, fast=FAST, ) ``` -------------------------------- ### akshare_proxy_patch.uninstall_patch Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/README.md Disables the previously installed proxy patch. ```APIDOC ## uninstall_patch() ### Description Removes the monkey-patching applied to the libraries, effectively disabling the proxy and acceleration features. ``` -------------------------------- ### Define Configuration File Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/008_configuration.md Create a dedicated configuration file to manage authentication and network settings. ```python # config.py AUTH_IP = "101.201.173.125" AUTH_TOKEN = "your_token_here" RETRY = 30 TIMEOUT = 5 FAST = True HOOK_DOMAINS = [ "fund.eastmoney.com", "push2.eastmoney.com", "push2his.eastmoney.com", "emweb.securities.eastmoney.com", ] ``` -------------------------------- ### Troubleshoot Fast Mode Initialization Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/008_configuration.md Disable fast mode if initialization fails during startup. ```python # 症状:打印"启动快速模式失败:..." # 解决:禁用快速模式 akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", fast=False, # 禁用快速模式 ) ``` -------------------------------- ### Integrate Data Fetching into Flask Web Applications Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/009_integration_patterns.md Demonstrates how to initialize the patch on application startup and expose data via API endpoints. Requires the Flask framework. ```python # app.py from flask import Flask, jsonify import akshare_proxy_patch import akshare as ak app = Flask(__name__) # ========== 在应用启动时安装补丁 ========== @app.before_first_request def setup(): akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", fast=True, ) # ========== API端点 ========== @app.route("/api/stocks") def get_stocks(): try: df = ak.stock_zh_a_spot_em() return jsonify({ "status": "success", "data": df.to_dict(orient="records"), "total": len(df), }) except Exception as e: return jsonify({ "status": "error", "message": str(e), }), 500 @app.route("/api/funds") def get_funds(): try: df = ak.fund_etf_fund_info_em() return jsonify({ "status": "success", "data": df.to_dict(orient="records"), "total": len(df), }) except Exception as e: return jsonify({ "status": "error", "message": str(e), }), 500 if __name__ == "__main__": app.run(debug=True, port=5000) ``` ```bash python app.py ``` -------------------------------- ### 基础用法示例 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/001_install_patch.md 在导入 akshare 之前调用 install_patch 以应用默认的代理补丁配置。 ```python import akshare_proxy_patch # 在导入akshare之前安装补丁 akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token_here", retry=30, ) # 后续代码保持不变 import akshare as ak df = ak.stock_zh_a_spot_em() ``` -------------------------------- ### Enable detailed logging Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/011_errors_and_troubleshooting.md Configures standard logging and urllib3 debug output to trace network activity. ```python import logging # 启用requests调试 logging.basicConfig(level=logging.DEBUG) logging.getLogger("urllib3").setLevel(logging.DEBUG) # 启用自定义日志 logger = logging.getLogger("akshare_patch") logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() logger.addHandler(handler) ``` -------------------------------- ### Enable Fast Mode Patch Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/008_configuration.md Initialize the patch with a token and enable fast mode for acceleration. ```python import akshare_proxy_patch akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", fast=True # 启用 ) ``` -------------------------------- ### 函数签名定义 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/003_install_yfinance_patch.md 展示了 install_yfinance_patch 函数的参数结构及默认值。 ```python def install_yfinance_patch( auth_ip: str, auth_token: str = "", retry: int = 30, hook_domains: List[str] = ["finance.yahoo.com"] ) -> None ``` -------------------------------- ### Increase global timeout via patch Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/011_errors_and_troubleshooting.md Adjust the timeout parameter during the initial patch installation to handle slow network responses. ```python import akshare_proxy_patch akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", timeout=30, # 从5秒增加到30秒 ) ``` -------------------------------- ### install_patch() Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/008_configuration.md Configures the proxy patch for AKShare, allowing users to set gateway IP, authentication tokens, retry logic, and domain interception rules. ```APIDOC ## install_patch(auth_ip, auth_token, retry, hook_domains, timeout, cookie, fast) ### Description Configures the proxy gateway settings for AKShare data requests. ### Parameters - **auth_ip** (str) - Required - 授权代理网关IP地址 - **auth_token** (str) - Optional - TOKEN授权凭证 (Default: "") - **retry** (int) - Optional - 请求失败重试次数 (Default: 30, Range: 1-1000) - **hook_domains** (List[str]) - Optional - 需要拦截的目标域名列表 - **timeout** (int) - Optional - HTTP请求超时时间(秒) (Default: 5, Range: 1-300) - **cookie** (str) - Optional - 自定义Cookie (Default: "") - **fast** (bool) - Optional - 是否启用多线程加速 (Default: True) ``` -------------------------------- ### install_patch(auth_ip, auth_token, retry, hook_domains, timeout, cookie, fast) Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/001_install_patch.md 为标准库 requests 和 curl_cffi 安装代理补丁,拦截指定域名的 HTTP 请求并进行代理转发。 ```APIDOC ## install_patch(auth_ip, auth_token, retry, hook_domains, timeout, cookie, fast) ### 描述 为标准库 `requests` 和 `curl_cffi` 安装代理补丁,用于解决国内访问东方财富等接口受限的问题。该补丁会拦截指定域名的HTTP请求,通过授权代理转发请求。 ### 参数 - **auth_ip** (str) - 必需 - 授权代理网关IP地址 - **auth_token** (str) - 可选 - TOKEN授权凭证,从插件官网获取 - **retry** (int) - 可选 - 请求失败时的重试次数,默认 30 - **hook_domains** (List[str]) - 可选 - 需要拦截的域名列表 - **timeout** (int) - 可选 - HTTP请求超时时间(秒),默认 5 - **cookie** (str) - 可选 - 自定义Cookie值 - **fast** (bool) - 可选 - 是否启用多线程加速模式,默认 True ### 返回类型 None ### 示例 ```python import akshare_proxy_patch akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token_here", retry=30 ) ``` ``` -------------------------------- ### 启用性能优化 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/000_INDEX.md 通过设置 fast 参数启用多线程加速,适用于需要快速获取大量数据的场景。 ```python akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="XXX", fast=True # 启用多线程加速 ) ``` -------------------------------- ### Implement Robust Data Fetching with Retries Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/009_integration_patterns.md Uses a decorator to wrap AkShare functions, providing automatic retries upon failure. Requires the akshare-proxy-patch library to be installed and configured before execution. ```python # robust_fetch.py import akshare_proxy_patch import akshare as ak import time from functools import wraps # ========== 安装补丁 ========== akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", retry=50, ) # ========== 重试装饰器 ========== def retry_on_failure(max_attempts=3, delay=5): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, max_attempts + 1): try: return func(*args, **kwargs) except Exception as e: if attempt < max_attempts: print(f"第 {attempt} 次尝试失败: {e},等待 {delay} 秒后重试...") time.sleep(delay) else: print(f"第 {attempt} 次尝试失败,已达到最大重试次数") raise return wrapper return decorator # ========== 业务函数 ========== @retry_on_failure(max_attempts=3, delay=5) def fetch_stock_data(): df = ak.stock_zh_a_spot_em() return df @retry_on_failure(max_attempts=3, delay=5) def fetch_fund_flow(indicator): df = ak.stock_individual_fund_flow_rank(indicator=indicator) return df # ========== 使用 ========== if __name__ == "__main__": try: stocks = fetch_stock_data() print(f"成功获取 {len(stocks)} 只股票") flows = fetch_fund_flow(indicator="5日") print(f"成功获取 {len(flows)} 条资金流数据") except Exception as e: print(f"最终失败: {e}") ``` -------------------------------- ### Troubleshoot Authorization Failure Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/008_configuration.md Verify token validity and network reachability if authorization fails. ```python # 症状:打印"授权失败: ..." # 解决: # 1. 检查auth_token是否有效 # 2. 检查网络连接是否正常 # 3. 检查auth_ip是否可达 akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="check_your_token", retry=50, # 增加重试次数 ) ``` -------------------------------- ### install_patch 函数签名 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/001_install_patch.md 函数定义及参数列表,用于配置代理网关、授权凭证及拦截行为。 ```python def install_patch( auth_ip: str, auth_token: str = "", retry: int = 30, hook_domains: List[str] = default_hook_domains, timeout: int = 5, cookie: str = "", fast: bool = True, ) -> None ``` -------------------------------- ### Configure akshare or efinance Patch Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/README.md Initialize the patch at the very top of your Python script before importing akshare or efinance. ```python # python 文件顶部添加如下代码 # 插件引入和调用一定要放到最顶部!不能在 akshare 或 efinance 之后引入! import akshare_proxy_patch akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="你的TOKEN", retry=30, # 封控的域名列表,可自行调整 hook_domains=[ "fund.eastmoney.com", "push2.eastmoney.com", "push2his.eastmoney.com", "emweb.securities.eastmoney.com", "searchapi.eastmoney.com/api/suggest/get" ], fast=True ) # -------------------------- # 后续你的正常业务代码保持不变 # -------------------------- # 假如你使用 akshare import akshare as ak df = ak.stock_zh_a_spot_em() # 假如你使用 efinance import efinance as ef ef.stock.get_realtime_quotes() ``` -------------------------------- ### Check version information Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/011_errors_and_troubleshooting.md Access the current package version for troubleshooting reports. ```python akshare_proxy_patch.__version__ ``` -------------------------------- ### 实现缓存管理机制 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/010_types.md 通过加锁机制实现线程安全的缓存检查与更新,在缓存失效时请求新配置并验证。 ```python def get_auth_config_with_cache(auth_url, auth_token): now = time.time() # 1. 检查缓存是否有效 if _cache.data and now < _cache.expire_at: return _cache.data # 2. 缓存失效或不存在,加锁更新 with _cache.lock: if _cache.data and now < _cache.expire_at: return _cache.data # 3. 向授权服务器请求新配置 try: resp = _auth_session.get(auth_url, params={...}) data = resp.json() # 4. 验证并缓存 if data.get("ua") or data.get("proxy"): _cache.data = data _cache.expire_at = now + _cache.ttl return data else: print(f"授权失败: {data.get('error_msg')}") except: pass return _cache.data # 返回旧缓存 ``` -------------------------------- ### Configure hook_domains for stock and fund data Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/008_configuration.md Intercept both stock and fund related domains. ```python hook_domains=[ "push2.eastmoney.com", "fund.eastmoney.com", ] ``` -------------------------------- ### Define origin_backup Variable Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/010_types.md Stores original functions for restoration during uninstallation. ```python origin_backup: Dict[Tuple[str, str], Callable] = {} ``` -------------------------------- ### Initialize thread pool executor Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/010_types.md Configures a thread pool with 8 workers for handling paginated requests. ```python ThreadPoolExecutor(max_workers=8) # 用于分页请求的线程池 ``` -------------------------------- ### Configure yfinance Patch Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/README.md Initialize the yfinance-specific patch at the top of your script. ```python # python 文件顶部添加如下代码 # 插件引入和调用一定要放到最顶部!不能在 akshare 或 efinance 之后引入! import akshare_proxy_patch akshare_proxy_patch.install_yfinance_patch( "101.201.173.125", auth_token="你的TOKEN", retry=30, ) # -------------------------- # 后续你的正常业务代码保持不变 # -------------------------- import yfinance as yf data = yf.download("AAPL", start="2017-01-01", end="2017-04-30") ``` -------------------------------- ### 验证 TOKEN 与网络连接 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/011_errors_and_troubleshooting.md 排查授权失败时用于检查 TOKEN 格式及测试服务器连通性的代码。 ```python import akshare_proxy_patch # 打印当前使用的TOKEN(注意隐私) auth_token = "your_token_here" print(f"TOKEN长度: {len(auth_token)}") print(f"TOKEN格式: {auth_token[:10]}...") # 仅打印前10个字符 ``` ```python import requests try: resp = requests.get( "http://101.201.173.125:47001/api/akshare-auth", params={"token": "test_token", "version": "0.5.0"}, timeout=5 ) print(f"响应状态: {resp.status_code}") print(f"响应内容: {resp.json()}") except Exception as e: print(f"连接失败: {e}") ``` -------------------------------- ### 禁用快速模式示例 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/001_install_patch.md 通过设置 fast=False 参数手动禁用多线程加速模式。 ```python import akshare_proxy_patch akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token_here", fast=False, ) import akshare as ak df = ak.stock_zh_a_spot_em() ``` -------------------------------- ### Configure hook_domains for all data Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/008_configuration.md Intercept all available data domains including search APIs. ```python hook_domains=[ "fund.eastmoney.com", "push2.eastmoney.com", "push2his.eastmoney.com", "emweb.securities.eastmoney.com", "searchapi.eastmoney.com/api/suggest/get", ] ``` -------------------------------- ### View Source Code Location Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/MANIFEST.md Displays the standard format used to reference the source code location for each documented function. ```text 源码位置: akshare_proxy_patch/模块路径:行号-行号 ``` ```text 例如: - `akshare_proxy_patch/__init__.py:90-184` — install_patch()的完整实现 - `akshare_proxy_patch/yfinance.py:50-95` — yfinance补丁的核心实现 ``` -------------------------------- ### Implement environment-aware patching Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/009_integration_patterns.md Configures the proxy patch differently based on the ENVIRONMENT environment variable. Requires the ENVIRONMENT variable to be set to 'production' or 'development'. ```python # env_aware.py import os import sys import akshare_proxy_patch # ========== 根据环境配置 ========== ENV = os.getenv("ENVIRONMENT", "development") if ENV == "production": # 生产环境:完整配置 akshare_proxy_patch.install_patch( "101.201.173.125", auth_token=os.getenv("AUTH_TOKEN"), retry=50, timeout=10, hook_domains=[ "fund.eastmoney.com", "push2.eastmoney.com", "push2his.eastmoney.com", "emweb.securities.eastmoney.com", ], fast=True, ) elif ENV == "development": # 开发环境:最少配置 akshare_proxy_patch.install_patch( "101.201.173.125", auth_token=os.getenv("AUTH_TOKEN"), retry=30, hook_domains=["push2.eastmoney.com"], fast=False, ) else: print("未知环境") sys.exit(1) # ========== 业务代码保持一致 ========== import akshare as ak def get_data(): return ak.stock_zh_a_spot_em() if __name__ == "__main__": print(f"运行环境: {ENV}") df = get_data() print(f"获取到 {len(df)} 条数据") ``` ```bash ENVIRONMENT=production python env_aware.py ENVIRONMENT=development python env_aware.py ``` -------------------------------- ### Optimize Memory Usage with as_completed Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/012_architecture_and_internals.md Processes results as they complete to avoid loading all data into memory simultaneously. ```python # 使用as_completed而非map # as_completed立即返回完成的任务,不用等所有任务完成 # 这样可以及时处理数据而不用一次性在内存中加载所有结果 for future in as_completed(futures): # 立即返回 # 处理单个结果 result = future.result() process(result) # 可以及时释放内存 ``` -------------------------------- ### 自定义超时时间 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/004_fetch_paginated_data.md 在网络环境不稳定时,可以通过 timeout 参数增加请求等待时间。 ```python from akshare_proxy_patch.akshare_src.func import fetch_paginated_data url = "https://push2.eastmoney.com/api/qt/clist/get" params = { "fid": "f62", "po": "1", "pz": "100", "pn": "1", } # 网络不稳定时增加超时时间 df = fetch_paginated_data(url, params, timeout=30) ``` -------------------------------- ### 函数签名 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/002_uninstall_patch.md 定义 uninstall_patch 函数的调用接口。 ```python def uninstall_patch() -> None ``` -------------------------------- ### Module Interaction Structure Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/012_architecture_and_internals.md Visual representation of the directory structure and functional dependencies within the project. ```text akshare_proxy_patch/ │ ├─ __init__.py (主入口) │ │ │ ├─ 导入curl_cffi │ ├─ 导入标准requests │ ├─ 创建AuthCache实例 │ ├─ 定义PatchedSession类 │ │ │ ├─ install_patch() │ │ └─ 使用 akshare_src.func:fetch_paginated_data │ │ └─ 使用 akshare_src.stock:stock_*函数 │ │ └─ 使用 akshare_src.fund:fund_*函数 │ │ │ ├─ install_fast_patch() │ │ └─ 导入akshare模块 │ │ └─ 替换其中的函数 │ │ │ └─ uninstall_patch() │ └─ 从origin_backup恢复原始函数 │ ├─ yfinance.py │ ├─ get_auth_config_with_cache() │ └─ install_yfinance_patch_main() │ └─ 替换curl_cffi.requests.Session.request() │ └─ akshare_src/ ├─ func.py │ ├─ fetch_paginated_data() (核心分页函数) │ └─ set_df_columns() │ ├─ stock/ │ └─ stock_fund_em.py │ ├─ stock_individual_fund_flow_rank() │ ├─ stock_sector_fund_flow_rank() │ └─ ... 其他函数 │ └─ fund/ ├─ fund_em.py │ ├─ fund_money_fund_info_em() │ ├─ fund_graded_fund_info_em() │ └─ fund_etf_fund_info_em() │ └─ fund_fhsp_em.py ├─ fund_fh_em() ├─ fund_cf_em() └─ fund_fh_rank_em() ``` -------------------------------- ### Configure Concurrency Settings Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/012_architecture_and_internals.md Defines thread pool limits and request intervals to balance performance and server rate limiting. ```python # 线程池大小 max_workers = min(8, len(pages)) # 优势:8个线程在大多数网络上都是最优 # 代价:超过8个线程反而会降低性能 # 请求间隔 time.sleep(random.uniform(0.5, 1.5)) # 优势:避免服务器限流 # 代价:总耗时 = 响应时间 + 延迟时间 ``` -------------------------------- ### 获取所有A股数据 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/000_INDEX.md 使用代理补丁获取A股实时行情数据。需在调用 akshare 函数前完成补丁安装。 ```python import akshare_proxy_patch import akshare as ak akshare_proxy_patch.install_patch("101.201.173.125", auth_token="XXX") df = ak.stock_zh_a_spot_em() ``` -------------------------------- ### Configure Caching Strategies Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/012_architecture_and_internals.md Sets TTL for authentication and uses lru_cache for DataFrame results to reduce redundant network requests. ```python # 授权缓存 _cache.ttl = 28 # 秒 # 优势:避免频繁认证请求 # 代价:认证配置最多延迟28秒更新 # DataFrame缓存(可选) import functools @functools.lru_cache(maxsize=3) def get_stock_list(): return ak.stock_zh_a_spot_em() ``` -------------------------------- ### 基础卸载示例 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/002_uninstall_patch.md 展示在完成 akshare 数据获取后,如何调用 uninstall_patch 恢复原始请求行为。 ```python import akshare_proxy_patch # 安装补丁 akshare_proxy_patch.install_patch("101.201.173.125", auth_token="token") import akshare as ak df = ak.stock_zh_a_spot_em() # 后续需要关闭补丁 akshare_proxy_patch.uninstall_patch() # 现在所有请求都不经过代理 import requests r = requests.get("https://example.com") ``` -------------------------------- ### Configure HTTP timeout tuple Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/010_types.md Defines a tuple for connection and read timeouts in seconds. ```python timeout: Tuple[float, float] = (1.5, 3) # (连接超时, 读取超时) ``` -------------------------------- ### Optimizing Performance with Hook Domains Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/009_integration_patterns.md Restrict hook domains to only those strictly necessary to prevent performance degradation. ```python # ✓ 解决:精确配置hook_domains # 仅配置需要的域名 hook_domains = ["push2.eastmoney.com/api/qt/clist/get"] ``` -------------------------------- ### 定义 AuthCache 类 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/010_types.md AuthCache类用于管理授权数据的缓存,包含数据存储、过期时间戳、线程锁和生存时间配置。 ```python class AuthCache: def __init__(self): self.data = None # 缓存的授权数据 (Dict | None) self.expire_at = 0 # 过期时间戳 (float) self.lock = threading.Lock() # 线程锁 (threading.Lock) self.ttl = 28 # 生存时间(秒)(int) ``` -------------------------------- ### 自定义重试次数 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/003_install_yfinance_patch.md 通过设置 retry 参数来应对不稳定的网络环境。 ```python import akshare_proxy_patch akshare_proxy_patch.install_yfinance_patch( "101.201.173.125", auth_token="your_token_here", retry=50, # 增加重试次数处理网络不稳定 ) import yfinance as yf ticker = yf.Ticker("MSFT") hist = ticker.history(period="1y") ``` -------------------------------- ### 自定义域名拦截示例 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/001_install_patch.md 通过 hook_domains 参数指定特定域名进行拦截,以减少不必要的积分消耗。 ```python import akshare_proxy_patch akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token_here", hook_domains=["push2.eastmoney.com/api/qt/clist/get"], retry=20, timeout=10, ) import akshare as ak df = ak.stock_zh_a_spot_em() ``` -------------------------------- ### 获取ETF基金信息 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/007_fund_functions.md 获取ETF基金信息列表的函数签名及筛选规模大于10亿的ETF示例。 ```python def fund_etf_fund_info_em() -> pd.DataFrame ``` ```python import akshare_proxy_patch import akshare as ak akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", ) # 获取所有ETF基金信息 etf_df = ak.fund_etf_fund_info_em() print(f"ETF总数: {len(etf_df)}") # 筛选规模大于10亿的ETF large_etf = etf_df[etf_df["基金规模"] > 1000000000] print(large_etf[["基金代码", "基金名称", "基金规模"]]) ``` -------------------------------- ### 多板块类型对比 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/006_stock_sector_fund_flow_rank.md 演示如何同时获取行业、概念和地域三种不同板块类型的数据。 ```python import akshare_proxy_patch import akshare as ak akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="your_token", ) # 获取不同板块类型数据 industry = ak.stock_sector_fund_flow_rank( indicator="今日", sector_type="行业资金流" ) concept = ak.stock_sector_fund_flow_rank( indicator="今日", sector_type="概念资金流" ) region = ak.stock_sector_fund_flow_rank( indicator="今日", sector_type="地域资金流" ) print(f"行业板块数: {len(industry)}") print(f"概念板块数: {len(concept)}") print(f"地域板块数: {len(region)}") ``` -------------------------------- ### Configuring Memory Management Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/009_integration_patterns.md Disable fast mode to mitigate continuous memory growth during high-frequency operations. ```python # ✓ 解决:禁用快速模式或定期清理缓存 akshare_proxy_patch.install_patch( "101.201.173.125", auth_token="token", fast=False, # 禁用多线程加速 ) ``` -------------------------------- ### 获取资金流排名 Source: https://github.com/helloyie/akshare-proxy-patch/blob/master/_autodocs/000_INDEX.md 获取个股资金流向排名数据,支持指定统计周期。 ```python df = ak.stock_individual_fund_flow_rank(indicator="5日") ```