乐于分享
好东西不私藏

PTrade下载财务数据(附代码)

PTrade下载财务数据(附代码)

PTrade介绍见 Ptrade介绍

本文介绍下如何使用PTrade获取财务数据,使用get_fundamentals函数

get_fundamentals(security, table, fields = None, date = None, start_year = None, end_year = None, report_types = None, merge_type = None, is_dataframe = False)

security:一支股票代码或者多只股票代码组成的list(list[str])

table:财务数据表名,输入具体表名可查询对应表中信息(str)

表名
包含内容
valuation
估值数据
balance_statement
资产负债表
income_statement
利润表
cashflow_statement
现金流量表
growth_ability
成长能力指标
profit_ability
盈利能力指标
eps
每股指标
operating_ability
营运能力指标
debt_paying_ability
偿债能力指标

其中valuation估值数据的获取方式不太一样,本节先不介绍这个,主要介绍其它几个表

fields:指明数据结果集中所需输出业务字段,支持多个业务字段输出(list类型),如fields=[‘settlement_provi’, ‘client_provi’](list[str]);

date:查询日期,按日期查询模式,返回查询日期之前对应的财务数据,输入形式如’20170620’;支持datetime.date时间格式输入,不能与start_year与end_year同时作用;支持按日期查询模式,不传入date时默认取回测日期的上一个交易日数据(str);

start_year:查询开始年份,按年份查询模式,返回输入年份范围内对应的财务数据,如’2015’,start_year与end_year必须同时输入,且不能与date同时作用(str)

end_year:查询截止年份,按年份查询模式,返回输入年份范围内对应的财务数据,如’2015’,start_year与end_year必须同时输入,且不能与date同时作用(str)

report_types:财报类型;如果为年份查询模式(start_year/end_year),不输入report_types返回当年可查询到的全部类型财报;如果为日期查询模式(date),不输入report_types返回距离指定日期最近一份财报(str)。

  • ‘1’:表示获取一季度财报
  • ‘2’:表示获取半年报
  • ‘3’:表示获取截止到三季度财报
  • ‘4’:表示获取年度财报

merge_type:数据更新设置;相关财务数据信息会不断进行修正更新,为了避免未来数据影响,可以通过参数获取原始发布或最新发布数据信息;只有部分表包含此字段(int) :

  • merge_type不传或传入merge_type = None,获取首次发布的数据,即使实际数据发生变化,也只返回原样数据信息;回测场景为避免未来数据建议使用此模式
  • merge_type传入1,获取已发布财报数据的更新数据,更新数据范围包括但不限于相关日期数据,研究场景或交易场景建议使用此模式,但需要指定报告期,否则会获取到历史最近一期有过更新情况的财报数据(不一定是最近一个财报期)

is_dataframe:True-返回DataFrame格式;False-返回pandas.Panel格式(默认,仅python3.5的按年份查询模式有效)。

