第5章 财务报表分析
5.1 财务报表概述
5.1.1 财务报表的组成
"""
财务报表组成结构
- 使用Python类实现财务报表基础结构
- 包含主要报表类型及其基本属性
代码说明:
1. FinancialStatement类封装了企业财务报表的主要组成部分
2. 包含五个核心属性:
- balance_sheet: 资产负债表,记录企业资产、负债和所有者权益
- income_statement: 利润表,反映企业经营成果
- cash_flow: 现金流量表,展示企业现金流动情况
- equity_change: 所有者权益变动表,记录权益变动
- notes: 财务报表附注,提供补充说明
3. 使用字典数据结构存储各项数据,便于扩展和访问
4. validate()方法用于验证报表完整性,确保包含必要报表
"""
class FinancialStatement :
def __init__ ( self) :
self. balance_sheet = { }
self. income_statement = { }
self. cash_flow = { }
self. equity_change = { }
self. notes = { }
def validate ( self) :
"""验证财务报表完整性
代码说明:
1. 定义required列表,包含必须的三大报表
2. 使用getattr()动态获取对象属性
3. all()函数确保所有必须报表都存在
4. 返回布尔值,True表示报表完整,False表示缺失
"""
required = [ 'balance_sheet' , 'income_statement' , 'cash_flow' ]
return all ( getattr ( self, attr) for attr in required)
"""
代码说明:
1. 实例化FinancialStatement对象
2. 填充资产负债表数据:
- 资产:500万
- 负债:200万
- 所有者权益:300万
3. 填充利润表数据:
- 收入:100万
- 成本:60万
- 利润:40万
4. 调用validate()方法验证报表完整性
5. 打印验证结果
"""
fs = FinancialStatement( )
fs. balance_sheet = {
'资产' : 5000000 ,
'负债' : 2000000 ,
'所有者权益' : 3000000
}
fs. income_statement = {
'收入' : 1000000 ,
'成本' : 600000 ,
'利润' : 400000
}
print ( "财务报表验证结果:" , fs. validate( ) )
5.1.2 财务报表的编制原则
"""
财务报表编制原则检查
- 实现财务报表质量检查功能
- 验证四大基本原则
"""
class FinancialStatementValidator :
def __init__ ( self, statement) :
self. statement = statement
def check_authenticity ( self) :
"""真实性检查"""
return self. statement[ 'assets' ] > 0 and self. statement[ 'liabilities' ] >= 0
def check_completeness ( self) :
"""完整性检查"""
required_fields = [ 'assets' , 'liabilities' , 'equity' , 'revenue' , 'expenses' ]
return all ( field in self. statement for field in required_fields)
def check_timeliness ( self, report_date) :
"""及时性检查"""
from datetime import datetime
return ( datetime. now( ) - report_date) . days <= 90
def check_comparability ( self, prev_statement) :
"""可比性检查"""
return all ( k in prev_statement for k in self. statement. keys( ) )
statement = {
'assets' : 5000000 ,
'liabilities' : 2000000 ,
'equity' : 3000000 ,
'revenue' : 1000000 ,
'expenses' : 600000
}
validator = FinancialStatementValidator( statement)
print ( "真实性检查:" , validator. check_authenticity( ) )
print ( "完整性检查:" , validator. check_completeness( ) )
5.2 财务报表分析方法
5.2.1 水平分析法
"""
水平分析实现
- 同比分析:与去年同期比较
- 环比分析:与上期比较
- 趋势分析:多期数据趋势
"""
import pandas as pd
class HorizontalAnalysis :
def __init__ ( self, data) :
self. data = pd. DataFrame( data)
def yoy_analysis ( self) :
"""同比分析"""
return self. data. pct_change( periods= 4 )
def mom_analysis ( self) :
"""环比分析"""
return self. data. pct_change( )
def trend_analysis ( self, window= 4 ) :
"""趋势分析"""
return self. data. rolling( window= window) . mean( )
data = {
'2023-Q1' : [ 100 , 120 , 150 ] ,
'2023-Q2' : [ 110 , 130 , 160 ] ,
'2023-Q3' : [ 120 , 140 , 170 ] ,
'2023-Q4' : [ 130 , 150 , 180 ] ,
'2024-Q1' : [ 140 , 160 , 190 ]
}
ha = HorizontalAnalysis( data)
print ( "同比分析结果:\n" , ha. yoy_analysis( ) )
print ( "环比分析结果:\n" , ha. mom_analysis( ) )
print ( "趋势分析结果:\n" , ha. trend_analysis( ) )
5.2.2 垂直分析法
"""
垂直分析实现
- 结构分析:各项目占总体的比例
- 比例分析:关键项目之间的比例关系
"""
class VerticalAnalysis :
def __init__ ( self, balance_sheet) :
self. balance_sheet = balance_sheet
def structure_analysis ( self) :
"""结构分析"""
total_assets = self. balance_sheet[ 'total_assets' ]
return { k: v/ total_assets for k, v in self. balance_sheet. items( ) }
def ratio_analysis ( self) :
"""比例分析"""
return {
'current_ratio' : self. balance_sheet[ 'current_assets' ] / self. balance_sheet[ 'current_liabilities' ] ,
'debt_to_equity' : self. balance_sheet[ 'total_liabilities' ] / self. balance_sheet[ 'equity' ]
}
balance_sheet = {
'current_assets' : 800000 ,
'non_current_assets' : 1200000 ,
'current_liabilities' : 400000 ,
'non_current_liabilities' : 600000 ,
'equity' : 1000000 ,
'total_assets' : 2000000 ,
'total_liabilities' : 1000000
}
va = VerticalAnalysis( balance_sheet)
print ( "结构分析结果:\n" , va. structure_analysis( ) )
print ( "比例分析结果:\n" , va. ratio_analysis( ) )
5.2.3 比率分析法
5.3 资产负债表分析
5.3.1 资产结构分析
"""
资产结构分析实现
- 流动资产分析
- 非流动资产分析
- 资产质量评估
"""
class AssetAnalysis :
def __init__ ( self, assets) :
self. assets = assets
def current_assets_analysis ( self) :
"""流动资产分析"""
return {
'current_ratio' : self. assets[ 'current_assets' ] / self. assets[ 'current_liabilities' ] ,
'quick_ratio' : ( self. assets[ 'current_assets' ] - self. assets[ 'inventory' ] ) /
self. assets[ 'current_liabilities' ]
}
def non_current_assets_analysis ( self) :
"""非流动资产分析"""
return {
'fixed_assets_turnover' : self. assets[ 'revenue' ] / self. assets[ 'fixed_assets' ] ,
'depreciation_rate' : self. assets[ 'accumulated_depreciation' ] /
self. assets[ 'fixed_assets_original' ]
}
def asset_quality ( self) :
"""资产质量评估"""
return {
'receivables_turnover' : self. assets[ 'revenue' ] / self. assets[ 'accounts_receivable' ] ,
'inventory_turnover' : self. assets[ 'cost_of_goods_sold' ] / self. assets[ 'inventory' ]
}
assets = {
'current_assets' : 800000 ,
'current_liabilities' : 400000 ,
'inventory' : 200000 ,
'revenue' : 5000000 ,
'fixed_assets' : 1200000 ,
'accumulated_depreciation' : 300000 ,
'fixed_assets_original' : 1500000 ,
'accounts_receivable' : 600000 ,
'cost_of_goods_sold' : 3000000
}
analysis = AssetAnalysis( assets)
print ( "流动资产分析结果:\n" , analysis. current_assets_analysis( ) )
print ( "非流动资产分析结果:\n" , analysis. non_current_assets_analysis( ) )
print ( "资产质量评估结果:\n" , analysis. asset_quality( ) )
5.3.2 负债结构分析
"""
负债结构分析实现
- 流动负债分析
- 非流动负债分析
- 资本结构分析
"""
class LiabilityAnalysis :
def __init__ ( self, liabilities) :
self. liabilities = liabilities
def current_liabilities_analysis ( self) :
"""流动负债分析"""
return {
'current_ratio' : self. liabilities[ 'current_assets' ] / self. liabilities[ 'current_liabilities' ] ,
'quick_ratio' : ( self. liabilities[ 'current_assets' ] - self. liabilities[ 'inventory' ] ) /
self. liabilities[ 'current_liabilities' ]
}
def non_current_liabilities_analysis ( self) :
"""非流动负债分析"""
return {
'debt_to_equity' : self. liabilities[ 'total_liabilities' ] / self. liabilities[ 'equity' ] ,
'interest_coverage' : self. liabilities[ 'ebit' ] / self. liabilities[ 'interest_expense' ]
}
def capital_structure ( self) :
"""资本结构分析"""
total_capital = self. liabilities[ 'total_liabilities' ] + self. liabilities[ 'equity' ]
return {
'debt_ratio' : self. liabilities[ 'total_liabilities' ] / total_capital,
'equity_ratio' : self. liabilities[ 'equity' ] / total_capital
}
liabilities = {
'current_assets' : 800000 ,
'current_liabilities' : 400000 ,
'inventory' : 200000 ,
'total_liabilities' : 1000000 ,
'equity' : 1500000 ,
'ebit' : 500000 ,
'interest_expense' : 50000
}
analysis = LiabilityAnalysis( liabilities)
print ( "流动负债分析结果:\n" , analysis. current_liabilities_analysis( ) )
print ( "非流动负债分析结果:\n" , analysis. non_current_liabilities_analysis( ) )
print ( "资本结构分析结果:\n" , analysis. capital_structure( ) )
5.3.3 所有者权益分析
"""
所有者权益分析实现
- 实收资本分析
- 资本公积分析
- 留存收益分析
"""
class EquityAnalysis :
def __init__ ( self, equity) :
self. equity = equity
def paid_in_capital_analysis ( self) :
"""实收资本分析"""
return {
'capital_adequacy_ratio' : self. equity[ 'total_equity' ] / self. equity[ 'risk_weighted_assets' ] ,
'capital_growth_rate' : ( self. equity[ 'current_paid_in_capital' ] -
self. equity[ 'previous_paid_in_capital' ] ) /
self. equity[ 'previous_paid_in_capital' ]
}
def capital_reserve_analysis ( self) :
"""资本公积分析"""
return {
'reserve_ratio' : self. equity[ 'capital_reserve' ] / self. equity[ 'total_equity' ] ,
'reserve_growth' : ( self. equity[ 'current_reserve' ] - self. equity[ 'previous_reserve' ] ) /
self. equity[ 'previous_reserve' ]
}
def retained_earnings_analysis ( self) :
"""留存收益分析"""
return {
'retention_ratio' : self. equity[ 'retained_earnings' ] / self. equity[ 'net_income' ] ,
'dividend_payout_ratio' : self. equity[ 'dividends' ] / self. equity[ 'net_income' ]
}
equity = {
'total_equity' : 2000000 ,
'risk_weighted_assets' : 5000000 ,
'current_paid_in_capital' : 1500000 ,
'previous_paid_in_capital' : 1400000 ,
'capital_reserve' : 300000 ,
'current_reserve' : 320000 ,
'previous_reserve' : 300000 ,
'retained_earnings' : 800000 ,
'net_income' : 1000000 ,
'dividends' : 200000
}
analysis = EquityAnalysis( equity)
print ( "实收资本分析结果:\n" , analysis. paid_in_capital_analysis( ) )
print ( "资本公积分析结果:\n" , analysis. capital_reserve_analysis( ) )
print ( "留存收益分析结果:\n" , analysis. retained_earnings_analysis( ) )
5.4 利润表分析
5.4.1 收入分析
"""
收入分析实现
- 主营业务收入分析
- 其他业务收入分析
- 收入增长分析
"""
class RevenueAnalysis :
def __init__ ( self, revenue_data) :
self. revenue_data = revenue_data
def main_business_analysis ( self) :
"""主营业务收入分析"""
return {
'main_business_ratio' : self. revenue_data[ 'main_business' ] / self. revenue_data[ 'total_revenue' ] ,
'main_business_growth' : ( self. revenue_data[ 'current_main' ] - self. revenue_data[ 'previous_main' ] ) /
self. revenue_data[ 'previous_main' ]
}
def other_business_analysis ( self) :
"""其他业务收入分析"""
return {
'other_business_ratio' : self. revenue_data[ 'other_business' ] / self. revenue_data[ 'total_revenue' ] ,
'other_business_growth' : ( self. revenue_data[ 'current_other' ] - self. revenue_data[ 'previous_other' ] ) /
self. revenue_data[ 'previous_other' ]
}
def revenue_growth_analysis ( self) :
"""收入增长分析"""
return {
'total_growth' : ( self. revenue_data[ 'current_total' ] - self. revenue_data[ 'previous_total' ] ) /
self. revenue_data[ 'previous_total' ] ,
'compound_growth' : ( self. revenue_data[ 'current_total' ] / self. revenue_data[ 'previous_total' ] ) ** ( 1 / 3 ) - 1
}
revenue_data = {
'main_business' : 8000000 ,
'total_revenue' : 10000000 ,
'current_main' : 8500000 ,
'previous_main' : 8000000 ,
'other_business' : 2000000 ,
'current_other' : 2200000 ,
'previous_other' : 2000000 ,
'current_total' : 10700000 ,
'previous_total' : 10000000
}
analysis = RevenueAnalysis( revenue_data)
print ( "主营业务收入分析结果:\n" , analysis. main_business_analysis( ) )
print ( "其他业务收入分析结果:\n" , analysis. other_business_analysis( ) )
print ( "收入增长分析结果:\n" , analysis. revenue_growth_analysis( ) )
5.4.2 成本费用分析
"""
成本费用分析实现
- 主营业务成本分析
- 期间费用分析
- 成本控制分析
"""
class CostAnalysis :
def __init__ ( self, cost_data) :
self. cost_data = cost_data
def main_cost_analysis ( self) :
"""主营业务成本分析"""
return {
'cost_ratio' : self. cost_data[ 'main_cost' ] / self. cost_data[ 'main_revenue' ] ,
'cost_growth' : ( self. cost_data[ 'current_cost' ] - self. cost_data[ 'previous_cost' ] ) /
self. cost_data[ 'previous_cost' ]
}
def period_cost_analysis ( self) :
"""期间费用分析"""
return {
'selling_expense_ratio' : self. cost_data[ 'selling_expense' ] / self. cost_data[ 'revenue' ] ,
'admin_expense_ratio' : self. cost_data[ 'admin_expense' ] / self. cost_data[ 'revenue' ] ,
'financial_expense_ratio' : self. cost_data[ 'financial_expense' ] / self. cost_data[ 'revenue' ]
}
def cost_control_analysis ( self) :
"""成本控制分析"""
return {
'cost_reduction_rate' : ( self. cost_data[ 'previous_cost' ] - self. cost_data[ 'current_cost' ] ) /
self. cost_data[ 'previous_cost' ] ,
'cost_structure' : {
'material' : self. cost_data[ 'material_cost' ] / self. cost_data[ 'total_cost' ] ,
'labor' : self. cost_data[ 'labor_cost' ] / self. cost_data[ 'total_cost' ] ,
'overhead' : self. cost_data[ 'overhead_cost' ] / self. cost_data[ 'total_cost' ]
}
}
cost_data = {
'main_cost' : 6000000 ,
'main_revenue' : 8000000 ,
'current_cost' : 6200000 ,
'previous_cost' : 6000000 ,
'selling_expense' : 500000 ,
'admin_expense' : 300000 ,
'financial_expense' : 200000 ,
'revenue' : 10000000 ,
'material_cost' : 4000000 ,
'labor_cost' : 1500000 ,
'overhead_cost' : 500000 ,
'total_cost' : 6000000
}
analysis = CostAnalysis( cost_data)
print ( "主营业务成本分析结果:\n" , analysis. main_cost_analysis( ) )
print ( "期间费用分析结果:\n" , analysis. period_cost_analysis( ) )
print ( "成本控制分析结果:\n" , analysis. cost_control_analysis( ) )
5.4.3 盈利能力分析
"""
盈利能力分析实现
- 毛利率分析
- 净利率分析
- 每股收益分析
"""
class ProfitabilityAnalysis :
def __init__ ( self, profit_data) :
self. profit_data = profit_data
def gross_margin_analysis ( self) :
"""毛利率分析"""
gross_profit = self. profit_data[ 'revenue' ] - self. profit_data[ 'cost_of_goods_sold' ]
return {
'gross_margin' : gross_profit / self. profit_data[ 'revenue' ] ,
'gross_margin_growth' : ( gross_profit - self. profit_data[ 'previous_gross_profit' ] ) /
self. profit_data[ 'previous_gross_profit' ]
}
def net_margin_analysis ( self) :
"""净利率分析"""
return {
'net_margin' : self. profit_data[ 'net_income' ] / self. profit_data[ 'revenue' ] ,
'net_margin_growth' : ( self. profit_data[ 'current_net_income' ] -
self. profit_data[ 'previous_net_income' ] ) /
self. profit_data[ 'previous_net_income' ]
}
def eps_analysis ( self) :
"""每股收益分析"""
return {
'basic_eps' : self. profit_data[ 'net_income' ] / self. profit_data[ 'shares_outstanding' ] ,
'diluted_eps' : self. profit_data[ 'net_income' ] /
( self. profit_data[ 'shares_outstanding' ] + self. profit_data[ 'potential_shares' ] )
}
profit_data = {
'revenue' : 10000000 ,
'cost_of_goods_sold' : 6000000 ,
'previous_gross_profit' : 3800000 ,
'net_income' : 2000000 ,
'current_net_income' : 2200000 ,
'previous_net_income' : 2000000 ,
'shares_outstanding' : 1000000 ,
'potential_shares' : 200000
}
analysis = ProfitabilityAnalysis( profit_data)
print ( "毛利率分析结果:\n" , analysis. gross_margin_analysis( ) )
print ( "净利率分析结果:\n" , analysis. net_margin_analysis( ) )
print ( "每股收益分析结果:\n" , analysis. eps_analysis( ) )
5.5 现金流量表分析
5.5.1 经营活动现金流分析
"""
经营活动现金流分析实现
- 现金流入分析
- 现金流出分析
- 净现金流分析
"""
class OperatingCashFlowAnalysis :
def __init__ ( self, cash_flow_data) :
self. cash_flow_data = cash_flow_data
def cash_inflow_analysis ( self) :
"""现金流入分析"""
return {
'receivables_turnover' : self. cash_flow_data[ 'sales' ] / self. cash_flow_data[ 'accounts_receivable' ] ,
'cash_inflow_ratio' : self. cash_flow_data[ 'cash_inflow' ] / self. cash_flow_data[ 'total_revenue' ]
}
def cash_outflow_analysis ( self) :
"""现金流出分析"""
return {
'payables_turnover' : self. cash_flow_data[ 'cost_of_goods_sold' ] / self. cash_flow_data[ 'accounts_payable' ] ,
'cash_outflow_ratio' : self. cash_flow_data[ 'cash_outflow' ] / self. cash_flow_data[ 'total_expenses' ]
}
def net_cash_flow_analysis ( self) :
"""净现金流分析"""
return {
'net_cash_flow' : self. cash_flow_data[ 'cash_inflow' ] - self. cash_flow_data[ 'cash_outflow' ] ,
'cash_flow_margin' : ( self. cash_flow_data[ 'cash_inflow' ] - self. cash_flow_data[ 'cash_outflow' ] ) /
self. cash_flow_data[ 'cash_inflow' ]
}
cash_flow_data = {
'sales' : 10000000 ,
'accounts_receivable' : 1500000 ,
'cash_inflow' : 9500000 ,
'total_revenue' : 10000000 ,
'cost_of_goods_sold' : 6000000 ,
'accounts_payable' : 1200000 ,
'cash_outflow' : 8500000 ,
'total_expenses' : 9000000
}
analysis = OperatingCashFlowAnalysis( cash_flow_data)
print ( "现金流入分析结果:\n" , analysis. cash_inflow_analysis( ) )
print ( "现金流出分析结果:\n" , analysis. cash_outflow_analysis( ) )
print ( "净现金流分析结果:\n" , analysis. net_cash_flow_analysis( ) )
5.5.2 投资活动现金流分析
"""
投资活动现金流分析实现
- 投资支出分析
- 投资收益分析
"""
class InvestingCashFlowAnalysis :
def __init__ ( self, investing_data) :
self. investing_data = investing_data
def investment_expenditure_analysis ( self) :
"""投资支出分析"""
return {
'capex_ratio' : self. investing_data[ 'capital_expenditure' ] / self. investing_data[ 'total_assets' ] ,
'investment_intensity' : self. investing_data[ 'capital_expenditure' ] /
self. investing_data[ 'operating_cash_flow' ]
}
def investment_return_analysis ( self) :
"""投资收益分析"""
return {
'roi' : self. investing_data[ 'investment_income' ] / self. investing_data[ 'total_investment' ] ,
'payback_period' : self. investing_data[ 'total_investment' ] /
self. investing_data[ 'annual_cash_flow' ]
}
investing_data = {
'capital_expenditure' : 2000000 ,
'total_assets' : 10000000 ,
'operating_cash_flow' : 5000000 ,
'investment_income' : 800000 ,
'total_investment' : 5000000 ,
'annual_cash_flow' : 1200000
}
analysis = InvestingCashFlowAnalysis( investing_data)
print ( "投资支出分析结果:\n" , analysis. investment_expenditure_analysis( ) )
print ( "投资收益分析结果:\n" , analysis. investment_return_analysis( ) )
5.5.3 筹资活动现金流分析
"""
筹资活动现金流分析实现
- 筹资方式分析
- 筹资成本分析
"""
class FinancingCashFlowAnalysis :
def __init__ ( self, financing_data) :
self. financing_data = financing_data
def financing_method_analysis ( self) :
"""筹资方式分析"""
return {
'debt_ratio' : self. financing_data[ 'debt_financing' ] / self. financing_data[ 'total_financing' ] ,
'equity_ratio' : self. financing_data[ 'equity_financing' ] / self. financing_data[ 'total_financing' ]
}
def financing_cost_analysis ( self) :
"""筹资成本分析"""
return {
'cost_of_debt' : self. financing_data[ 'interest_expense' ] / self. financing_data[ 'total_debt' ] ,
'cost_of_equity' : self. financing_data[ 'dividends' ] / self. financing_data[ 'equity' ]
}
financing_data = {
'debt_financing' : 3000000 ,
'total_financing' : 5000000 ,
'equity_financing' : 2000000 ,
'interest_expense' : 150000 ,
'total_debt' : 3000000 ,
'dividends' : 200000 ,
'equity' : 5000000
}
analysis = FinancingCashFlowAnalysis( financing_data)
print ( "筹资方式分析结果:\n" , analysis. financing_method_analysis( ) )
print ( "筹资成本分析结果:\n" , analysis. financing_cost_analysis( ) )
5.6 综合财务分析
5.6.1 杜邦分析法
"""
杜邦分析实现
- 净资产收益率分解
- 财务杠杆分析
- 经营效率分析
"""
class DuPontAnalysis :
def __init__ ( self, financial_data) :
self. financial_data = financial_data
def roe_decomposition ( self) :
"""净资产收益率分解"""
net_profit_margin = self. financial_data[ 'net_income' ] / self. financial_data[ 'revenue' ]
asset_turnover = self. financial_data[ 'revenue' ] / self. financial_data[ 'total_assets' ]
equity_multiplier = self. financial_data[ 'total_assets' ] / self. financial_data[ 'equity' ]
return {
'roe' : net_profit_margin * asset_turnover * equity_multiplier,
'net_profit_margin' : net_profit_margin,
'asset_turnover' : asset_turnover,
'equity_multiplier' : equity_multiplier
}
def financial_leverage_analysis ( self) :
"""财务杠杆分析"""
return {
'debt_to_equity' : self. financial_data[ 'total_liabilities' ] / self. financial_data[ 'equity' ] ,
'interest_coverage' : self. financial_data[ 'ebit' ] / self. financial_data[ 'interest_expense' ]
}
def operating_efficiency_analysis ( self) :
"""经营效率分析"""
return {
'inventory_turnover' : self. financial_data[ 'cost_of_goods_sold' ] / self. financial_data[ 'inventory' ] ,
'receivables_turnover' : self. financial_data[ 'revenue' ] / self. financial_data[ 'accounts_receivable' ]
}
financial_data = {
'net_income' : 2000000 ,
'revenue' : 10000000 ,
'total_assets' : 15000000 ,
'equity' : 8000000 ,
'total_liabilities' : 7000000 ,
'ebit' : 3000000 ,
'interest_expense' : 150000 ,
'cost_of_goods_sold' : 6000000 ,
'inventory' : 1500000 ,
'accounts_receivable' : 1200000
}
analysis = DuPontAnalysis( financial_data)
print ( "杜邦分析结果:\n" , analysis. roe_decomposition( ) )
print ( "财务杠杆分析结果:\n" , analysis. financial_leverage_analysis( ) )
print ( "经营效率分析结果:\n" , analysis. operating_efficiency_analysis( ) )
5.6.2 财务预警分析
"""
财务预警分析实现
- Z-score模型
- F分数模型
- 财务风险预警
"""
class FinancialEarlyWarning :
def __init__ ( self, financial_data) :
self. financial_data = financial_data
def z_score_model ( self) :
"""Z-score模型"""
working_capital = self. financial_data[ 'current_assets' ] - self. financial_data[ 'current_liabilities' ]
retained_earnings = self. financial_data[ 'retained_earnings' ]
ebit = self. financial_data[ 'ebit' ]
market_value = self. financial_data[ 'market_value' ]
total_liabilities = self. financial_data[ 'total_liabilities' ]
sales = self. financial_data[ 'sales' ]
total_assets = self. financial_data[ 'total_assets' ]
z_score = 1.2 * ( working_capital/ total_assets) + \
1.4 * ( retained_earnings/ total_assets) + \
3.3 * ( ebit/ total_assets) + \
0.6 * ( market_value/ total_liabilities) + \
1.0 * ( sales/ total_assets)
return z_score
def f_score_model ( self) :
"""F分数模型"""
roa = self. financial_data[ 'net_income' ] / self. financial_data[ 'total_assets' ]
cash_flow = self. financial_data[ 'operating_cash_flow' ] / self. financial_data[ 'total_liabilities' ]
delta_roa = roa - self. financial_data[ 'previous_roa' ]
accruals = ( self. financial_data[ 'net_income' ] - self. financial_data[ 'operating_cash_flow' ] ) / \
self. financial_data[ 'total_assets' ]
delta_leverage = ( self. financial_data[ 'total_liabilities' ] / self. financial_data[ 'total_assets' ] ) - \
( self. financial_data[ 'previous_liabilities' ] / self. financial_data[ 'previous_assets' ] )
delta_liquidity = ( self. financial_data[ 'current_assets' ] / self. financial_data[ 'current_liabilities' ] ) - \
( self. financial_data[ 'previous_current_assets' ] / self. financial_data[ 'previous_current_liabilities' ] )
delta_margin = ( self. financial_data[ 'gross_margin' ] / self. financial_data[ 'sales' ] ) - \
( self. financial_data[ 'previous_gross_margin' ] / self. financial_data[ 'previous_sales' ] )
f_score = - 0.1774 + 1.1091 * roa + 0.1074 * cash_flow + 1.9271 * delta_roa + \
0.0302 * accruals + 0.4961 * delta_leverage + 0.4961 * delta_liquidity + \
0.4961 * delta_margin
return f_score
def risk_warning ( self) :
"""财务风险预警"""
z_score = self. z_score_model( )
f_score = self. f_score_model( )
return {
'z_score' : z_score,
'f_score' : f_score,
'z_warning' : '安全' if z_score > 2.99 else ( '需要关注' if 1.81 < z_score <= 2.99 else '危险' ) ,
'f_warning' : '安全' if f_score > 0.5 else '危险'
}
financial_data = {
'current_assets' : 8000000 ,
'current_liabilities' : 4000000 ,
'retained_earnings' : 3000000 ,
'ebit' : 2000000 ,
'market_value' : 10000000 ,
'total_liabilities' : 6000000 ,
'sales' : 15000000 ,
'total_assets' : 20000000 ,
'net_income' : 1200000 ,
'operating_cash_flow' : 1500000 ,
'previous_roa' : 0.05 ,
'previous_liabilities' : 5500000 ,
'previous_assets' : 18000000 ,
'previous_current_assets' : 7500000 ,
'previous_current_liabilities' : 3800000 ,
'gross_margin' : 5000000 ,
'previous_gross_margin' : 4500000 ,
'previous_sales' : 14000000
}
analysis = FinancialEarlyWarning( financial_data)
print ( "财务预警分析结果:\n" , analysis. risk_warning( ) )
5.7 财务报表分析案例
5.7.1 上市公司财务报表分析
"""
上市公司财务报表分析案例
- 案例背景
- 分析方法
- 分析结论
"""
class PublicCompanyAnalysis :
def __init__ ( self, company_data) :
self. company_data = company_data
def case_background ( self) :
"""案例背景"""
return {
'company_name' : self. company_data[ 'name' ] ,
'industry' : self. company_data[ 'industry' ] ,
'market_cap' : self. company_data[ 'market_cap' ] ,
'revenue' : self. company_data[ 'revenue' ]
}
def analysis_methods ( self) :
"""分析方法"""
return {
'ratio_analysis' : True ,
'trend_analysis' : True ,
'benchmarking' : True ,
'duPont_analysis' : True
}
def analysis_conclusion ( self) :
"""分析结论"""
return {
'profitability' : '良好' if self. company_data[ 'net_margin' ] > 0.1 else '一般' ,
'liquidity' : '充足' if self. company_data[ 'current_ratio' ] > 2 else '不足' ,
'solvency' : '安全' if self. company_data[ 'debt_to_equity' ] < 1 else '有风险' ,
'growth' : '强劲' if self. company_data[ 'revenue_growth' ] > 0.2 else '平稳'
}
company_data = {
'name' : 'ABC股份有限公司' ,
'industry' : '制造业' ,
'market_cap' : 5000000000 ,
'revenue' : 1000000000 ,
'net_margin' : 0.12 ,
'current_ratio' : 2.5 ,
'debt_to_equity' : 0.8 ,
'revenue_growth' : 0.25
}
analysis = PublicCompanyAnalysis( company_data)
print ( "案例背景:\n" , analysis. case_background( ) )
print ( "分析方法:\n" , analysis. analysis_methods( ) )
print ( "分析结论:\n" , analysis. analysis_conclusion( ) )
5.7.2 中小企业财务报表分析
"""
中小企业财务报表分析案例
- 案例背景
- 分析方法
- 分析结论
"""
class SMEAnalysis :
def __init__ ( self, sme_data) :
self. sme_data = sme_data
def case_background ( self) :
"""案例背景"""
return {
'company_name' : self. sme_data[ 'name' ] ,
'industry' : self. sme_data[ 'industry' ] ,
'revenue' : self. sme_data[ 'revenue' ] ,
'employee_count' : self. sme_data[ 'employee_count' ]
}
def analysis_methods ( self) :
"""分析方法"""
return {
'cash_flow_analysis' : True ,
'break_even_analysis' : True ,
'working_capital_analysis' : True ,
'credit_risk_assessment' : True
}
def analysis_conclusion ( self) :
"""分析结论"""
return {
'profitability' : '良好' if self. sme_data[ 'net_margin' ] > 0.05 else '一般' ,
'liquidity' : '充足' if self. sme_data[ 'current_ratio' ] > 1.5 else '不足' ,
'solvency' : '安全' if self. sme_data[ 'debt_to_equity' ] < 1.5 else '有风险' ,
'growth' : '强劲' if self. sme_data[ 'revenue_growth' ] > 0.15 else '平稳'
}
sme_data = {
'name' : 'XYZ有限公司' ,
'industry' : '服务业' ,
'revenue' : 5000000 ,
'employee_count' : 50 ,
'net_margin' : 0.06 ,
'current_ratio' : 1.8 ,
'debt_to_equity' : 1.2 ,
'revenue_growth' : 0.18
}
analysis = SMEAnalysis( sme_data)
print ( "案例背景:\n" , analysis. case_background( ) )
print ( "分析方法:\n" , analysis. analysis_methods( ) )
print ( "分析结论: \n
- 案例背景
- 分析方法
- 分析结论
```python
"""
Excel财务分析自动化实现
- 使用Python自动化Excel操作
- 包含数据透视表、财务函数、图表分析等功能
"""
import pandas as pd
import openpyxl
from openpyxl. chart import BarChart, Reference
class ExcelFinancialAnalysis :
def __init__ ( self, file_path) :
self. file_path = file_path
self. wb = openpyxl. Workbook( )
self. ws = self. wb. active
def create_pivot_table ( self, data) :
"""创建数据透视表"""
df = pd. DataFrame( data)
pivot = pd. pivot_table( df, values= '金额' , index= '项目' ,
columns= '期间' , aggfunc= 'sum' )
for r in dataframe_to_rows( pivot, index= True , header= True ) :
self. ws. append( r)
def apply_financial_functions ( self) :
"""应用财务函数"""
self. ws[ 'B10' ] = '净现值(NPV):'
self. ws[ 'C10' ] = '=NPV(0.1, C2:C8)'
self. ws[ 'B11' ] = '内部收益率(IRR):'
self. ws[ 'C11' ] = '=IRR(C2:C8)'
self. ws[ 'B12' ] = '投资回收期:'
self. ws[ 'C12' ] = '=NPER(0.1, -100000, 500000)'
def create_charts ( self) :
"""创建图表"""
chart = BarChart( )
data = Reference( self. ws, min_col= 2 , min_row= 1 , max_col= 5 , max_row= 8 )
cats = Reference( self. ws, min_col= 1 , min_row= 2 , max_row= 8 )
chart. add_data( data, titles_from_data= True )
chart. set_categories( cats)
self. ws. add_chart( chart, "A15" )
def save ( self) :
"""保存文件"""
self. wb. save( self. file_path)
data = {
'项目' : [ '收入' , '成本' , '利润' , '税费' , '净利润' ] ,
'2023-Q1' : [ 1000000 , 600000 , 400000 , 100000 , 300000 ] ,
'2023-Q2' : [ 1200000 , 700000 , 500000 , 120000 , 380000 ] ,
'2023-Q3' : [ 1500000 , 900000 , 600000 , 150000 , 450000 ]
}
excel_analysis = ExcelFinancialAnalysis( 'financial_analysis.xlsx' )
excel_analysis. create_pivot_table( data)
excel_analysis. apply_financial_functions( )
excel_analysis. create_charts( )
excel_analysis. save( )
5.8.2 Python在财务分析中的应用
"""
Python财务分析综合应用
- 财务报表分析
- 财务预测
- 风险管理
"""
import pandas as pd
import numpy as np
from sklearn. linear_model import LinearRegression
from scipy. stats import norm
class FinancialAnalysis :
def __init__ ( self, financial_data) :
self. data = pd. DataFrame( financial_data)
def financial_statement_analysis ( self) :
"""财务报表分析"""
return {
'current_ratio' : self. data[ 'current_assets' ] . sum ( ) / self. data[ 'current_liabilities' ] . sum ( ) ,
'debt_to_equity' : self. data[ 'total_liabilities' ] . sum ( ) / self. data[ 'equity' ] . sum ( ) ,
'net_profit_margin' : self. data[ 'net_income' ] . sum ( ) / self. data[ 'revenue' ] . sum ( )
}
def financial_forecasting ( self) :
"""财务预测"""
X = np. array( range ( len ( self. data) ) ) . reshape( - 1 , 1 )
y = self. data[ 'revenue' ] . values
model = LinearRegression( )
model. fit( X, y)
forecast = model. predict( np. array( [ [ len ( self. data) + 1 ] ] ) )
return forecast[ 0 ]
def risk_management ( self) :
"""风险管理"""
returns = self. data[ 'revenue' ] . pct_change( ) . dropna( )
var_95 = norm. ppf( 0.05 , returns. mean( ) , returns. std( ) )
return {
'average_return' : returns. mean( ) ,
'volatility' : returns. std( ) ,
'var_95' : var_95
}
financial_data = {
'period' : [ '2023-Q1' , '2023-Q2' , '2023-Q3' ] ,
'revenue' : [ 1000000 , 1200000 , 1500000 ] ,
'current_assets' : [ 800000 , 850000 , 900000 ] ,
'current_liabilities' : [ 400000 , 420000 , 450000 ] ,
'total_liabilities' : [ 600000 , 620000 , 650000 ] ,
'equity' : [ 1000000 , 1100000 , 1200000 ] ,
'net_income' : [ 200000 , 250000 , 300000 ]
}
analysis = FinancialAnalysis( financial_data)
print ( "财务报表分析结果:\n" , analysis. financial_statement_analysis( ) )
print ( "财务预测结果:\n" , analysis. financial_forecasting( ) )
print ( "风险管理分析结果:\n" , analysis. risk_management( ) )
5.8.2.1 财务报表数据结构
import pandas as pd
"""
创建资产负债表数据结构
- 使用Pandas DataFrame存储资产负债表数据
- 包含主要项目:流动资产、非流动资产、流动负债、非流动负债、所有者权益
- 金额单位为元
"""
balance_sheet = pd. DataFrame( {
'项目' : [ '流动资产' , '非流动资产' , '流动负债' , '非流动负债' , '所有者权益' ] ,
'金额' : [ 1500000 , 2500000 , 800000 , 1200000 , 2000000 ]
} )
"""
创建利润表数据结构
- 使用Pandas DataFrame存储利润表数据
- 包含主要项目:营业收入、营业成本、营业利润、利润总额、净利润
- 金额单位为元
"""
income_statement = pd. DataFrame( {
'项目' : [ '营业收入' , '营业成本' , '营业利润' , '利润总额' , '净利润' ] ,
'金额' : [ 5000000 , 3000000 , 1500000 , 1400000 , 1000000 ]
} )
print ( "资产负债表示例:" )
print ( balance_sheet)
print ( "\n利润表示例:" )
print ( income_statement)
5.8.2.2 财务比率计算
"""
流动比率计算
- 公式:流动比率 = 流动资产 / 流动负债
- 衡量企业短期偿债能力
- 通常认为2:1的流动比率较为理想
"""
current_ratio = balance_sheet. loc[ 0 , '金额' ] / balance_sheet. loc[ 2 , '金额' ]
print ( f"流动比率: { current_ratio: .2f } " )
"""
资产负债率计算
- 公式:资产负债率 = (流动负债 + 非流动负债)/ 总资产
- 反映企业财务杠杆水平
- 通常认为40%-60%较为合理
"""
debt_ratio = ( balance_sheet. loc[ 2 , '金额' ] + balance_sheet. loc[ 3 , '金额' ] ) / \
( balance_sheet. loc[ 0 , '金额' ] + balance_sheet. loc[ 1 , '金额' ] )
print ( f"资产负债率: { debt_ratio: .2% } " )
"""
净利润率计算
- 公式:净利润率 = 净利润 / 营业收入
- 反映企业盈利能力
- 行业平均值可作为参考基准
"""
net_profit_margin = income_statement. loc[ 4 , '金额' ] / income_statement. loc[ 0 , '金额' ]
print ( f"净利润率: { net_profit_margin: .2% } " )
5.8.2.3 财务数据可视化
import matplotlib. pyplot as plt
"""
资产负债表可视化
- 使用柱状图展示资产负债表各项目金额
- 设置图表大小、标题、标签等
- 自动调整x轴标签角度防止重叠
"""
plt. figure( figsize= ( 10 , 5 ) )
plt. bar( balance_sheet[ '项目' ] , balance_sheet[ '金额' ] , color= 'skyblue' )
plt. title( '资产负债表可视化' , fontsize= 14 )
plt. ylabel( '金额(元)' , fontsize= 12 )
plt. xlabel( '项目' , fontsize= 12 )
plt. xticks( rotation= 45 )
plt. grid( axis= 'y' , linestyle= '--' , alpha= 0.7 )
plt. show( )
"""
利润表可视化
- 使用折线图展示利润表各项目趋势
- 添加数据点标记
- 设置图表样式和格式
"""
plt. figure( figsize= ( 10 , 5 ) )
plt. plot( income_statement[ '项目' ] , income_statement[ '金额' ] ,
marker= 'o' , color= 'orange' , linewidth= 2 )
plt. title( '利润表趋势分析' , fontsize= 14 )
plt. ylabel( '金额(元)' , fontsize= 12 )
plt. xlabel( '项目' , fontsize= 12 )
plt. xticks( rotation= 45 )
plt. grid( linestyle= '--' , alpha= 0.7 )
plt. show( )
5.8.2.4 杜邦分析实现
"""
杜邦分析实现
- 公式:ROE = 净利润率 × 总资产周转率 × 权益乘数
- 分解企业盈利能力来源
- 帮助分析企业财务表现驱动因素
"""
asset_turnover = income_statement. loc[ 0 , '金额' ] / \
( balance_sheet. loc[ 0 , '金额' ] + balance_sheet. loc[ 1 , '金额' ] )
equity_multiplier = ( balance_sheet. loc[ 0 , '金额' ] + balance_sheet. loc[ 1 , '金额' ] ) / \
balance_sheet. loc[ 4 , '金额' ]
roe = net_profit_margin * asset_turnover * equity_multiplier
print ( f"净利润率: { net_profit_margin: .2% } " )
print ( f"总资产周转率: { asset_turnover: .2f } " )
print ( f"权益乘数: { equity_multiplier: .2f } " )
print ( f"净资产收益率(ROE): { roe: .2% } " )
5.8.2.5 财务预警模型
"""
Z-score模型计算
- 用于预测企业破产风险的模型
- 由Edward Altman开发
- 判断标准:
Z > 2.99:安全区
1.81 < Z < 2.99:灰色区
Z < 1.81:危险区
"""
working_capital = balance_sheet. loc[ 0 , '金额' ] - balance_sheet. loc[ 2 , '金额' ]
retained_earnings = balance_sheet. loc[ 4 , '金额' ]
ebit = income_statement. loc[ 2 , '金额' ]
market_value = 5000000
total_liabilities = balance_sheet. loc[ 2 , '金额' ] + balance_sheet. loc[ 3 , '金额' ]
sales = income_statement. loc[ 0 , '金额' ]
total_assets = balance_sheet. loc[ 0 , '金额' ] + balance_sheet. loc[ 1 , '金额' ]
z_score = 1.2 * ( working_capital/ total_assets) + \
1.4 * ( retained_earnings/ total_assets) + \
3.3 * ( ebit/ total_assets) + \
0.6 * ( market_value/ total_liabilities) + \
1.0 * ( sales/ total_assets)
print ( f"Z-score: { z_score: .2f } " )
if z_score > 2.99 :
print ( "财务状况:安全" )
elif 1.81 < z_score <= 2.99 :
print ( "财务状况:需要关注" )
else :
print ( "财务状况:危险" )
5.9 财务报表分析报告撰写
5.9.1 报告结构
"""
财务报表分析报告生成器
- 自动生成报告结构
- 包含摘要、分析内容、结论与建议
"""
from datetime import datetime
class FinancialReport :
def __init__ ( self, company_name) :
self. company_name = company_name
self. report = {
'header' : self. _generate_header( ) ,
'summary' : '' ,
'analysis' : { } ,
'conclusions' : [ ] ,
'recommendations' : [ ]
}
def _generate_header ( self) :
"""生成报告头"""
return {
'title' : f' { self. company_name} 财务报表分析报告' ,
'date' : datetime. now( ) . strftime( '%Y-%m-%d' ) ,
'author' : '财务分析系统'
}
def add_summary ( self, text) :
"""添加摘要"""
self. report[ 'summary' ] = text
def add_analysis ( self, section, content) :
"""添加分析内容"""
self. report[ 'analysis' ] [ section] = content
def add_conclusion ( self, conclusion) :
"""添加结论"""
self. report[ 'conclusions' ] . append( conclusion)
def add_recommendation ( self, recommendation) :
"""添加建议"""
self. report[ 'recommendations' ] . append( recommendation)
def generate_report ( self) :
"""生成完整报告"""
report_text = f"报告标题: { self. report[ 'header' ] [ 'title' ] } \n"
report_text += f"报告日期: { self. report[ 'header' ] [ 'date' ] } \n"
report_text += f"报告作者: { self. report[ 'header' ] [ 'author' ] } \n\n"
report_text += "摘要:\n" + self. report[ 'summary' ] + "\n\n"
report_text += "分析内容:\n"
for section, content in self. report[ 'analysis' ] . items( ) :
report_text += f" { section} :\n { content} \n"
report_text += "\n结论:\n"
for conclusion in self. report[ 'conclusions' ] :
report_text += f"- { conclusion} \n"
report_text += "\n建议:\n"
for recommendation in self. report[ 'recommendations' ] :
report_text += f"- { recommendation} \n"
return report_text
report = FinancialReport( 'ABC公司' )
report. add_summary( '本报告对ABC公司2023年财务状况进行了全面分析...' )
report. add_analysis( '盈利能力分析' , '公司净利润率保持在10%以上...' )
report. add_analysis( '偿债能力分析' , '流动比率维持在2.0左右...' )
report. add_conclusion( '公司财务状况总体健康' )
report. add_conclusion( '需要关注应收账款周转率下降的问题' )
report. add_recommendation( '加强应收账款管理' )
report. add_recommendation( '优化资本结构' )
print ( report. generate_report( ) )
5.9.2 报告注意事项
"""
财务报表分析报告质量检查
- 数据准确性验证
- 分析客观性评估
- 建议可行性分析
"""
class ReportQualityChecker :
def __init__ ( self, report) :
self. report = report
def check_data_accuracy ( self, source_data) :
"""数据准确性检查"""
errors = [ ]
for key, value in self. report[ 'data' ] . items( ) :
if value != source_data[ key] :
errors. append( f" { key} 数据不一致: 报告值 { value} , 源数据 { source_data[ key] } " )
return errors
def check_analysis_objectivity ( self) :
"""分析客观性评估"""
subjective_words = [ '非常' , '极其' , '绝对' , '肯定' ]
subjective_count = sum ( self. report[ 'analysis' ] . count( word) for word in subjective_words)
return subjective_count
def check_recommendation_feasibility ( self) :
"""建议可行性分析"""
feasibility_score = 0
for recommendation in self. report[ 'recommendations' ] :
if '加强' in recommendation or '优化' in recommendation:
feasibility_score += 1
elif '立即' in recommendation or '全面' in recommendation:
feasibility_score -= 1
return feasibility_score
report_data = {
'data' : {
'revenue' : 1000000 ,
'profit' : 200000
} ,
'analysis' : '公司业绩非常好,绝对领先于行业' ,
'recommendations' : [ '立即削减成本' , '优化产品结构' ]
}
source_data = {
'revenue' : 1000000 ,
'profit' : 250000
}
checker = ReportQualityChecker( report_data)
print ( "数据准确性检查结果:" , checker. check_data_accuracy( source_data) )
print ( "分析主观性评估结果:" , checker. check_analysis_objectivity( ) )
print ( "建议可行性评分:" , checker. check_recommendation_feasibility( ) )
5.10 财务报表分析发展趋势
5.10.1 大数据分析
"""
大数据财务分析实现
- 数据采集与清洗
- 数据挖掘与分析
- 智能决策支持
"""
import pandas as pd
from sklearn. cluster import KMeans
from sklearn. preprocessing import StandardScaler
class BigDataFinancialAnalysis :
def __init__ ( self, data) :
self. data = pd. DataFrame( data)
def data_cleaning ( self) :
"""数据清洗"""
self. data = self. data. dropna( )
self. data = self. data[ self. data[ 'revenue' ] > 0 ]
return self. data
def data_mining ( self) :
"""数据挖掘"""
scaler = StandardScaler( )
scaled_data = scaler. fit_transform( self. data[ [ 'revenue' , 'profit' ] ] )
kmeans = KMeans( n_clusters= 3 )
self. data[ 'cluster' ] = kmeans. fit_predict( scaled_data)
return self. data
def intelligent_analysis ( self) :
"""智能分析"""
cluster_analysis = self. data. groupby( 'cluster' ) . agg( {
'revenue' : [ 'mean' , 'std' ] ,
'profit' : [ 'mean' , 'std' ]
} )
return cluster_analysis
data = {
'company' : [ 'A' , 'B' , 'C' , 'D' , 'E' ] ,
'revenue' : [ 1000000 , 1200000 , 800000 , 1500000 , 900000 ] ,
'profit' : [ 200000 , 250000 , 150000 , 300000 , 180000 ]
}
analysis = BigDataFinancialAnalysis( data)
cleaned_data = analysis. data_cleaning( )
print ( "清洗后的数据:\n" , cleaned_data)
clustered_data = analysis. data_mining( )
print ( "聚类分析结果:\n" , clustered_data)
intelligent_analysis = analysis. intelligent_analysis( )
print ( "智能分析结果:\n" , intelligent_analysis)
5.10.2 人工智能应用
"""
AI财务分析实现
- 机器学习预测
- 深度学习分析
- 智能决策支持
"""
import numpy as np
from sklearn. ensemble import RandomForestRegressor
from tensorflow. keras. models import Sequential
from tensorflow. keras. layers import Dense
class AIFinancialAnalysis :
def __init__ ( self, data) :
self. data = data
def machine_learning_prediction ( self) :
"""机器学习预测"""
X = np. array( range ( len ( self. data) ) ) . reshape( - 1 , 1 )
y = self. data[ 'revenue' ] . values
model = RandomForestRegressor( )
model. fit( X, y)
prediction = model. predict( np. array( [ [ len ( self. data) + 1 ] ] ) )
return prediction[ 0 ]
def deep_learning_analysis ( self) :
"""深度学习分析"""
model = Sequential( [
Dense( 64 , activation= 'relu' , input_shape= ( 2 , ) ) ,
Dense( 32 , activation= 'relu' ) ,
Dense( 1 )
] )
model. compile ( optimizer= 'adam' , loss= 'mse' )
X = np. array( [ [ x[ 'revenue' ] , x[ 'profit' ] ] for x in self. data] )
y = np. array( [ x[ 'profit' ] for x in self. data] )
model. fit( X, y, epochs= 50 , verbose= 0 )
return model
def intelligent_decision ( self, threshold) :
"""智能决策"""
predictions = [ ]
for item in self. data:
if item[ 'profit' ] / item[ 'revenue' ] > threshold:
predictions. append( '投资' )
else :
predictions. append( '观望' )
return predictions
data = [
{ 'revenue' : 1000000 , 'profit' : 200000 } ,
{ 'revenue' : 1200000 , 'profit' : 250000 } ,
{ 'revenue' : 800000 , 'profit' : 150000 }
]
analysis = AIFinancialAnalysis( data)
print ( "机器学习预测结果:" , analysis. machine_learning_prediction( ) )
model = analysis. deep_learning_analysis( )
print ( "深度学习模型:" , model. summary( ) )
print ( "智能决策结果:" , analysis. intelligent_decision( 0.2 ) )
5.10.3 可视化技术
"""
财务数据可视化实现
- 交互式报表
- 动态图表
- 数据仪表盘
"""
import plotly. express as px
import dash
from dash import dcc, html
import pandas as pd
class FinancialVisualization :
def __init__ ( self, data) :
self. data = pd. DataFrame( data)
def interactive_report ( self) :
"""交互式报表"""
fig = px. bar( self. data, x= 'period' , y= 'revenue' ,
title= '季度收入分析' , text= 'revenue' )
fig. update_traces( textposition= 'outside' )
return fig
def dynamic_charts ( self) :
"""动态图表"""
fig = px. line( self. data, x= 'period' , y= [ 'revenue' , 'profit' ] ,
title= '收入与利润趋势' )
return fig
def create_dashboard ( self) :
"""创建仪表盘"""
app = dash. Dash( )
app. layout = html. Div( [
html. H1( '财务分析仪表盘' ) ,
dcc. Graph( figure= self. interactive_report( ) ) ,
dcc. Graph( figure= self. dynamic_charts( ) )
] )
return app
data = {
'period' : [ '2023-Q1' , '2023-Q2' , '2023-Q3' ] ,
'revenue' : [ 1000000 , 1200000 , 1500000 ] ,
'profit' : [ 200000 , 250000 , 300000 ]
}
visualization = FinancialVisualization( data)
print ( "交互式报表已创建" )
print ( "动态图表已创建" )
dashboard = visualization. create_dashboard( )
dashboard. run_server( debug= True )