Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import pandas as pd
|
3 |
+
import json
|
4 |
+
|
5 |
+
def analyze_financial_statements(income_statement, balance_sheet):
|
6 |
+
"""Analyze uploaded financial statements"""
|
7 |
+
try:
|
8 |
+
# Read the uploaded files
|
9 |
+
income_df = pd.read_csv(income_statement.name)
|
10 |
+
balance_df = pd.read_csv(balance_sheet.name)
|
11 |
+
|
12 |
+
# Calculate key metrics
|
13 |
+
metrics = calculate_metrics(income_df, balance_df)
|
14 |
+
|
15 |
+
# Generate analysis
|
16 |
+
analysis = generate_analysis(metrics)
|
17 |
+
|
18 |
+
# Format output
|
19 |
+
return format_results(metrics, analysis)
|
20 |
+
|
21 |
+
except Exception as e:
|
22 |
+
return f"Error analyzing files: {str(e)}"
|
23 |
+
|
24 |
+
def calculate_metrics(income_df, balance_df):
|
25 |
+
"""Calculate financial metrics"""
|
26 |
+
# Clean numeric data
|
27 |
+
income_df = income_df.replace({'\$': '', ' ': '', ',': '', '\(': '-', '\)': ''}, regex=True)
|
28 |
+
balance_df = balance_df.replace({'\$': '', ' ': '', ',': '', '\(': '-', '\)': ''}, regex=True)
|
29 |
+
|
30 |
+
# Convert to numeric
|
31 |
+
numeric_cols = ['Revenue', 'Net Income', 'Gross Profit', 'Total Assets',
|
32 |
+
'Total Liabilities', "Shareholder's Equity"]
|
33 |
+
|
34 |
+
for col in numeric_cols:
|
35 |
+
if col in income_df.columns:
|
36 |
+
income_df[col] = pd.to_numeric(income_df[col], errors='coerce')
|
37 |
+
if col in balance_df.columns:
|
38 |
+
balance_df[col] = pd.to_numeric(balance_df[col], errors='coerce')
|
39 |
+
|
40 |
+
# Calculate metrics
|
41 |
+
metrics = {
|
42 |
+
"Profitability": {
|
43 |
+
"Gross Margin (%)": round((income_df['Gross Profit'].iloc[-1] /
|
44 |
+
income_df['Revenue'].iloc[-1] * 100), 2),
|
45 |
+
"Net Margin (%)": round((income_df['Net Income'].iloc[-1] /
|
46 |
+
income_df['Revenue'].iloc[-1] * 100), 2)
|
47 |
+
},
|
48 |
+
"Growth": {
|
49 |
+
"Revenue Growth (%)": round(((income_df['Revenue'].iloc[-1] /
|
50 |
+
income_df['Revenue'].iloc[0] - 1) * 100), 2),
|
51 |
+
"Net Income Growth (%)": round(((income_df['Net Income'].iloc[-1] /
|
52 |
+
income_df['Net Income'].iloc[0] - 1) * 100), 2)
|
53 |
+
},
|
54 |
+
"Financial Position": {
|
55 |
+
"Debt to Equity": round(balance_df['Total Liabilities'].iloc[-1] /
|
56 |
+
balance_df["Shareholder's Equity"].iloc[-1], 2),
|
57 |
+
"Equity Ratio (%)": round((balance_df["Shareholder's Equity"].iloc[-1] /
|
58 |
+
balance_df['Total Assets'].iloc[-1] * 100), 2)
|
59 |
+
}
|
60 |
+
}
|
61 |
+
|
62 |
+
return metrics
|
63 |
+
|
64 |
+
def generate_analysis(metrics):
|
65 |
+
"""Generate insights and recommendations"""
|
66 |
+
analysis = {
|
67 |
+
"Key Insights": [],
|
68 |
+
"Recommendations": [],
|
69 |
+
"Risk Factors": []
|
70 |
+
}
|
71 |
+
|
72 |
+
# Analyze profitability
|
73 |
+
net_margin = metrics["Profitability"]["Net Margin (%)"]
|
74 |
+
if net_margin < 5:
|
75 |
+
analysis["Key Insights"].append(
|
76 |
+
"Low profit margins indicating operational efficiency challenges")
|
77 |
+
analysis["Recommendations"].append({
|
78 |
+
"Priority": "High",
|
79 |
+
"Area": "Profitability",
|
80 |
+
"Action": "Implement cost optimization program",
|
81 |
+
"Impact": "Improve net margins by 2-3%"
|
82 |
+
})
|
83 |
+
|
84 |
+
# Analyze growth
|
85 |
+
revenue_growth = metrics["Growth"]["Revenue Growth (%)"]
|
86 |
+
if revenue_growth < 5:
|
87 |
+
analysis["Key Insights"].append(
|
88 |
+
"Slow revenue growth suggesting need for market expansion")
|
89 |
+
analysis["Recommendations"].append({
|
90 |
+
"Priority": "High",
|
91 |
+
"Area": "Growth",
|
92 |
+
"Action": "Develop market expansion strategy",
|
93 |
+
"Impact": "Accelerate revenue growth to 8-10%"
|
94 |
+
})
|
95 |
+
|
96 |
+
# Analyze financial position
|
97 |
+
equity_ratio = metrics["Financial Position"]["Equity Ratio (%)"]
|
98 |
+
if equity_ratio > 70:
|
99 |
+
analysis["Key Insights"].append(
|
100 |
+
"High equity ratio suggests potential for leveraged growth")
|
101 |
+
analysis["Recommendations"].append({
|
102 |
+
"Priority": "Medium",
|
103 |
+
"Area": "Capital Structure",
|
104 |
+
"Action": "Evaluate growth financing options",
|
105 |
+
"Impact": "Optimize capital structure"
|
106 |
+
})
|
107 |
+
|
108 |
+
return analysis
|
109 |
+
|
110 |
+
def format_results(metrics, analysis):
|
111 |
+
"""Format analysis results"""
|
112 |
+
output = "# Financial Analysis Report\n\n"
|
113 |
+
|
114 |
+
# Add Metrics
|
115 |
+
output += "## Financial Metrics\n\n"
|
116 |
+
for category, values in metrics.items():
|
117 |
+
output += f"### {category}\n"
|
118 |
+
for metric, value in values.items():
|
119 |
+
output += f"- {metric}: {value}\n"
|
120 |
+
output += "\n"
|
121 |
+
|
122 |
+
# Add Insights
|
123 |
+
output += "## Key Insights\n\n"
|
124 |
+
for insight in analysis["Key Insights"]:
|
125 |
+
output += f"- {insight}\n"
|
126 |
+
output += "\n"
|
127 |
+
|
128 |
+
# Add Recommendations
|
129 |
+
output += "## Recommendations\n\n"
|
130 |
+
for rec in analysis["Recommendations"]:
|
131 |
+
output += f"### {rec['Area']} ({rec['Priority']} Priority)\n"
|
132 |
+
output += f"- Action: {rec['Action']}\n"
|
133 |
+
output += f"- Expected Impact: {rec['Impact']}\n\n"
|
134 |
+
|
135 |
+
return output
|
136 |
+
|
137 |
+
# Create Gradio interface
|
138 |
+
iface = gr.Interface(
|
139 |
+
fn=analyze_financial_statements,
|
140 |
+
inputs=[
|
141 |
+
gr.File(label="Income Statement (CSV)"),
|
142 |
+
gr.File(label="Balance Sheet (CSV)")
|
143 |
+
],
|
144 |
+
outputs=gr.Markdown(),
|
145 |
+
title="Financial Statement Analysis",
|
146 |
+
description="Upload your Income Statement and Balance Sheet (CSV format) for analysis.",
|
147 |
+
examples=[
|
148 |
+
[
|
149 |
+
"OFINTECH-Income Statement-template.csv",
|
150 |
+
"OFINTECH Balance Sheet template.csv"
|
151 |
+
]
|
152 |
+
]
|
153 |
+
)
|
154 |
+
|
155 |
+
# Launch the interface
|
156 |
+
if __name__ == "__main__":
|
157 |
+
iface.launch()
|