walaa2022 commited on
Commit
a1ef945
·
verified ·
1 Parent(s): a468d34

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -156
app.py CHANGED
@@ -1,157 +1,153 @@
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()
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from transformers import pipeline
4
+ import torch
5
+
6
+ class FinancialAnalyzer:
7
+ def __init__(self):
8
+ """Initialize models"""
9
+ # 1. Llama 2 for strategic analysis
10
+ self.strategic_analyzer = pipeline(
11
+ "text-generation",
12
+ model="meta-llama/Llama-2-7b-chat-hf",
13
+ device_map="auto"
14
+ )
15
+
16
+ # 2. FinBERT for financial sentiment
17
+ self.financial_analyzer = pipeline(
18
+ "text-classification",
19
+ model="ProsusAI/finbert",
20
+ return_all_scores=True
21
+ )
22
+
23
+ # 3. Falcon for recommendations
24
+ self.recommendation_generator = pipeline(
25
+ "text-generation",
26
+ model="tiiuae/falcon-7b-instruct",
27
+ device_map="auto"
28
+ )
29
+
30
+ def generate_strategic_analysis(self, financial_data):
31
+ """Generate strategic analysis using Llama 2"""
32
+ prompt = f"""[INST] As a senior financial analyst, analyze these financial statements:
33
+
34
+ Financial Data:
35
+ {financial_data}
36
+
37
+ Provide:
38
+ 1. Business Health Assessment
39
+ 2. Key Strategic Insights
40
+ 3. Market Position Analysis
41
+ 4. Growth Opportunities
42
+ 5. Risk Factors [/INST]"""
43
+
44
+ response = self.strategic_analyzer(
45
+ prompt,
46
+ max_length=1000,
47
+ temperature=0.7
48
+ )
49
+ return response[0]['generated_text']
50
+
51
+ def analyze_sentiment(self, text):
52
+ """Analyze financial sentiment using FinBERT"""
53
+ return self.financial_analyzer(text)
54
+
55
+ def generate_recommendations(self, analysis):
56
+ """Generate recommendations using Falcon"""
57
+ prompt = f"""Based on this financial analysis:
58
+ {analysis}
59
+
60
+ Provide specific, actionable recommendations covering:
61
+ 1. Strategic Initiatives
62
+ 2. Operational Improvements
63
+ 3. Financial Management
64
+ 4. Risk Mitigation
65
+ 5. Growth Strategy"""
66
+
67
+ response = self.recommendation_generator(
68
+ prompt,
69
+ max_length=800,
70
+ temperature=0.6
71
+ )
72
+ return response[0]['generated_text']
73
+
74
+ def analyze_financial_statements(income_statement, balance_sheet):
75
+ """Main analysis function"""
76
+ try:
77
+ # Read files
78
+ income_df = pd.read_csv(income_statement.name)
79
+ balance_df = pd.read_csv(balance_sheet.name)
80
+
81
+ # Initialize analyzer
82
+ analyzer = FinancialAnalyzer()
83
+
84
+ # Prepare financial data
85
+ financial_data = f"""
86
+ Income Statement Summary:
87
+ {income_df.to_string()}
88
+
89
+ Balance Sheet Summary:
90
+ {balance_df.to_string()}
91
+ """
92
+
93
+ # Generate strategic analysis
94
+ strategic_analysis = analyzer.generate_strategic_analysis(financial_data)
95
+
96
+ # Analyze sentiment
97
+ sentiment = analyzer.analyze_sentiment(strategic_analysis)
98
+
99
+ # Generate recommendations
100
+ recommendations = analyzer.generate_recommendations(strategic_analysis)
101
+
102
+ # Format output
103
+ output = format_results(strategic_analysis, sentiment, recommendations)
104
+
105
+ return output
106
+
107
+ except Exception as e:
108
+ return f"Error analyzing files: {str(e)}"
109
+
110
+ def format_results(analysis, sentiment, recommendations):
111
+ """Format analysis results"""
112
+ output = "# Financial Analysis Report\n\n"
113
+
114
+ # Strategic Analysis
115
+ output += "## Strategic Analysis\n\n"
116
+ output += analysis + "\n\n"
117
+
118
+ # Sentiment Analysis
119
+ output += "## Market Sentiment\n\n"
120
+ for score in sentiment[0]:
121
+ output += f"- {score['label']}: {score['score']:.2%}\n"
122
+ output += "\n"
123
+
124
+ # Recommendations
125
+ output += "## Strategic Recommendations\n\n"
126
+ output += recommendations
127
+
128
+ return output
129
+
130
+ # Create Gradio interface
131
+ iface = gr.Interface(
132
+ fn=analyze_financial_statements,
133
+ inputs=[
134
+ gr.File(label="Income Statement (CSV)"),
135
+ gr.File(label="Balance Sheet (CSV)")
136
+ ],
137
+ outputs=gr.Markdown(),
138
+ title="AI-Powered Financial Statement Analysis",
139
+ description="""Upload your financial statements for comprehensive analysis using:
140
+ - Llama 2: Strategic Analysis
141
+ - FinBERT: Financial Sentiment Analysis
142
+ - Falcon: Strategic Recommendations""",
143
+ examples=[
144
+ [
145
+ "OFINTECH-Income Statement-template.csv",
146
+ "OFINTECH Balance Sheet template.csv"
147
+ ]
148
+ ]
149
+ )
150
+
151
+ # Launch the interface
152
+ if __name__ == "__main__":
 
 
 
 
153
  iface.launch()