参考代码(方便复制见平台帖子https://quantkt.com/forumDetail?id=201223)

"""下载全部财务数据,输出UTF-8编码CSV"""import osimport pandas as pddef initialize(context):    g.path = get_research_path()    g.sy, g.ey = "2010""2099"    run_daily(context, func=down_data, time="14:15")def handle_data(context, data):    passdef down_data(context):#stock = get_Ashares()    stock = ['000001.SZ','000002.SZ']# 接口名、保存csv文件名    tbls = [        ("balance_statement""资产负债表.csv"),        ("income_statement""利润表.csv"),        ("cashflow_statement""现金流量表.csv"),        ("growth_ability""成长能力指标.csv"),        ("profit_ability""盈利能力指标.csv"),        ("eps""每股指标.csv"),        ("operating_ability""营运能力指标.csv"),        ("debt_paying_ability""偿债能力指标.csv"),    ]print("开始下载财务数据")for api, name in tbls:        fpath = os.path.join(g.path, name)df = get_fundamentals(stock, api, start_year=g.sy, end_year=g.ey)        df.to_csv(fpath, index=False, encoding="utf-8-sig")print(f"{name} 完成")print("全部下载完毕")

由于回测也能用,且已经设置了start_year和end_year,所以直接随便单个交易日回测即可

下载完各csv如下

可从ptrade服务器下载保存到本地

盈利能力指标.csv如下

成长能力指标.csv

其它的csv也类似

各个表格内部字段如下

1. 资产负债表.csv

字段名
independence_account_assets
deposit_of_interbank
other_assets
retained_profit
commission_payable
dividend_receivable
taxs_payable
inventories
total_non_current_assets
deposit_in_interbank
other_composite_income
bonds_payable
long_salaries_pay
t_constru_in_process
oil_gas_assets
interest_receivable
borrowing_capital
impawned_loan
loan_and_advance
total_liability_and_equity
advance_receipts
receivable_lt_health_r
advance_insurance
other_equityinstruments
independence_liability
dividend_payable
capital_reserve_fund
se_without_mi
other_non_current_assets
refundable_capital_deposit
total_current_liability
total_liability
trading_liability
insurer_deposit_investment
other_receivable
total_shareholder_equity
non_current_asset_in_one_year
long_deferred_expense
outstanding_claim_reserve
construction_materials
treasury_stock
r_metal
other_liability
client_deposit
receivable_unearned_r
receivable_subrogation_fee
longterm_receivable_account
shortterm_loan
receivable_claims_r
hold_to_maturity_investments
specific_account_payable
policy_dividend_payable
client_provi
compensation_payable
cash_equivalents
account_receivable
publ_date
surplus_reserve_fund
other_payable
longterm_loan
secu_abbr
specific_reserves
non_current_liability_in_one_year
sub_issue_secu_proceeds
fixed_assets_liquidation
sold_buyback_secu_proceeds
hold_for_sale_assets
foreign_currency_report_conv_diff
lend_capital
reinsurance_payables
other_current_liability
reinsurance_receivables
trading_assets
lt_health_insurance_lr
ordinary_risk_reserve_fund
settlement_provi
intangible_assets
salaries_payable
derivative_assets
good_will
minority_interests
deposit
deposits_received
seat_costs
insurance_receivables
bought_sellback_assets
unearned_premium_reserve
total_current_assets
other_current_assets
development_expenditure
contract_liability
receivable_life_r
constru_in_process
refundable_deposit
borrowing_from_centralbank
fixed_assets
notes_payable
life_insurance_reserve
interest_payable
estimate_liability
total_non_current_liability
accounts_payable
other_non_current_liability
longterm_equity_invest
paidin_capital
bill_receivable
company_type
total_assets
long_defer_income
insurer_impawn_loan
investment_property
derivative_liability
deferred_tax_assets
proxy_secu_proceeds
longterm_account_payable
fixed_deposit
deferred_tax_liability
advance_payment
total_fixed_asset
biological_assets

2. 营运能力指标.csv

字段名
accounts_payables_turnover_rate
accounts_receivables_turnover_days
current_assets_turnover_rate
fixed_asset_turnover_rate
publ_date
equity_turnover_rate
accounts_payables_turnover_days
oper_cycle
accounts_receivables_turnover_rate
secu_abbr
total_asset_turnover_rate
inventory_turnover_days
inventory_turnover_rate

3. 盈利能力指标.csv

字段名
t_operating_cost_to_tor_ttm
publ_date
roa
operating_profit_to_tor
secu_abbr
net_profit_ratio_ttm
roe_ttm
operating_expense_rate_ttm
net_profit_cut
np_to_tor
sales_cost_ratio
net_profit_ratio
ebit_to_tor_ttm
financial_expense_rate
roe_weighted
roe_avg
gross_income_ratio
asset_impa_loss_to_tor_ttm
operating_profit_to_tor_ttm
period_costs_rate_ttm
gross_income_ratio_ttm
np_to_tor_ttm
roe_cut
ebitda
admini_expense_rate_ttm
roa_ttm
financial_expense_rate_ttm
ebit
operating_profit_ratio
admini_expense_rate
roic
ebit_to_tor
net_profit
operating_expense_rate
t_operating_cost_to_tor
period_costs_rate
roe_cut_weighted
roa_ebit_ttm
roa_ebit
roe
total_profit_cost_ratio
asset_impa_loss_to_tor

4. 现金流量表.csv

字段名
cash_from_bonds_issue
subtotal_operate_cash_outflow
other_cash_from_invest_act
net_operate_cash_flow
net_insurer_deposit_investment
policy_dividend_cash_paid
fix_intan_other_asset_acqui_cash
original_compensation_paid
interest_and_commission_cashin
net_borrowing_from_central_bank
fix_intanther_asset_dispo_loss
net_cash_for_reinsurance
cash_equivalents_at_beginning
cash_at_beginning_of_year
net_borrowing_from_finance_co
net_deposit_in_cb_and_ib
staff_behalf_paid
cash_from_invest
dividend_interest_payment
others
net_deal_trading_assets
inventory_decrease
subtotal_finance_cash_outflow
commission_cash_paid
subtotal_invest_cash_outflow
cash_equivalents_at_end_of_year
net_incr_in_cash_and_equivalents
net_profit
net_operate_cash_flow_notes
operate_receivable_decrease
minority_profit
net_loan_and_advance_increase
financial_expense
fixed_asset_depreciation
operate_payable_increase
net_cash_deal_sub_company
net_lend_capital
intangible_asset_amortization
publ_date
defered_tax_liability_increase
invest_proceeds
begin_period_cash
defered_tax_asset_decrease
cash_equivalent_increase
invest_loss
secu_abbr
fix_intan_other_asset_dispo_cash
other_finance_act_payment
net_original_insurance_cash
net_cash_from_sub_company
fixed_asset_scrap_loss
net_deposit_increase
accrued_expense_added
net_invest_cash_flow
tax_levy_refund
goods_and_services_cash_paid
debt_to_captical
end_period_cash_equivalent
net_reinsurance_cash
other_cashin_related_operate
cbs_expiring_within_one_year
subtotal_invest_cash_inflow
other_operate_cash_paid
subtotal_finance_cash_inflow
assets_depreciation_reserves
subtotal_operate_cash_inflow
net_finance_cash_flow
invest_withdrawal_cash
net_buyback
goods_sale_service_render_cash
impawned_loan_net_increase
loss_from_fair_value_changes
company_type
cash_from_borrowing
other_finance_act_cash
cash_at_end_of_year
all_taxes_paid
borrowing_repayment
deferred_expense_amort
other_cash_to_invest_act
invest_cash_paid
exchan_rate_change_effect
deferred_expense_decreased
fixed_assets_finance_leases

5. 每股指标.csv

字段名
publ_date
oper_profit_ps
undivided_profit
enterprise_fcf_ps
shareholder_fcf_ps
secu_abbr
eps_ttm
retained_earnings_ps
diluted_eps
ebitps
basic_eps
surplus_reserve_fund_ps
eps
accumulation_fund_ps
capital_surplus_fund_ps
total_operating_revenue_ps
naps
cash_flow_ps
operating_revenue_ps_ttm
net_operate_cash_flow_ps
cash_flow_ps_ttm
main_income_ps
net_operate_cash_flow_ps_ttm

6. 利润表.csv

字段名
fair_value_change_income
publ_date
administration_expense
reinsurance_income
insurance_commission_expense
net_commission_income
operating_profit
operating_expense
secu_abbr
income_tax_cost
net_trust_income
basic_eps
reinsurance
ci_parent_company_owners
total_composite_income
non_operating_expense
unearned_premium_reserve
compensation_expense
amortization_reinsurance_cost
interest_income
ci_minority_owners
np_parent_company_owners
reinsurance_cost
exchange_income
total_profit
premium_reserve
asset_impairment_loss
commission_income
operating_payout
invest_income
r_and_d
total_operating_revenue
other_operating_cost
other_operating_revenue
premiums_income
policy_dividend_payout
total_operating_cost
net_proxy_secu_income
net_subissue_secu_income
diluted_eps
premiums_earned
non_current_assetss_deal_loss
net_profit
company_type
operating_revenue
operating_cost
invest_income_associates
minority_profit
refunded_premiums
amortization_premium_reserve
financial_expense
non_operating_income
commission_expense
other_net_revenue
amortization_expense
net_interest_income
interest_expense
operating_tax_surcharges

7. 成长能力指标.csv

字段名
publ_date
oper_cash_ps_grow_rate
diluted_eps_yoy
se_without_mi_grow_rate_ytd
total_profit_grow_rate
secu_abbr
net_asset_grow_rate
oper_profit_grow_rate
net_profit_grow_rate
net_operate_cash_flow_yoy
avg_np_yoy_past_five_year
sustainable_grow_rate
total_asset_grow_rate
operating_revenue_grow_rate
eps_grow_rate_ytd
np_parent_company_yoy
ta_grow_rate_ytd
np_parent_company_cut_yoy
naor_yoy
basic_eps_yoy

8. 偿债能力指标.csv

字段名
sewmi_to_total_liability
quick_ratio
publ_date
tangible_a_to_net_debt
interest_cover
nocf_to_interest_bear_debt
super_quick_ratio
secu_abbr
debt_equity_ratio
long_debt_to_working_capital
sewmi_to_interest_bear_debt
nocf_to_t_liability
nocf_to_net_debt
nocf_to_current_liability
current_ratio
debt_tangible_equity_ratio
opercashinto_current_debt
ebitda_to_t_liability
tangible_a_to_interest_bear_debt

各类代码教程与视频演示放于宽客堂量化平台https://quantkt.com

现阶段渠道开户和量化QMT/PTrade福利(万0.8,etf万0.5)解锁平台会员,获取量化系统教程与各类量化框架

量化学习交流群和相关教程联系平台管理员quantkt获取