Ptrade财务数据API实战:5分钟搞定股票基本面分析(附完整Python代码)
在量化投资领域,基本面分析是构建稳健策略的基石。传统手动收集财务数据的方式效率低下,而Ptrade提供的财务数据API恰好解决了这一痛点。本文将带你快速上手这套工具,用不到5分钟的时间完成从数据获取到可视化分析的全流程。
1. 环境准备与API基础配置
1.1 安装必要依赖
确保你的Python环境已安装以下核心库:
pip install pandas numpy matplotlib requests对于Ptrade API的接入,通常需要先完成券商账户绑定和权限申请。不同券商的接入方式略有差异,但核心认证流程相似:
# 认证配置示例(以模拟环境为例) import ptrade_api as pt config = { "username": "your_account", "password": "your_password", "host": "trade.yourbroker.com", "port": 443, "auto_retry": True } # 初始化连接 session = pt.PTrade(config)注意:实际使用时需替换为真实的账户信息,生产环境建议将敏感信息存储在环境变量中
1.2 接口核心参数速查
Ptrade财务API主要包含以下通用参数:
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| security | str/list | 是 | 股票代码或列表 |
| table_name | str | 是 | 数据表名称 |
| fields | str/list | 否 | 查询字段 |
| date | str | 否 | 查询日期 |
| start_year | str | 否 | 起始年份 |
| end_year | str | 否 | 结束年份 |
2. 核心财务数据获取实战
2.1 估值数据一键获取
以下代码演示如何快速获取多只股票的估值指标:
def get_valuation_data(stock_list, date=None): """获取股票估值数据""" fields = ['pe_dynamic', 'pb', 'ps', 'dividend_ratio'] data = session.get_fundamentals( security=stock_list, table_name='valuation', fields=fields, date=date ) # 百分比字段转换 percent_cols = ['dividend_ratio'] for col in percent_cols: if col in data.columns: data[col] = data[col].str.replace('%','').astype(float) / 100 return data # 示例:获取沪深300成分股最新估值 hs300 = session.get_index_stocks('000300.XSHG') valuation_df = get_valuation_data(hs300) print(valuation_df.head())2.2 三大财务报表集成查询
通过组合查询可以大幅提升效率:
def get_financial_statements(stock_code, years=3): """获取三大报表关键指标""" current_year = pd.Timestamp.now().year start_year = str(current_year - years + 1) # 资产负债表 balance_sheet = session.get_fundamentals( stock_code, 'balance_statement', fields=['total_assets', 'total_liabilities', 'total_equity'], start_year=start_year, report_types=['4'] # 年报 ) # 利润表 income_stmt = session.get_fundamentals( stock_code, 'income_statement', fields=['operating_revenue', 'net_profit'], start_year=start_year, report_types=['4'] ) # 现金流量表 cashflow = session.get_fundamentals( stock_code, 'cashflow_statement', fields=['net_operate_cash_flow'], start_year=start_year, report_types=['4'] ) return { 'balance_sheet': balance_sheet, 'income_statement': income_stmt, 'cashflow': cashflow }3. 财务指标智能分析
3.1 杜邦分析自动化实现
def dupont_analysis(stock_code): """自动化杜邦分析""" data = session.get_fundamentals( stock_code, fields=['roe', 'net_profit_ratio', 'total_asset_turnover', 'equity_multiplier'], table_name='profit_ability' ) # 结果可视化 fig, ax = plt.subplots(figsize=(10,6)) data.plot(kind='bar', ax=ax) ax.set_title(f'{stock_code} 杜邦分析') ax.set_ylabel('比率') plt.xticks(rotation=45) plt.tight_layout() return fig3.2 财务健康度评分模型
建立简单的评分体系:
def financial_health_score(stock_code): """财务健康度评分(0-100)""" # 获取关键指标 indicators = session.get_fundamentals( stock_code, table_name=['profit_ability', 'debt_paying_ability'], fields=['current_ratio', 'quick_ratio', 'debt_to_equity', 'interest_coverage'] ) # 评分规则 score = 0 if indicators['current_ratio'] > 2: score += 25 if indicators['quick_ratio'] > 1: score += 25 if indicators['debt_to_equity'] < 1: score += 25 if indicators['interest_coverage'] > 3: score += 25 return score4. 实战案例:消费行业筛选系统
4.1 行业股票池构建
def get_industry_stocks(industry_code): """获取行业成分股""" return session.get_industry_stocks(industry_code) # 示例:获取白酒行业股票 liquor_stocks = get_industry_stocks('C1515')4.2 多因子筛选策略
def screen_stocks(stock_list, min_roe=0.15, max_pe=30, min_current_ratio=1.5): """基本面筛选""" results = [] for stock in stock_list: try: # 获取估值数据 valuation = get_valuation_data([stock]) # 获取财务指标 ratios = session.get_fundamentals( stock, table_name=['profit_ability', 'debt_paying_ability'], fields=['roe', 'current_ratio'] ) # 筛选条件 if (valuation['pe_dynamic'].iloc[0] <= max_pe and ratios['roe'].iloc[0] >= min_roe and ratios['current_ratio'].iloc[0] >= min_current_ratio): results.append(stock) except Exception as e: print(f"Error processing {stock}: {str(e)}") return results # 执行筛选 qualified_stocks = screen_stocks(liquor_stocks) print(f"符合标准的股票:{qualified_stocks}")4.3 结果可视化分析
def plot_industry_comparison(stock_list): """行业对比分析""" data = [] for stock in stock_list: vals = get_valuation_data([stock]).iloc[0] data.append({ 'code': stock, 'PE': vals['pe_dynamic'], 'PB': vals['pb'], 'ROE': vals['roe'] }) df = pd.DataFrame(data).set_index('code') # 绘制散点图 fig, ax = plt.subplots(figsize=(12,8)) scatter = ax.scatter( df['PE'], df['PB'], s=df['ROE']*1000, c=df['ROE'], alpha=0.6 ) # 添加标注 for i, txt in enumerate(df.index): ax.annotate(txt, (df['PE'].iloc[i], df['PB'].iloc[i])) ax.set_xlabel('市盈率(PE)') ax.set_ylabel('市净率(PB)') ax.set_title('行业估值-ROE气泡图') plt.colorbar(scatter, label='ROE') return fig