资讯动态

Ptrade财务数据API实战:5分钟搞定股票基本面分析(附完整Python代码)

发布时间:2026/8/22 16:20:33 来源:尧图企业网站定制
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主要包含以下通用参数参数名类型必填说明securitystr/list是股票代码或列表table_namestr是数据表名称fieldsstr/list否查询字段datestr否查询日期start_yearstr否起始年份end_yearstr否结束年份2. 核心财务数据获取实战2.1 估值数据一键获取以下代码演示如何快速获取多只股票的估值指标def get_valuation_data(stock_list, dateNone): 获取股票估值数据 fields [pe_dynamic, pb, ps, dividend_ratio] data session.get_fundamentals( securitystock_list, table_namevaluation, fieldsfields, datedate ) # 百分比字段转换 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, years3): 获取三大报表关键指标 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_yearstart_year, report_types[4] # 年报 ) # 利润表 income_stmt session.get_fundamentals( stock_code, income_statement, fields[operating_revenue, net_profit], start_yearstart_year, report_types[4] ) # 现金流量表 cashflow session.get_fundamentals( stock_code, cashflow_statement, fields[net_operate_cash_flow], start_yearstart_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_nameprofit_ability ) # 结果可视化 fig, ax plt.subplots(figsize(10,6)) data.plot(kindbar, axax) ax.set_title(f{stock_code} 杜邦分析) ax.set_ylabel(比率) plt.xticks(rotation45) 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_roe0.15, max_pe30, min_current_ratio1.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(fError 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], sdf[ROE]*1000, cdf[ROE], alpha0.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, labelROE) return fig

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价