entropy25 commited on
Commit
6a28bb0
·
verified ·
1 Parent(s): 141e923

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +533 -1321
app.py CHANGED
@@ -1,1322 +1,534 @@
1
- # app.py - Main Application
2
- import streamlit as st
3
- import pandas as pd
4
- import plotly.express as px
5
- import plotly.graph_objects as go
6
- from plotly.subplots import make_subplots
7
- import numpy as np
8
- from datetime import datetime, timedelta
9
- import io
10
- import base64
11
-
12
- # Set page config
13
- st.set_page_config(
14
- page_title="FinanceGPT Analyzer",
15
- page_icon="💰",
16
- layout="wide",
17
- initial_sidebar_state="expanded"
18
- )
19
-
20
- # Custom CSS
21
- st.markdown("""
22
- <style>
23
- .main-header {
24
- font-size: 2.5rem;
25
- font-weight: bold;
26
- color: #1f77b4;
27
- text-align: center;
28
- margin-bottom: 2rem;
29
- }
30
- .kpi-card {
31
- background-color: #f0f8ff;
32
- padding: 1rem;
33
- border-radius: 10px;
34
- border-left: 5px solid #1f77b4;
35
- margin: 0.5rem 0;
36
- }
37
- .risk-alert {
38
- background-color: #ffe6e6;
39
- border-left: 5px solid #ff4444;
40
- }
41
- .positive-signal {
42
- background-color: #e6ffe6;
43
- border-left: 5px solid #44ff44;
44
- }
45
- </style>
46
- """, unsafe_allow_html=True)
47
-
48
- # Sample data generator
49
- @st.cache_data
50
- def generate_sample_data():
51
- years = [2020, 2021, 2022, 2023, 2024]
52
- data = {
53
- 'Year': years,
54
- 'Revenue': [1000000, 1150000, 1320000, 1450000, 1600000],
55
- 'Cost_of_Goods_Sold': [650000, 720000, 800000, 870000, 960000],
56
- 'Operating_Expenses': [200000, 230000, 250000, 280000, 300000],
57
- 'Net_Profit': [120000, 160000, 210000, 240000, 280000],
58
- 'Total_Assets': [2000000, 2300000, 2600000, 2900000, 3200000],
59
- 'Current_Assets': [800000, 920000, 1040000, 1160000, 1280000],
60
- 'Cash': [200000, 250000, 300000, 350000, 420000],
61
- 'Receivables': [150000, 180000, 220000, 250000, 290000],
62
- 'Current_Liabilities': [400000, 460000, 520000, 580000, 640000],
63
- 'Total_Liabilities': [800000, 920000, 1040000, 1160000, 1280000],
64
- 'Operating_Cash_Flow': [180000, 220000, 280000, 320000, 360000],
65
- 'Investing_Cash_Flow': [-80000, -120000, -150000, -180000, -200000],
66
- 'Financing_Cash_Flow': [-50000, -60000, -70000, -80000, -90000]
67
- }
68
- return pd.DataFrame(data)
69
-
70
- # Utility functions
71
- def calculate_yoy_change(current, previous):
72
- if previous == 0:
73
- return 0
74
- return ((current - previous) / previous) * 100
75
-
76
- def calculate_rating(value, ratio_type):
77
- ratings = {
78
- 'ROE': {'A+': 25, 'A': 20, 'B': 15, 'C': 10, 'D': 0},
79
- 'Current_Ratio': {'A+': 2.5, 'A': 2.0, 'B': 1.5, 'C': 1.0, 'D': 0},
80
- 'Debt_Ratio': {'A+': 0.3, 'A': 0.4, 'B': 0.5, 'C': 0.7, 'D': 1.0},
81
- 'Net_Margin': {'A+': 15, 'A': 10, 'B': 5, 'C': 2, 'D': 0}
82
- }
83
-
84
- if ratio_type not in ratings:
85
- return 'N/A'
86
-
87
- thresholds = ratings[ratio_type]
88
- if ratio_type == 'Debt_Ratio': # Lower is better
89
- for grade, threshold in thresholds.items():
90
- if value <= threshold:
91
- return grade
92
- else: # Higher is better
93
- for grade, threshold in thresholds.items():
94
- if value >= threshold:
95
- return grade
96
- return 'D'
97
-
98
- # Sidebar navigation
99
- def main():
100
- st.markdown('<h1 class="main-header">💰 FinanceGPT Analyzer</h1>', unsafe_allow_html=True)
101
-
102
- # Sidebar
103
- st.sidebar.title("Navigation")
104
- page = st.sidebar.selectbox(
105
- "Choose a page:",
106
- ["Dashboard", "Income Analysis", "Balance Sheet", "Cash Flow", "Ratio Hub", "AI Assistant"]
107
- )
108
-
109
- # Data loading section
110
- st.sidebar.header("Data Upload")
111
- uploaded_file = st.sidebar.file_uploader("Upload CSV file", type=['csv'])
112
- use_sample = st.sidebar.button("Use Sample Data")
113
-
114
- # Load data
115
- if uploaded_file is not None:
116
- df = pd.read_csv(uploaded_file)
117
- st.sidebar.success("Data uploaded successfully!")
118
- elif use_sample:
119
- df = generate_sample_data()
120
- st.sidebar.success("Sample data loaded!")
121
- else:
122
- df = generate_sample_data() # Default to sample data
123
-
124
- # Store data in session state
125
- st.session_state['financial_data'] = df
126
-
127
- # Page routing
128
- if page == "Dashboard":
129
- dashboard_page(df)
130
- elif page == "Income Analysis":
131
- income_analysis_page(df)
132
- elif page == "Balance Sheet":
133
- balance_sheet_page(df)
134
- elif page == "Cash Flow":
135
- cash_flow_page(df)
136
- elif page == "Ratio Hub":
137
- ratio_hub_page(df)
138
- elif page == "AI Assistant":
139
- ai_assistant_page(df)
140
-
141
- # Dashboard Page
142
- def dashboard_page(df):
143
- st.header("📊 Financial Dashboard")
144
-
145
- if len(df) < 2:
146
- st.error("Need at least 2 years of data for analysis")
147
- return
148
-
149
- # Calculate KPIs
150
- current_year = df.iloc[-1]
151
- previous_year = df.iloc[-2]
152
-
153
- # KPI Cards
154
- col1, col2, col3, col4 = st.columns(4)
155
-
156
- with col1:
157
- revenue_change = calculate_yoy_change(current_year['Revenue'], previous_year['Revenue'])
158
- st.markdown(f"""
159
- <div class="kpi-card">
160
- <h3>Revenue</h3>
161
- <h2>${current_year['Revenue']:,.0f}</h2>
162
- <p>YoY Change: {revenue_change:+.1f}%</p>
163
- </div>
164
- """, unsafe_allow_html=True)
165
-
166
- with col2:
167
- profit_change = calculate_yoy_change(current_year['Net_Profit'], previous_year['Net_Profit'])
168
- st.markdown(f"""
169
- <div class="kpi-card">
170
- <h3>Net Profit</h3>
171
- <h2>${current_year['Net_Profit']:,.0f}</h2>
172
- <p>YoY Change: {profit_change:+.1f}%</p>
173
- </div>
174
- """, unsafe_allow_html=True)
175
-
176
- with col3:
177
- assets_change = calculate_yoy_change(current_year['Total_Assets'], previous_year['Total_Assets'])
178
- st.markdown(f"""
179
- <div class="kpi-card">
180
- <h3>Total Assets</h3>
181
- <h2>${current_year['Total_Assets']:,.0f}</h2>
182
- <p>YoY Change: {assets_change:+.1f}%</p>
183
- </div>
184
- """, unsafe_allow_html=True)
185
-
186
- with col4:
187
- cash_change = calculate_yoy_change(current_year['Cash'], previous_year['Cash'])
188
- card_class = "kpi-card positive-signal" if cash_change > 100 else "kpi-card"
189
- st.markdown(f"""
190
- <div class="{card_class}">
191
- <h3>Cash</h3>
192
- <h2>${current_year['Cash']:,.0f}</h2>
193
- <p>YoY Change: {cash_change:+.1f}%</p>
194
- </div>
195
- """, unsafe_allow_html=True)
196
-
197
- # Insights
198
- st.subheader("📈 Key Insights")
199
- insights = []
200
-
201
- # Receivables check
202
- receivables_ratio = current_year['Receivables'] / current_year['Revenue'] * 100
203
- if receivables_ratio > 20:
204
- insights.append(f"⚠️ Receivables are {receivables_ratio:.1f}% of revenue - potential collection risk")
205
-
206
- # Cash growth check
207
- if cash_change > 100:
208
- insights.append(f"💪 Strong cash growth of {cash_change:.1f}% - excellent liquidity position")
209
-
210
- # Profitability check
211
- net_margin = current_year['Net_Profit'] / current_year['Revenue'] * 100
212
- if net_margin < 5:
213
- insights.append(f"📉 Net margin is {net_margin:.1f}% - consider cost optimization")
214
-
215
- for insight in insights:
216
- st.info(insight)
217
-
218
- # Charts
219
- st.subheader("📊 Financial Charts")
220
-
221
- # Create 2x2 chart layout
222
- fig = make_subplots(
223
- rows=2, cols=2,
224
- subplot_titles=('Revenue vs Net Profit', 'Financial Health Score',
225
- 'Asset vs Liability Structure', 'Cash Flow Overview'),
226
- specs=[[{"secondary_y": True}, {"type": "scatterpolar"}],
227
- [{"type": "bar"}, {"type": "waterfall"}]]
228
- )
229
-
230
- # Revenue vs Net Profit (dual-axis)
231
- fig.add_trace(
232
- go.Scatter(x=df['Year'], y=df['Revenue'], name='Revenue', line=dict(color='blue')),
233
- row=1, col=1
234
- )
235
- fig.add_trace(
236
- go.Scatter(x=df['Year'], y=df['Net_Profit'], name='Net Profit',
237
- line=dict(color='green'), yaxis='y2'),
238
- row=1, col=1
239
- )
240
-
241
- # Financial Health Score (radar chart)
242
- categories = ['Profitability', 'Liquidity', 'Efficiency', 'Growth', 'Stability']
243
- values = [
244
- min(net_margin / 10 * 100, 100), # Profitability
245
- min(current_year['Cash'] / current_year['Current_Liabilities'] * 25, 100), # Liquidity
246
- min(current_year['Revenue'] / current_year['Total_Assets'] * 100, 100), # Efficiency
247
- min(revenue_change * 10, 100), # Growth
248
- 80 # Stability (mock value)
249
- ]
250
-
251
- fig.add_trace(
252
- go.Scatterpolar(r=values, theta=categories, fill='tonext', name='Health Score'),
253
- row=1, col=2
254
- )
255
-
256
- # Asset vs Liability Structure
257
- years = df['Year'].tolist()
258
- fig.add_trace(
259
- go.Bar(x=years, y=df['Total_Assets'], name='Assets', marker_color='lightblue'),
260
- row=2, col=1
261
- )
262
- fig.add_trace(
263
- go.Bar(x=years, y=df['Total_Liabilities'], name='Liabilities', marker_color='lightcoral'),
264
- row=2, col=1
265
- )
266
-
267
- # Cash Flow Overview (waterfall)
268
- current_cf = current_year
269
- fig.add_trace(
270
- go.Waterfall(
271
- x=['Operating CF', 'Investing CF', 'Financing CF', 'Net Change'],
272
- y=[current_cf['Operating_Cash_Flow'], current_cf['Investing_Cash_Flow'],
273
- current_cf['Financing_Cash_Flow'],
274
- current_cf['Operating_Cash_Flow'] + current_cf['Investing_Cash_Flow'] + current_cf['Financing_Cash_Flow']],
275
- name='Cash Flow'
276
- ),
277
- row=2, col=2
278
- )
279
-
280
- fig.update_layout(height=800, title_text="Financial Dashboard Overview")
281
- st.plotly_chart(fig, use_container_width=True)
282
-
283
- # Income Analysis Page
284
- def income_analysis_page(df):
285
- st.header("💰 Income Analysis")
286
-
287
- # Revenue Trend
288
- st.subheader("📈 Revenue Trend")
289
- fig_revenue = px.line(df, x='Year', y='Revenue', title='Revenue Growth Over Time')
290
- fig_revenue.add_scatter(x=df['Year'], y=df['Revenue'], mode='markers+text',
291
- text=[f"{x:,.0f}" for x in df['Revenue']], textposition="top center")
292
- st.plotly_chart(fig_revenue, use_container_width=True)
293
-
294
- # YoY Growth Rate
295
- revenue_growth = df['Revenue'].pct_change() * 100
296
- fig_growth = px.bar(df[1:], x='Year', y=revenue_growth[1:], title='Year-over-Year Revenue Growth (%)')
297
- st.plotly_chart(fig_growth, use_container_width=True)
298
-
299
- col1, col2 = st.columns(2)
300
-
301
- with col1:
302
- # Cost Structure
303
- st.subheader("🥧 Cost Structure")
304
- current_year = df.iloc[-1]
305
- costs = {
306
- 'Cost of Goods Sold': current_year['Cost_of_Goods_Sold'],
307
- 'Operating Expenses': current_year['Operating_Expenses'],
308
- 'Other Costs': current_year['Revenue'] - current_year['Cost_of_Goods_Sold'] - current_year['Operating_Expenses'] - current_year['Net_Profit']
309
- }
310
-
311
- fig_pie = px.pie(values=list(costs.values()), names=list(costs.keys()),
312
- title='Cost Breakdown')
313
- st.plotly_chart(fig_pie, use_container_width=True)
314
-
315
- with col2:
316
- # Profitability Ratios
317
- st.subheader("📊 Profitability Ratios")
318
-
319
- # Calculate margins
320
- df['Gross_Margin'] = ((df['Revenue'] - df['Cost_of_Goods_Sold']) / df['Revenue']) * 100
321
- df['Operating_Margin'] = ((df['Revenue'] - df['Cost_of_Goods_Sold'] - df['Operating_Expenses']) / df['Revenue']) * 100
322
- df['Net_Margin'] = (df['Net_Profit'] / df['Revenue']) * 100
323
-
324
- # ROE and ROA (simplified calculations)
325
- equity = df['Total_Assets'] - df['Total_Liabilities']
326
- df['ROE'] = (df['Net_Profit'] / equity) * 100
327
- df['ROA'] = (df['Net_Profit'] / df['Total_Assets']) * 100
328
-
329
- margins_df = df[['Year', 'Gross_Margin', 'Operating_Margin', 'Net_Margin']].melt(
330
- id_vars=['Year'], var_name='Margin_Type', value_name='Percentage'
331
- )
332
-
333
- fig_margins = px.line(margins_df, x='Year', y='Percentage', color='Margin_Type',
334
- title='Profitability Margins Trend')
335
- fig_margins.add_hline(y=15, line_dash="dash", line_color="green",
336
- annotation_text="Industry Benchmark (15%)")
337
- st.plotly_chart(fig_margins, use_container_width=True)
338
-
339
- # Ratio Table
340
- st.subheader("📋 Key Ratios Summary")
341
- current_ratios = {
342
- 'Gross Margin (%)': df['Gross_Margin'].iloc[-1],
343
- 'Operating Margin (%)': df['Operating_Margin'].iloc[-1],
344
- 'Net Margin (%)': df['Net_Margin'].iloc[-1],
345
- 'ROE (%)': df['ROE'].iloc[-1],
346
- 'ROA (%)': df['ROA'].iloc[-1]
347
- }
348
-
349
- ratios_df = pd.DataFrame(list(current_ratios.items()), columns=['Ratio', 'Current Value'])
350
- ratios_df['Industry Benchmark'] = [35, 15, 10, 15, 8] # Mock benchmarks
351
- ratios_df['Performance'] = ratios_df.apply(
352
- lambda row: "Above" if row['Current Value'] > row['Industry Benchmark'] else "Below", axis=1
353
- )
354
-
355
- st.dataframe(ratios_df, use_container_width=True)
356
-
357
- # AI Suggestions
358
- st.subheader("🤖 AI-Generated Suggestions")
359
-
360
- suggestions = []
361
- current_net_margin = df['Net_Margin'].iloc[-1]
362
- revenue_growth_current = df['Revenue'].pct_change().iloc[-1] * 100
363
-
364
- if current_net_margin < 10:
365
- suggestions.append("💡 **Cost Optimization**: Consider reducing operating expenses or negotiating better supplier terms to improve net margin.")
366
-
367
- if revenue_growth_current < 5:
368
- suggestions.append("📈 **Revenue Growth**: Explore new market segments or product lines to accelerate revenue growth.")
369
-
370
- if df['ROE'].iloc[-1] < 15:
371
- suggestions.append("🎯 **Profitability**: Focus on high-margin products and improve asset utilization to boost ROE.")
372
-
373
- suggestions.append("📊 **Diversification**: Consider diversifying revenue streams to reduce dependency on single products/markets.")
374
-
375
- for suggestion in suggestions:
376
- st.info(suggestion)
377
-
378
- # Balance Sheet Page
379
- def balance_sheet_page(df):
380
- st.header("🏛️ Balance Sheet Analysis")
381
-
382
- current_year = df.iloc[-1]
383
-
384
- col1, col2 = st.columns(2)
385
-
386
- with col1:
387
- # Asset Structure
388
- st.subheader("📊 Asset Structure")
389
- non_current_assets = current_year['Total_Assets'] - current_year['Current_Assets']
390
-
391
- asset_data = {
392
- 'Current Assets': current_year['Current_Assets'],
393
- 'Non-Current Assets': non_current_assets
394
- }
395
-
396
- fig_assets = px.pie(values=list(asset_data.values()), names=list(asset_data.keys()),
397
- title='Asset Composition')
398
- st.plotly_chart(fig_assets, use_container_width=True)
399
-
400
- # Asset Quality Indicators
401
- st.subheader("🔍 Asset Quality Indicators")
402
- asset_quality = {
403
- 'Cash Ratio': (current_year['Cash'] / current_year['Current_Assets']) * 100,
404
- 'Receivables Ratio': (current_year['Receivables'] / current_year['Revenue']) * 100,
405
- 'Asset Turnover': current_year['Revenue'] / current_year['Total_Assets']
406
- }
407
-
408
- quality_df = pd.DataFrame(list(asset_quality.items()), columns=['Indicator', 'Value'])
409
- st.dataframe(quality_df, use_container_width=True)
410
-
411
- with col2:
412
- # Liability Structure
413
- st.subheader("📈 Liability Structure")
414
- short_term_liab = current_year['Current_Liabilities']
415
- long_term_liab = current_year['Total_Liabilities'] - current_year['Current_Liabilities']
416
-
417
- liab_data = {
418
- 'Short-term Liabilities': short_term_liab,
419
- 'Long-term Liabilities': long_term_liab
420
- }
421
-
422
- fig_liab = px.bar(x=list(liab_data.keys()), y=list(liab_data.values()),
423
- title='Liability Structure')
424
- st.plotly_chart(fig_liab, use_container_width=True)
425
-
426
- # Debt Maturity
427
- st.subheader("📅 Debt Maturity Structure")
428
- years = ['< 1 Year', '1-3 Years', '3-5 Years', '> 5 Years']
429
- debt_amounts = [short_term_liab, long_term_liab * 0.4, long_term_liab * 0.35, long_term_liab * 0.25]
430
-
431
- fig_maturity = px.bar(x=years, y=debt_amounts, title='Debt Maturity Profile')
432
- st.plotly_chart(fig_maturity, use_container_width=True)
433
-
434
- # Solvency Ratios
435
- st.subheader("⚖️ Solvency Ratios")
436
-
437
- current_ratio = current_year['Current_Assets'] / current_year['Current_Liabilities']
438
- quick_ratio = (current_year['Current_Assets'] - current_year['Receivables']) / current_year['Current_Liabilities']
439
- debt_to_asset = current_year['Total_Liabilities'] / current_year['Total_Assets']
440
-
441
- # Mock interest coverage calculation
442
- interest_expense = current_year['Total_Liabilities'] * 0.05 # Assume 5% interest rate
443
- ebit = current_year['Net_Profit'] + interest_expense # Simplified EBIT
444
- interest_coverage = ebit / interest_expense if interest_expense > 0 else 0
445
-
446
- ratios_data = {
447
- 'Current Ratio': current_ratio,
448
- 'Quick Ratio': quick_ratio,
449
- 'Debt to Asset Ratio': debt_to_asset,
450
- 'Interest Coverage': interest_coverage
451
- }
452
-
453
- col1, col2, col3, col4 = st.columns(4)
454
-
455
- for i, (ratio_name, value) in enumerate(ratios_data.items()):
456
- with [col1, col2, col3, col4][i]:
457
- color = "green" if ratio_name == "Current Ratio" and value >= 1.0 else "red" if ratio_name == "Current Ratio" and value < 1.0 else "blue"
458
- st.metric(ratio_name, f"{value:.2f}", delta=None)
459
-
460
- # Risk Alerts
461
- st.subheader("🚨 Risk Alert System")
462
-
463
- alerts = []
464
-
465
- if current_ratio < 1.0:
466
- alerts.append("🔴 **Liquidity Warning**: Current ratio below 1.0 indicates potential liquidity issues")
467
-
468
- if debt_to_asset > 0.7:
469
- alerts.append("🟠 **High Leverage**: Debt ratio above 70% suggests high financial risk")
470
-
471
- receivables_ratio = (current_year['Receivables'] / current_year['Revenue']) * 100
472
- if receivables_ratio > 20:
473
- alerts.append("🟡 **Receivable Risk**: Receivables exceed 20% of revenue - monitor collection efficiency")
474
-
475
- if not alerts:
476
- st.success("✅ No major risk alerts detected")
477
- else:
478
- for alert in alerts:
479
- st.warning(alert)
480
-
481
- # Improvement Suggestions
482
- st.subheader("💡 Improvement Suggestions")
483
-
484
- suggestions = []
485
-
486
- if current_ratio < 2.0:
487
- suggestions.append("Improve working capital management by optimizing inventory and receivables collection")
488
-
489
- if debt_to_asset > 0.5:
490
- suggestions.append("Consider debt reduction strategies or equity financing to improve leverage ratios")
491
-
492
- if quick_ratio < 1.0:
493
- suggestions.append("Maintain higher cash reserves for better short-term liquidity")
494
-
495
- for suggestion in suggestions:
496
- st.info(f"💡 {suggestion}")
497
-
498
- # Cash Flow Page
499
- def cash_flow_page(df):
500
- st.header("💸 Cash Flow Analysis")
501
-
502
- current_year = df.iloc[-1]
503
-
504
- # Cash Flow Overview
505
- st.subheader("🌊 Cash Flow Overview")
506
-
507
- # Waterfall Chart
508
- fig_waterfall = go.Figure(go.Waterfall(
509
- name="Cash Flow", orientation="v",
510
- measure=["relative", "relative", "relative", "total"],
511
- x=["Operating CF", "Investing CF", "Financing CF", "Net Cash Flow"],
512
- textposition="outside",
513
- text=[f"${current_year['Operating_Cash_Flow']:,.0f}",
514
- f"${current_year['Investing_Cash_Flow']:,.0f}",
515
- f"${current_year['Financing_Cash_Flow']:,.0f}",
516
- f"${current_year['Operating_Cash_Flow'] + current_year['Investing_Cash_Flow'] + current_year['Financing_Cash_Flow']:,.0f}"],
517
- y=[current_year['Operating_Cash_Flow'], current_year['Investing_Cash_Flow'],
518
- current_year['Financing_Cash_Flow'], 0],
519
- connector={"line": {"color": "rgb(63, 63, 63)"}},
520
- ))
521
-
522
- fig_waterfall.update_layout(title="Cash Flow Waterfall", showlegend=True)
523
- st.plotly_chart(fig_waterfall, use_container_width=True)
524
-
525
- col1, col2 = st.columns(2)
526
-
527
- with col1:
528
- # Cash Flow Trend
529
- st.subheader("📈 Cash Flow Trend")
530
-
531
- cf_melted = df[['Year', 'Operating_Cash_Flow', 'Investing_Cash_Flow', 'Financing_Cash_Flow']].melt(
532
- id_vars=['Year'], var_name='Cash_Flow_Type', value_name='Amount'
533
- )
534
-
535
- fig_trend = px.line(cf_melted, x='Year', y='Amount', color='Cash_Flow_Type',
536
- title='Cash Flow Trends Over Time')
537
- st.plotly_chart(fig_trend, use_container_width=True)
538
-
539
- with col2:
540
- # Cash Health Score
541
- st.subheader("💪 Cash Health Score")
542
-
543
- # Calculate health metrics
544
- ocf_net_profit = current_year['Operating_Cash_Flow'] / current_year['Net_Profit'] if current_year['Net_Profit'] > 0 else 0
545
- free_cash_flow = current_year['Operating_Cash_Flow'] + current_year['Investing_Cash_Flow']
546
- cash_coverage = current_year['Cash'] / current_year['Current_Liabilities']
547
-
548
- health_metrics = ['OCF Quality', 'FCF Strength', 'Cash Coverage', 'Overall Health']
549
- health_values = [
550
- min(ocf_net_profit * 20, 100),
551
- min(max(free_cash_flow / 100000 * 20, 0), 100),
552
- min(cash_coverage * 30, 100),
553
- (min(ocf_net_profit * 20, 100) + min(max(free_cash_flow / 100000 * 20, 0), 100) + min(cash_coverage * 30, 100)) / 3
554
- ]
555
-
556
- fig_radar = go.Figure()
557
- fig_radar.add_trace(go.Scatterpolar(
558
- r=health_values,
559
- theta=health_metrics,
560
- fill='tonext',
561
- name='Cash Health'
562
- ))
563
-
564
- fig_radar.update_layout(
565
- polar=dict(
566
- radialaxis=dict(
567
- visible=True,
568
- range=[0, 100]
569
- )),
570
- showlegend=False,
571
- title="Cash Health Score"
572
- )
573
- st.plotly_chart(fig_radar, use_container_width=True)
574
-
575
- # Cash Quality Metrics
576
- st.subheader("🔍 Cash Quality Metrics")
577
-
578
- # Free Cash Flow calculation
579
- free_cash_flow = current_year['Operating_Cash_Flow'] + current_year['Investing_Cash_Flow']
580
-
581
- # Cash Conversion Cycle (simplified)
582
- receivables_days = (current_year['Receivables'] / current_year['Revenue']) * 365
583
- cash_conversion_cycle = receivables_days # Simplified calculation
584
-
585
- quality_metrics = {
586
- 'Operating CF / Net Profit': ocf_net_profit,
587
- 'Free Cash Flow ($)': free_cash_flow,
588
- 'Cash Conversion Cycle (days)': cash_conversion_cycle
589
- }
590
-
591
- col1, col2, col3 = st.columns(3)
592
-
593
- for i, (metric, value) in enumerate(quality_metrics.items()):
594
- with [col1, col2, col3][i]:
595
- if 'days' in metric:
596
- st.metric(metric, f"{value:.0f}")
597
- elif '$' in metric:
598
- st.metric(metric, f"${value:,.0f}")
599
- else:
600
- st.metric(metric, f"{value:.2f}")
601
-
602
- # Cash Flow Ratios Dashboard
603
- st.subheader("📊 Cash Flow Ratios")
604
-
605
- cash_to_current_liab = current_year['Cash'] / current_year['Current_Liabilities']
606
- cash_to_debt = current_year['Cash'] / current_year['Total_Liabilities']
607
- capex_coverage = abs(current_year['Operating_Cash_Flow'] / current_year['Investing_Cash_Flow']) if current_year['Investing_Cash_Flow'] != 0 else 0
608
-
609
- ratios = ['Cash to Current Liabilities', 'Cash to Debt', 'CapEx Coverage']
610
- ratio_values = [cash_to_current_liab, cash_to_debt, capex_coverage]
611
-
612
- fig_ratios = px.bar(x=ratios, y=ratio_values, title='Cash Flow Ratios Dashboard')
613
- st.plotly_chart(fig_ratios, use_container_width=True)
614
-
615
- # Cash Flow Forecast
616
- st.subheader("🔮 Cash Flow Forecast (Next 3 Months)")
617
-
618
- # Simple trend-based forecast
619
- recent_ocf_trend = np.mean(df['Operating_Cash_Flow'].tail(3).pct_change().dropna())
620
-
621
- months = ['Month 1', 'Month 2', 'Month 3']
622
- monthly_ocf = current_year['Operating_Cash_Flow'] / 12 # Monthly average
623
-
624
- forecasted_cf = []
625
- for i in range(3):
626
- forecast = monthly_ocf * (1 + recent_ocf_trend) ** (i + 1)
627
- forecasted_cf.append(forecast)
628
-
629
- forecast_df = pd.DataFrame({
630
- 'Month': months,
631
- 'Forecasted Operating CF': forecasted_cf
632
- })
633
-
634
- fig_forecast = px.line(forecast_df, x='Month', y='Forecasted Operating CF',
635
- title='3-Month Cash Flow Forecast')
636
- st.plotly_chart(fig_forecast, use_container_width=True)
637
-
638
- # Warning system
639
- min_forecast = min(forecasted_cf)
640
- if min_forecast < current_year['Current_Liabilities'] * 0.1: # Less than 10% of current liabilities
641
- st.error("⚠️ **Cash Flow Warning**: Forecasted cash flow may be insufficient to meet short-term obligations")
642
- else:
643
- st.success("✅ Forecasted cash flow appears adequate for the next 3 months")
644
-
645
- # Ratio Hub Page
646
- def ratio_hub_page(df):
647
- st.header("📊 Financial Ratios Hub")
648
-
649
- current_year = df.iloc[-1]
650
-
651
- # Ratio Type Filter
652
- ratio_types = ['All', 'Profitability', 'Solvency', 'Efficiency', 'Growth']
653
- selected_type = st.selectbox("Select Ratio Type:", ratio_types)
654
-
655
- # Calculate all ratios
656
- ratios_data = calculate_all_ratios(df)
657
-
658
- # Filter ratios based on selection
659
- if selected_type != 'All':
660
- filtered_ratios = {k: v for k, v in ratios_data.items() if v['category'] == selected_type}
661
- else:
662
- filtered_ratios = ratios_data
663
-
664
- # Display ratios
665
- for ratio_name, ratio_info in filtered_ratios.items():
666
- with st.expander(f"{ratio_name} - Rating: {ratio_info['rating']} {ratio_info['trend']}"):
667
- col1, col2, col3 = st.columns([1, 1, 2])
668
-
669
- with col1:
670
- st.metric("Current Value", f"{ratio_info['value']:.2f}")
671
- st.metric("Industry Benchmark", f"{ratio_info['benchmark']:.2f}")
672
-
673
- with col2:
674
- # Mini trend chart
675
- if len(ratio_info['history']) > 1:
676
- fig_mini = px.line(x=range(len(ratio_info['history'])),
677
- y=ratio_info['history'],
678
- title=f"{ratio_name} Trend")
679
- fig_mini.update_layout(height=200, showlegend=False)
680
- st.plotly_chart(fig_mini, use_container_width=True)
681
-
682
- with col3:
683
- st.write(f"**Definition**: {ratio_info['definition']}")
684
- st.write(f"**Formula**: {ratio_info['formula']}")
685
-
686
- if ratio_info['value'] < ratio_info['benchmark']:
687
- st.warning(f"⚠️ **Warning**: {ratio_info['warning']}")
688
-
689
- st.info(f"💡 **Improvement**: {ratio_info['improvement']}")
690
-
691
- # Download PDF Report
692
- st.subheader("📄 Download Report")
693
- if st.button("Generate PDF Report"):
694
- pdf_content = generate_pdf_report(ratios_data)
695
- st.download_button(
696
- label="Download PDF",
697
- data=pdf_content,
698
- file_name=f"financial_ratios_report_{datetime.now().strftime('%Y%m%d')}.txt",
699
- mime="text/plain"
700
- )
701
-
702
- def calculate_all_ratios(df):
703
- current_year = df.iloc[-1]
704
- previous_year = df.iloc[-2] if len(df) > 1 else current_year
705
-
706
- # Calculate ratios with history
707
- def get_ratio_history(ratio_name, df):
708
- history = []
709
- for _, row in df.iterrows():
710
- if ratio_name == 'ROE':
711
- equity = row['Total_Assets'] - row['Total_Liabilities']
712
- history.append((row['Net_Profit'] / equity) * 100 if equity > 0 else 0)
713
- elif ratio_name == 'Current Ratio':
714
- history.append(row['Current_Assets'] / row['Current_Liabilities'])
715
- elif ratio_name == 'Net Margin':
716
- history.append((row['Net_Profit'] / row['Revenue']) * 100)
717
- elif ratio_name == 'Debt Ratio':
718
- history.append(row['Total_Liabilities'] / row['Total_Assets'])
719
- elif ratio_name == 'Asset Turnover':
720
- history.append(row['Revenue'] / row['Total_Assets'])
721
- return history
722
-
723
- ratios = {
724
- 'ROE': {
725
- 'value': (current_year['Net_Profit'] / (current_year['Total_Assets'] - current_year['Total_Liabilities'])) * 100,
726
- 'benchmark': 15.0,
727
- 'category': 'Profitability',
728
- 'definition': 'Return on Equity measures how effectively a company uses shareholders equity to generate profit',
729
- 'formula': 'Net Profit / Shareholders Equity × 100',
730
- 'warning': 'Low ROE may indicate inefficient use of equity capital',
731
- 'improvement': 'Focus on increasing profitability or optimizing capital structure',
732
- 'history': get_ratio_history('ROE', df)
733
- },
734
- 'Current Ratio': {
735
- 'value': current_year['Current_Assets'] / current_year['Current_Liabilities'],
736
- 'benchmark': 2.0,
737
- 'category': 'Solvency',
738
- 'definition': 'Current Ratio measures ability to pay short-term obligations',
739
- 'formula': 'Current Assets / Current Liabilities',
740
- 'warning': 'Low current ratio indicates potential liquidity problems',
741
- 'improvement': 'Improve working capital management and maintain adequate cash reserves',
742
- 'history': get_ratio_history('Current Ratio', df)
743
- },
744
- 'Net Margin': {
745
- 'value': (current_year['Net_Profit'] / current_year['Revenue']) * 100,
746
- 'benchmark': 10.0,
747
- 'category': 'Profitability',
748
- 'definition': 'Net Margin shows percentage of revenue that becomes profit',
749
- 'formula': 'Net Profit / Revenue × 100',
750
- 'warning': 'Low net margin suggests high costs or pricing pressure',
751
- 'improvement': 'Focus on cost reduction and operational efficiency',
752
- 'history': get_ratio_history('Net Margin', df)
753
- },
754
- 'Debt Ratio': {
755
- 'value': current_year['Total_Liabilities'] / current_year['Total_Assets'],
756
- 'benchmark': 0.4,
757
- 'category': 'Solvency',
758
- 'definition': 'Debt Ratio measures proportion of assets financed by debt',
759
- 'formula': 'Total Liabilities / Total Assets',
760
- 'warning': 'High debt ratio increases financial risk',
761
- 'improvement': 'Consider debt reduction or equity financing strategies',
762
- 'history': get_ratio_history('Debt Ratio', df)
763
- },
764
- 'Asset Turnover': {
765
- 'value': current_year['Revenue'] / current_year['Total_Assets'],
766
- 'benchmark': 1.0,
767
- 'category': 'Efficiency',
768
- 'definition': 'Asset Turnover measures how efficiently assets generate revenue',
769
- 'formula': 'Revenue / Total Assets',
770
- 'warning': 'Low asset turnover indicates inefficient asset utilization',
771
- 'improvement': 'Optimize asset utilization and consider divesting underperforming assets',
772
- 'history': get_ratio_history('Asset Turnover', df)
773
- }
774
- }
775
-
776
- # Add ratings and trends
777
- for ratio_name, ratio_info in ratios.items():
778
- ratio_info['rating'] = calculate_rating(ratio_info['value'], ratio_name)
779
-
780
- # Calculate trend
781
- if len(ratio_info['history']) > 1:
782
- recent_change = ratio_info['history'][-1] - ratio_info['history'][-2]
783
- if recent_change > 0:
784
- ratio_info['trend'] = '📈'
785
- elif recent_change < 0:
786
- ratio_info['trend'] = '📉'
787
- else:
788
- ratio_info['trend'] = '➡️'
789
- else:
790
- ratio_info['trend'] = '➡️'
791
-
792
- return ratios
793
-
794
- def generate_pdf_report(ratios_data):
795
- """Generate a text-based report (placeholder for PDF)"""
796
- report = f"""
797
- FINANCIAL RATIOS REPORT
798
- Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
799
-
800
- EXECUTIVE SUMMARY
801
- ================
802
- """
803
-
804
- for ratio_name, ratio_info in ratios_data.items():
805
- report += f"""
806
- {ratio_name.upper()}
807
- - Current Value: {ratio_info['value']:.2f}
808
- - Rating: {ratio_info['rating']}
809
- - Benchmark: {ratio_info['benchmark']:.2f}
810
- - Category: {ratio_info['category']}
811
- - Definition: {ratio_info['definition']}
812
-
813
- """
814
-
815
- return report
816
-
817
- # AI Assistant Page
818
- def ai_assistant_page(df):
819
- st.header("🤖 AI Finance Assistant")
820
-
821
- # Initialize chat history
822
- if 'chat_history' not in st.session_state:
823
- st.session_state.chat_history = []
824
-
825
- # Data Context Panel
826
- with st.sidebar:
827
- st.subheader("📊 Data Context")
828
- current_year = df.iloc[-1]
829
-
830
- st.write("**Key Financials:**")
831
- st.write(f"• Revenue: ${current_year['Revenue']:,.0f}")
832
- st.write(f"• Net Profit: ${current_year['Net_Profit']:,.0f}")
833
- st.write(f"• Total Assets: ${current_year['Total_Assets']:,.0f}")
834
- st.write(f"• Cash: ${current_year['Cash']:,.0f}")
835
-
836
- # Quick issue detection
837
- st.write("**Detected Issues:**")
838
- issues = []
839
-
840
- net_margin = (current_year['Net_Profit'] / current_year['Revenue']) * 100
841
- if net_margin < 5:
842
- issues.append("• Low net profit margin")
843
-
844
- current_ratio = current_year['Current_Assets'] / current_year['Current_Liabilities']
845
- if current_ratio < 1.0:
846
- issues.append("• Liquidity concerns")
847
-
848
- debt_ratio = current_year['Total_Liabilities'] / current_year['Total_Assets']
849
- if debt_ratio > 0.7:
850
- issues.append("• High leverage")
851
-
852
- if issues:
853
- for issue in issues:
854
- st.write(issue)
855
- else:
856
- st.write("• No major issues detected ✅")
857
-
858
- # Quick Question Buttons
859
- st.subheader("🚀 Quick Questions")
860
-
861
- col1, col2, col3, col4 = st.columns(4)
862
-
863
- with col1:
864
- if st.button("💊 Analyze Financial Health"):
865
- handle_quick_question("financial_health", df)
866
-
867
- with col2:
868
- if st.button("⚠️ Find Top Risks"):
869
- handle_quick_question("risks", df)
870
-
871
- with col3:
872
- if st.button("💡 Investment Advice"):
873
- handle_quick_question("investment", df)
874
-
875
- with col4:
876
- if st.button("📈 Improvement Plan"):
877
- handle_quick_question("improvement", df)
878
-
879
- # Chat Interface
880
- st.subheader("💬 Chat with AI Assistant")
881
-
882
- # Display chat history
883
- for message in st.session_state.chat_history:
884
- if message['role'] == 'user':
885
- st.write(f"**You:** {message['content']}")
886
- else:
887
- st.write(f"**AI:** {message['content']}")
888
-
889
- # Chat input
890
- user_input = st.text_input("Ask me anything about your financial data:", key="chat_input")
891
-
892
- if st.button("Send") and user_input:
893
- # Add user message to history
894
- st.session_state.chat_history.append({"role": "user", "content": user_input})
895
-
896
- # Generate AI response
897
- ai_response = generate_ai_response(user_input, df)
898
- st.session_state.chat_history.append({"role": "assistant", "content": ai_response})
899
-
900
- # Rerun to show updated chat
901
- st.rerun()
902
-
903
- # Export Options
904
- st.subheader("📥 Export Options")
905
-
906
- col1, col2 = st.columns(2)
907
-
908
- with col1:
909
- if st.button("📄 Export Chat Log"):
910
- chat_log = export_chat_log(st.session_state.chat_history)
911
- st.download_button(
912
- label="Download Chat Log",
913
- data=chat_log,
914
- file_name=f"chat_log_{datetime.now().strftime('%Y%m%d_%H%M')}.txt",
915
- mime="text/plain"
916
- )
917
-
918
- with col2:
919
- if st.button("📊 Generate AI Report"):
920
- ai_report = generate_ai_report(df)
921
- st.download_button(
922
- label="Download AI Report",
923
- data=ai_report,
924
- file_name=f"ai_financial_report_{datetime.now().strftime('%Y%m%d')}.txt",
925
- mime="text/plain"
926
- )
927
-
928
- def handle_quick_question(question_type, df):
929
- current_year = df.iloc[-1]
930
-
931
- if question_type == "financial_health":
932
- response = analyze_financial_health(df)
933
- elif question_type == "risks":
934
- response = identify_top_risks(df)
935
- elif question_type == "investment":
936
- response = provide_investment_advice(df)
937
- elif question_type == "improvement":
938
- response = create_improvement_plan(df)
939
-
940
- st.session_state.chat_history.append({"role": "assistant", "content": response})
941
-
942
- def analyze_financial_health(df):
943
- current_year = df.iloc[-1]
944
-
945
- # Calculate key health indicators
946
- net_margin = (current_year['Net_Profit'] / current_year['Revenue']) * 100
947
- current_ratio = current_year['Current_Assets'] / current_year['Current_Liabilities']
948
- debt_ratio = current_year['Total_Liabilities'] / current_year['Total_Assets']
949
- roe = (current_year['Net_Profit'] / (current_year['Total_Assets'] - current_year['Total_Liabilities'])) * 100
950
-
951
- health_score = 0
952
- issues = []
953
- strengths = []
954
-
955
- # Profitability
956
- if net_margin >= 10:
957
- health_score += 25
958
- strengths.append("Strong profitability")
959
- elif net_margin >= 5:
960
- health_score += 15
961
- else:
962
- issues.append("Low profitability")
963
-
964
- # Liquidity
965
- if current_ratio >= 2.0:
966
- health_score += 25
967
- strengths.append("Excellent liquidity")
968
- elif current_ratio >= 1.0:
969
- health_score += 15
970
- else:
971
- health_score += 5
972
- issues.append("Liquidity concerns")
973
-
974
- # Leverage
975
- if debt_ratio <= 0.3:
976
- health_score += 25
977
- strengths.append("Conservative leverage")
978
- elif debt_ratio <= 0.5:
979
- health_score += 15
980
- else:
981
- health_score += 5
982
- issues.append("High leverage")
983
-
984
- # Returns
985
- if roe >= 15:
986
- health_score += 25
987
- strengths.append("Excellent returns")
988
- elif roe >= 10:
989
- health_score += 15
990
- else:
991
- issues.append("Low returns on equity")
992
-
993
- # Generate response
994
- if health_score >= 80:
995
- grade = "A - Excellent"
996
- elif health_score >= 60:
997
- grade = "B - Good"
998
- elif health_score >= 40:
999
- grade = "C - Average"
1000
- else:
1001
- grade = "D - Needs Improvement"
1002
-
1003
- response = f"""
1004
- **FINANCIAL HEALTH ANALYSIS**
1005
-
1006
- **Overall Health Score: {health_score}/100 - Grade {grade}**
1007
-
1008
- **Key Metrics:**
1009
- • Net Margin: {net_margin:.1f}%
1010
- • Current Ratio: {current_ratio:.2f}
1011
- • Debt Ratio: {debt_ratio:.1f}%
1012
- • ROE: {roe:.1f}%
1013
-
1014
- **Strengths:**
1015
- {chr(10).join(['• ' + s for s in strengths]) if strengths else '• Areas for improvement identified'}
1016
-
1017
- **Areas of Concern:**
1018
- {chr(10).join(['• ' + i for i in issues]) if issues else '• No major concerns identified'}
1019
-
1020
- **Recommendation:** {"Continue current strategy with minor optimizations" if health_score >= 60 else "Implement comprehensive improvement plan to address key weaknesses"}
1021
- """
1022
-
1023
- return response
1024
-
1025
- def identify_top_risks(df):
1026
- current_year = df.iloc[-1]
1027
- risks = []
1028
-
1029
- # Liquidity risk
1030
- current_ratio = current_year['Current_Assets'] / current_year['Current_Liabilities']
1031
- if current_ratio < 1.0:
1032
- risks.append(("HIGH", "Liquidity Risk", f"Current ratio of {current_ratio:.2f} indicates potential difficulty meeting short-term obligations"))
1033
- elif current_ratio < 1.5:
1034
- risks.append(("MEDIUM", "Liquidity Risk", f"Current ratio of {current_ratio:.2f} is below optimal levels"))
1035
-
1036
- # Leverage risk
1037
- debt_ratio = current_year['Total_Liabilities'] / current_year['Total_Assets']
1038
- if debt_ratio > 0.7:
1039
- risks.append(("HIGH", "Leverage Risk", f"Debt ratio of {debt_ratio:.1%} indicates high financial leverage"))
1040
- elif debt_ratio > 0.5:
1041
- risks.append(("MEDIUM", "Leverage Risk", f"Debt ratio of {debt_ratio:.1%} is above average industry levels"))
1042
-
1043
- # Profitability risk
1044
- net_margin = (current_year['Net_Profit'] / current_year['Revenue']) * 100
1045
- if net_margin < 2:
1046
- risks.append(("HIGH", "Profitability Risk", f"Net margin of {net_margin:.1f}% is critically low"))
1047
- elif net_margin < 5:
1048
- risks.append(("MEDIUM", "Profitability Risk", f"Net margin of {net_margin:.1f}% is below industry standards"))
1049
-
1050
- # Receivables risk
1051
- receivables_ratio = (current_year['Receivables'] / current_year['Revenue']) * 100
1052
- if receivables_ratio > 25:
1053
- risks.append(("MEDIUM", "Collection Risk", f"Receivables represent {receivables_ratio:.1f}% of revenue - monitor collection efficiency"))
1054
-
1055
- # Cash flow risk
1056
- if len(df) > 1:
1057
- ocf_trend = (current_year['Operating_Cash_Flow'] - df.iloc[-2]['Operating_Cash_Flow']) / df.iloc[-2]['Operating_Cash_Flow'] * 100
1058
- if ocf_trend < -10:
1059
- risks.append(("MEDIUM", "Cash Flow Risk", f"Operating cash flow declined by {abs(ocf_trend):.1f}%"))
1060
-
1061
- if not risks:
1062
- return "**RISK ANALYSIS**\n\n✅ **Good news!** No major financial risks detected in your current financial position. Continue monitoring key metrics regularly."
1063
-
1064
- response = "**TOP FINANCIAL RISKS IDENTIFIED**\n\n"
1065
- for risk_level, risk_type, description in sorted(risks, key=lambda x: x[0], reverse=True):
1066
- emoji = "🔴" if risk_level == "HIGH" else "🟡"
1067
- response += f"{emoji} **{risk_level} - {risk_type}**\n{description}\n\n"
1068
-
1069
- return response
1070
-
1071
- def provide_investment_advice(df):
1072
- current_year = df.iloc[-1]
1073
-
1074
- # Calculate key metrics for investment decision
1075
- roe = (current_year['Net_Profit'] / (current_year['Total_Assets'] - current_year['Total_Liabilities'])) * 100
1076
- revenue_growth = ((current_year['Revenue'] / df.iloc[-2]['Revenue']) - 1) * 100 if len(df) > 1 else 0
1077
- debt_ratio = current_year['Total_Liabilities'] / current_year['Total_Assets']
1078
- current_ratio = current_year['Current_Assets'] / current_year['Current_Liabilities']
1079
-
1080
- score = 0
1081
- reasons = []
1082
-
1083
- # Investment scoring
1084
- if roe >= 15:
1085
- score += 2
1086
- reasons.append("Strong return on equity")
1087
- elif roe >= 10:
1088
- score += 1
1089
- else:
1090
- reasons.append("Below-average returns")
1091
-
1092
- if revenue_growth >= 10:
1093
- score += 2
1094
- reasons.append("Strong revenue growth")
1095
- elif revenue_growth >= 5:
1096
- score += 1
1097
- else:
1098
- reasons.append("Modest growth trajectory")
1099
-
1100
- if debt_ratio <= 0.4:
1101
- score += 2
1102
- reasons.append("Conservative debt levels")
1103
- elif debt_ratio <= 0.6:
1104
- score += 1
1105
- else:
1106
- reasons.append("High leverage concerns")
1107
-
1108
- if current_ratio >= 1.5:
1109
- score += 2
1110
- reasons.append("Strong liquidity position")
1111
- elif current_ratio >= 1.0:
1112
- score += 1
1113
- else:
1114
- reasons.append("Liquidity challenges")
1115
-
1116
- # Investment recommendation
1117
- if score >= 6:
1118
- recommendation = "STRONG BUY"
1119
- outlook = "Excellent investment opportunity with strong fundamentals"
1120
- elif score >= 4:
1121
- recommendation = "BUY"
1122
- outlook = "Good investment opportunity with solid fundamentals"
1123
- elif score >= 2:
1124
- recommendation = "HOLD"
1125
- outlook = "Mixed signals - monitor closely before investing"
1126
- else:
1127
- recommendation = "AVOID"
1128
- outlook = "Significant concerns identified - avoid until improvements made"
1129
-
1130
- response = f"""
1131
- **INVESTMENT ANALYSIS & RECOMMENDATION**
1132
-
1133
- **Recommendation: {recommendation}**
1134
-
1135
- **Investment Score: {score}/8**
1136
-
1137
- **Key Metrics:**
1138
- • ROE: {roe:.1f}%
1139
- • Revenue Growth: {revenue_growth:.1f}%
1140
- • Debt Ratio: {debt_ratio:.1%}
1141
- • Current Ratio: {current_ratio:.2f}
1142
-
1143
- **Investment Rationale:**
1144
- {chr(10).join(['• ' + r for r in reasons])}
1145
-
1146
- **Outlook:** {outlook}
1147
-
1148
- **Risk Considerations:**
1149
- • Monitor quarterly performance trends
1150
- • Watch for changes in market conditions
1151
- • Consider portfolio diversification
1152
- • Regular review of financial health metrics
1153
- """
1154
-
1155
- return response
1156
-
1157
- def create_improvement_plan(df):
1158
- current_year = df.iloc[-1]
1159
-
1160
- # Identify improvement areas
1161
- improvements = []
1162
-
1163
- # Profitability improvements
1164
- net_margin = (current_year['Net_Profit'] / current_year['Revenue']) * 100
1165
- if net_margin < 10:
1166
- improvements.append({
1167
- "area": "Profitability Enhancement",
1168
- "priority": "HIGH",
1169
- "actions": [
1170
- "Conduct cost reduction analysis focusing on operating expenses",
1171
- "Review pricing strategy and consider premium positioning",
1172
- "Improve operational efficiency through automation",
1173
- "Negotiate better terms with suppliers"
1174
- ]
1175
- })
1176
-
1177
- # Liquidity improvements
1178
- current_ratio = current_year['Current_Assets'] / current_year['Current_Liabilities']
1179
- if current_ratio < 2.0:
1180
- improvements.append({
1181
- "area": "Liquidity Management",
1182
- "priority": "HIGH" if current_ratio < 1.0 else "MEDIUM",
1183
- "actions": [
1184
- "Improve accounts receivable collection processes",
1185
- "Optimize inventory management to free up cash",
1186
- "Establish credit facilities for working capital needs",
1187
- "Consider factoring receivables if necessary"
1188
- ]
1189
- })
1190
-
1191
- # Leverage optimization
1192
- debt_ratio = current_year['Total_Liabilities'] / current_year['Total_Assets']
1193
- if debt_ratio > 0.5:
1194
- improvements.append({
1195
- "area": "Capital Structure Optimization",
1196
- "priority": "MEDIUM",
1197
- "actions": [
1198
- "Develop debt reduction strategy with timeline",
1199
- "Consider equity financing options",
1200
- "Refinance high-interest debt",
1201
- "Improve debt service coverage ratios"
1202
- ]
1203
- })
1204
-
1205
- # Growth initiatives
1206
- revenue_growth = ((current_year['Revenue'] / df.iloc[-2]['Revenue']) - 1) * 100 if len(df) > 1 else 0
1207
- if revenue_growth < 5:
1208
- improvements.append({
1209
- "area": "Growth Acceleration",
1210
- "priority": "MEDIUM",
1211
- "actions": [
1212
- "Identify new market opportunities",
1213
- "Invest in marketing and sales capabilities",
1214
- "Consider strategic partnerships or acquisitions",
1215
- "Develop new products or services"
1216
- ]
1217
- })
1218
-
1219
- if not improvements:
1220
- return "**IMPROVEMENT PLAN**\n\n✅ **Excellent Performance!** Your financial metrics are strong across all key areas. Focus on maintaining current performance and exploring growth opportunities."
1221
-
1222
- response = "**COMPREHENSIVE IMPROVEMENT PLAN**\n\n"
1223
-
1224
- for i, improvement in enumerate(improvements, 1):
1225
- priority_emoji = "🔴" if improvement["priority"] == "HIGH" else "🟡"
1226
- response += f"**{i}. {improvement['area']} {priority_emoji} {improvement['priority']} PRIORITY**\n\n"
1227
- response += "**Action Items:**\n"
1228
- for action in improvement["actions"]:
1229
- response += f"• {action}\n"
1230
- response += "\n"
1231
-
1232
- response += "**Implementation Timeline:**\n"
1233
- response += "• Month 1-2: Address HIGH priority items\n"
1234
- response += "• Month 3-6: Implement MEDIUM priority initiatives\n"
1235
- response += "• Month 6+: Monitor progress and adjust strategy\n"
1236
-
1237
- return response
1238
-
1239
- def generate_ai_response(user_input, df):
1240
- """Generate AI response based on user input and financial data"""
1241
- current_year = df.iloc[-1]
1242
-
1243
- # Simple keyword-based responses (in a real implementation, this would use an LLM)
1244
- input_lower = user_input.lower()
1245
-
1246
- if any(word in input_lower for word in ['profit', 'margin', 'profitability']):
1247
- net_margin = (current_year['Net_Profit'] / current_year['Revenue']) * 100
1248
- return f"Your current net profit margin is {net_margin:.1f}%. {'This is above industry average' if net_margin >= 10 else 'Consider cost optimization strategies to improve profitability'}. Your net profit for the current year is ${current_year['Net_Profit']:,.0f}."
1249
-
1250
- elif any(word in input_lower for word in ['cash', 'liquidity', 'current ratio']):
1251
- current_ratio = current_year['Current_Assets'] / current_year['Current_Liabilities']
1252
- return f"Your liquidity position shows a current ratio of {current_ratio:.2f}. You have ${current_year['Cash']:,.0f} in cash. {'This indicates strong liquidity' if current_ratio >= 2.0 else 'Consider improving working capital management'}."
1253
-
1254
- elif any(word in input_lower for word in ['debt', 'leverage', 'liability']):
1255
- debt_ratio = current_year['Total_Liabilities'] / current_year['Total_Assets']
1256
- return f"Your debt-to-asset ratio is {debt_ratio:.1%}. Total liabilities are ${current_year['Total_Liabilities']:,.0f}. {'This represents conservative leverage' if debt_ratio <= 0.4 else 'Consider debt reduction strategies' if debt_ratio > 0.6 else 'Moderate leverage levels'}."
1257
-
1258
- elif any(word in input_lower for word in ['growth', 'revenue', 'sales']):
1259
- if len(df) > 1:
1260
- revenue_growth = ((current_year['Revenue'] - df.iloc[-2]['Revenue']) / df.iloc[-2]['Revenue']) * 100
1261
- return f"Your revenue growth is {revenue_growth:.1f}% year-over-year. Current revenue is ${current_year['Revenue']:,.0f}. {'Strong growth performance' if revenue_growth >= 10 else 'Consider growth acceleration strategies' if revenue_growth < 5 else 'Solid growth trajectory'}."
1262
- else:
1263
- return f"Current revenue is ${current_year['Revenue']:,.0f}. I need more historical data to analyze growth trends."
1264
-
1265
- elif any(word in input_lower for word in ['risk', 'warning', 'concern']):
1266
- return identify_top_risks(df)
1267
-
1268
- elif any(word in input_lower for word in ['recommend', 'advice', 'suggest']):
1269
- return create_improvement_plan(df)
1270
-
1271
- else:
1272
- return f"I can help you analyze various aspects of your financial data including profitability, liquidity, growth, and risks. Your key metrics are: Revenue ${current_year['Revenue']:,.0f}, Net Profit ${current_year['Net_Profit']:,.0f}, Total Assets ${current_year['Total_Assets']:,.0f}. What specific area would you like to explore?"
1273
-
1274
- def export_chat_log(chat_history):
1275
- """Export chat history as text"""
1276
- log = f"FINANCEGPT ANALYZER - CHAT LOG\nGenerated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
1277
-
1278
- for i, message in enumerate(chat_history, 1):
1279
- role = "USER" if message['role'] == 'user' else "AI ASSISTANT"
1280
- log += f"{i}. {role}: {message['content']}\n\n"
1281
-
1282
- return log
1283
-
1284
- def generate_ai_report(df):
1285
- """Generate comprehensive AI financial report"""
1286
- current_year = df.iloc[-1]
1287
-
1288
- report = f"""
1289
- AI FINANCIAL ANALYSIS REPORT
1290
- Generated by FinanceGPT Analyzer
1291
- Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
1292
-
1293
- EXECUTIVE SUMMARY
1294
- ================
1295
- Based on analysis of your financial data, here are the key findings:
1296
-
1297
- FINANCIAL OVERVIEW
1298
- - Revenue: ${current_year['Revenue']:,.0f}
1299
- - Net Profit: ${current_year['Net_Profit']:,.0f}
1300
- - Total Assets: ${current_year['Total_Assets']:,.0f}
1301
- - Cash Position: ${current_year['Cash']:,.0f}
1302
-
1303
- PERFORMANCE ANALYSIS
1304
- {analyze_financial_health(df)}
1305
-
1306
- RISK ASSESSMENT
1307
- {identify_top_risks(df)}
1308
-
1309
- INVESTMENT RECOMMENDATION
1310
- {provide_investment_advice(df)}
1311
-
1312
- STRATEGIC RECOMMENDATIONS
1313
- {create_improvement_plan(df)}
1314
-
1315
- ---
1316
- This report is generated by AI and should be reviewed by financial professionals.
1317
- """
1318
-
1319
- return report
1320
-
1321
- if __name__ == "__main__":
1322
  main()
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.express as px
4
+ import plotly.graph_objects as go
5
+ from plotly.subplots import make_subplots
6
+ import numpy as np
7
+ from datetime import datetime
8
+ import io
9
+ import os
10
+
11
+ # Initialize session state
12
+ if 'data_loaded' not in st.session_state:
13
+ st.session_state.data_loaded = False
14
+ if 'analyzer' not in st.session_state:
15
+ st.session_state.analyzer = None
16
+
17
+ # Page configuration
18
+ st.set_page_config(
19
+ page_title="📊 FinanceGPT Analyzer",
20
+ page_icon="📊",
21
+ layout="wide",
22
+ initial_sidebar_state="expanded"
23
+ )
24
+
25
+ # Custom CSS for better styling
26
+ st.markdown("""
27
+ <style>
28
+ .metric-card {
29
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
30
+ padding: 1rem;
31
+ border-radius: 10px;
32
+ color: white;
33
+ text-align: center;
34
+ margin: 0.5rem 0;
35
+ }
36
+ .insight-box {
37
+ background: #f8f9fa;
38
+ padding: 1rem;
39
+ border-left: 4px solid #007bff;
40
+ border-radius: 5px;
41
+ margin: 1rem 0;
42
+ }
43
+ .warning-box {
44
+ background: #fff3cd;
45
+ padding: 1rem;
46
+ border-left: 4px solid #ffc107;
47
+ border-radius: 5px;
48
+ margin: 1rem 0;
49
+ }
50
+ </style>
51
+ """, unsafe_allow_html=True)
52
+
53
+ class FinanceAnalyzer:
54
+ def __init__(self):
55
+ self.data = None
56
+ self.processed_data = {}
57
+
58
+ def load_csv_data(self):
59
+ """Load CSV data from local file"""
60
+ try:
61
+ # Try to load from data directory first
62
+ csv_path = os.path.join(os.path.dirname(__file__), 'data', '2024.csv')
63
+ if os.path.exists(csv_path):
64
+ df = pd.read_csv(csv_path)
65
+ return df
66
+ else:
67
+ # Fallback to sample data if file not found
68
+ return self.load_sample_data()
69
+ except Exception as e:
70
+ st.error(f"Error loading CSV file: {e}")
71
+ return self.load_sample_data()
72
+
73
+ def load_sample_data(self):
74
+ """Load sample financial data"""
75
+ sample_data = {
76
+ 'Year': [2024, 2024, 2024, 2024, 2024, 2024, 2024, 2024, 2024, 2024,
77
+ 2023, 2023, 2023, 2023, 2023, 2023, 2023, 2023, 2023, 2023],
78
+ 'Statement_Type': ['Income Statement'] * 10 + ['Income Statement'] * 10,
79
+ 'Account_Name_Norwegian': ['Salgsinntekt', 'Varekostnad', 'Bruttoresultat', 'Lønnskostnad',
80
+ 'Andre driftskostnader', 'Driftsresultat', 'Finansinntekter',
81
+ 'Finanskostnader', 'Ordinært resultat før skatt', 'Årsresultat'] * 2,
82
+ 'Account_Name_English': ['Sales Revenue', 'Cost of Goods Sold', 'Gross Profit', 'Salary Costs',
83
+ 'Other Operating Expenses', 'Operating Result', 'Financial Income',
84
+ 'Financial Expenses', 'Profit Before Tax', 'Net Profit'] * 2,
85
+ '2024_Amount_NOK': [25107008, -15064205, 10042803, -3521456, -1987234, 4534113, 123456,
86
+ -234567, 4422002, 3537602, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
87
+ '2023_Amount_NOK': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4891891, -2934535, 1957356, -1234567,
88
+ -654321, 68468, 45678, -123456, -9310, -7448]
89
+ }
90
+ return pd.DataFrame(sample_data)
91
+
92
+ def process_financial_data(self, df):
93
+ """Process uploaded financial data"""
94
+ self.data = df
95
+
96
+ # Add Year column if not present
97
+ if 'Year' not in df.columns:
98
+ # Create year based on data structure
99
+ df = df.copy()
100
+ df['Year'] = 2024 # Default to 2024
101
+
102
+ # Create pivot tables for easier analysis
103
+ try:
104
+ # Handle different data structures
105
+ if '2024_Amount_NOK' in df.columns and '2023_Amount_NOK' in df.columns:
106
+ # Original structure
107
+ revenue_accounts = df[df['Account_Name_English'].str.contains('Sales Revenue|Revenue', case=False, na=False)]
108
+ profit_accounts = df[df['Account_Name_English'].str.contains('Annual Result|Net Profit', case=False, na=False)]
109
+ cogs_accounts = df[df['Account_Name_English'].str.contains('Cost of Goods', case=False, na=False)]
110
+ operating_accounts = df[df['Account_Name_English'].str.contains('Operating Result', case=False, na=False)]
111
+
112
+ self.processed_data = {
113
+ 'revenue_2024': revenue_accounts['2024_Amount_NOK'].iloc[0] if len(revenue_accounts) > 0 else 0,
114
+ 'revenue_2023': revenue_accounts['2023_Amount_NOK'].iloc[0] if len(revenue_accounts) > 0 else 0,
115
+ 'net_profit_2024': profit_accounts['2024_Amount_NOK'].iloc[0] if len(profit_accounts) > 0 else 0,
116
+ 'net_profit_2023': profit_accounts['2023_Amount_NOK'].iloc[0] if len(profit_accounts) > 0 else 0,
117
+ 'cogs_2024': abs(cogs_accounts['2024_Amount_NOK'].iloc[0]) if len(cogs_accounts) > 0 else 0,
118
+ 'cogs_2023': abs(cogs_accounts['2023_Amount_NOK'].iloc[0]) if len(cogs_accounts) > 0 else 0,
119
+ 'operating_profit_2024': operating_accounts['2024_Amount_NOK'].iloc[0] if len(operating_accounts) > 0 else 0,
120
+ 'operating_profit_2023': operating_accounts['2023_Amount_NOK'].iloc[0] if len(operating_accounts) > 0 else 0,
121
+ }
122
+ else:
123
+ # Fallback for different structures
124
+ self.processed_data = {
125
+ 'revenue_2024': 25107008,
126
+ 'revenue_2023': 4891891,
127
+ 'net_profit_2024': 5313634,
128
+ 'net_profit_2023': -3940,
129
+ 'cogs_2024': 9880032,
130
+ 'cogs_2023': 770840,
131
+ 'operating_profit_2024': 6854887,
132
+ 'operating_profit_2023': 87697,
133
+ }
134
+ except Exception as e:
135
+ st.warning(f"Error processing data: {e}. Using default values.")
136
+ self.processed_data = {
137
+ 'revenue_2024': 25107008,
138
+ 'revenue_2023': 4891891,
139
+ 'net_profit_2024': 5313634,
140
+ 'net_profit_2023': -3940,
141
+ 'cogs_2024': 9880032,
142
+ 'cogs_2023': 770840,
143
+ 'operating_profit_2024': 6854887,
144
+ 'operating_profit_2023': 87697,
145
+ }
146
+
147
+ def calculate_metrics(self):
148
+ """Calculate key financial metrics"""
149
+ if not self.processed_data:
150
+ return {}
151
+
152
+ data = self.processed_data
153
+
154
+ # Growth rates
155
+ revenue_growth = ((data['revenue_2024'] - data['revenue_2023']) /
156
+ abs(data['revenue_2023']) * 100) if data['revenue_2023'] != 0 else 0
157
+
158
+ # Profitability ratios
159
+ gross_margin_2024 = ((data['revenue_2024'] - data['cogs_2024']) /
160
+ data['revenue_2024'] * 100) if data['revenue_2024'] != 0 else 0
161
+ net_margin_2024 = (data['net_profit_2024'] / data['revenue_2024'] * 100) if data['revenue_2024'] != 0 else 0
162
+
163
+ return {
164
+ 'revenue_growth': revenue_growth,
165
+ 'gross_margin_2024': gross_margin_2024,
166
+ 'net_margin_2024': net_margin_2024,
167
+ 'revenue_2024_m': data['revenue_2024'] / 1000000,
168
+ 'net_profit_2024_m': data['net_profit_2024'] / 1000000,
169
+ }
170
+
171
+ def create_revenue_trend_chart(self):
172
+ """Create revenue trend visualization"""
173
+ if not self.processed_data:
174
+ return go.Figure()
175
+
176
+ fig = go.Figure()
177
+
178
+ years = [2023, 2024]
179
+ revenues = [self.processed_data['revenue_2023']/1000000,
180
+ self.processed_data['revenue_2024']/1000000]
181
+ net_profits = [self.processed_data['net_profit_2023']/1000000,
182
+ self.processed_data['net_profit_2024']/1000000]
183
+
184
+ fig.add_trace(go.Scatter(x=years, y=revenues, mode='lines+markers',
185
+ name='Revenue (M NOK)', line=dict(color='#1f77b4', width=3)))
186
+ fig.add_trace(go.Scatter(x=years, y=net_profits, mode='lines+markers',
187
+ name='Net Profit (M NOK)', line=dict(color='#ff7f0e', width=3)))
188
+
189
+ fig.update_layout(title='Revenue vs Profit Trend', xaxis_title='Year',
190
+ yaxis_title='Amount (M NOK)', height=400)
191
+ return fig
192
+
193
+ def create_financial_health_radar(self):
194
+ """Create financial health radar chart"""
195
+ metrics = self.calculate_metrics()
196
+
197
+ categories = ['Revenue Growth', 'Gross Margin', 'Net Margin', 'Profitability', 'Efficiency']
198
+ values = [
199
+ min(metrics.get('revenue_growth', 0) / 5, 100), # Scale revenue growth
200
+ metrics.get('gross_margin_2024', 0),
201
+ max(metrics.get('net_margin_2024', 0), 0),
202
+ 70, # Sample value
203
+ 65 # Sample value
204
+ ]
205
+
206
+ fig = go.Figure()
207
+ fig.add_trace(go.Scatterpolar(
208
+ r=values,
209
+ theta=categories,
210
+ fill='toself',
211
+ name='Financial Health'
212
+ ))
213
+
214
+ fig.update_layout(
215
+ polar=dict(
216
+ radialaxis=dict(visible=True, range=[0, 100])
217
+ ),
218
+ title="Financial Health Score",
219
+ height=400
220
+ )
221
+ return fig
222
+
223
+ def main():
224
+ st.title("📊 FinanceGPT Analyzer")
225
+ st.markdown("### Professional Financial Analysis Dashboard")
226
+
227
+ # Initialize analyzer
228
+ if st.session_state.analyzer is None:
229
+ st.session_state.analyzer = FinanceAnalyzer()
230
+
231
+ analyzer = st.session_state.analyzer
232
+
233
+ # Sidebar navigation
234
+ with st.sidebar:
235
+ st.header("Navigation")
236
+ page = st.selectbox("Choose Analysis Page", [
237
+ "🏠 Dashboard",
238
+ "💰 Income Analysis",
239
+ "🏛️ Balance Sheet Analysis",
240
+ "💸 Cash Flow Analysis",
241
+ "📊 Financial Ratios Hub",
242
+ "🤖 AI Finance Assistant"
243
+ ])
244
+
245
+ st.header("Data Upload")
246
+ uploaded_file = st.file_uploader("Upload CSV file", type=['csv'])
247
+
248
+ if st.button("Load CSV Data"):
249
+ try:
250
+ df = analyzer.load_csv_data()
251
+ analyzer.process_financial_data(df)
252
+ st.session_state.data_loaded = True
253
+ st.success("CSV data loaded successfully!")
254
+ st.rerun()
255
+ except Exception as e:
256
+ st.error(f"Error loading CSV data: {e}")
257
+
258
+ if st.button("Use Sample Data"):
259
+ analyzer.data = analyzer.load_sample_data()
260
+ analyzer.process_financial_data(analyzer.data)
261
+ st.session_state.data_loaded = True
262
+ st.success("Sample data loaded!")
263
+ st.rerun()
264
+
265
+ if uploaded_file is not None:
266
+ try:
267
+ # Reset file pointer to beginning
268
+ uploaded_file.seek(0)
269
+ # Read CSV directly from the uploaded file object
270
+ df = pd.read_csv(uploaded_file)
271
+
272
+ analyzer.data = df
273
+ analyzer.process_financial_data(df)
274
+ st.session_state.data_loaded = True
275
+ st.success("Data uploaded successfully!")
276
+ st.rerun()
277
+ except Exception as e:
278
+ st.error(f"Error loading file: {e}")
279
+ st.info("Please ensure your CSV file has the correct format with columns: Year, Statement_Type, Account_Name_Norwegian, Account_Name_English, 2024_Amount_NOK, 2023_Amount_NOK")
280
+
281
+ # Main content based on selected page
282
+ if page == "🏠 Dashboard":
283
+ dashboard_page(analyzer)
284
+ elif page == "💰 Income Analysis":
285
+ income_analysis_page(analyzer)
286
+ elif page == "🏛️ Balance Sheet Analysis":
287
+ balance_sheet_page(analyzer)
288
+ elif page == "💸 Cash Flow Analysis":
289
+ cash_flow_page(analyzer)
290
+ elif page == "📊 Financial Ratios Hub":
291
+ ratios_page(analyzer)
292
+ elif page == "🤖 AI Finance Assistant":
293
+ ai_assistant_page(analyzer)
294
+
295
+ def dashboard_page(analyzer):
296
+ """Main dashboard page"""
297
+ st.header("📊 Financial Dashboard")
298
+
299
+ if analyzer.data is None:
300
+ st.warning("Please upload data or use sample data to begin analysis.")
301
+ return
302
+
303
+ metrics = analyzer.calculate_metrics()
304
+
305
+ # Key metrics cards
306
+ col1, col2, col3, col4 = st.columns(4)
307
+
308
+ with col1:
309
+ st.markdown("""
310
+ <div class="metric-card">
311
+ <h3>💰 Revenue</h3>
312
+ <h2>{:.1f}M NOK</h2>
313
+ <p>+{:.0f}% 🔥</p>
314
+ </div>
315
+ """.format(metrics.get('revenue_2024_m', 0), metrics.get('revenue_growth', 0)),
316
+ unsafe_allow_html=True)
317
+
318
+ with col2:
319
+ st.markdown("""
320
+ <div class="metric-card">
321
+ <h3>📈 Net Profit</h3>
322
+ <h2>{:.1f}M NOK</h2>
323
+ <p>Profitable ✅</p>
324
+ </div>
325
+ """.format(metrics.get('net_profit_2024_m', 0)), unsafe_allow_html=True)
326
+
327
+ with col3:
328
+ st.markdown("""
329
+ <div class="metric-card">
330
+ <h3>📊 Gross Margin</h3>
331
+ <h2>{:.1f}%</h2>
332
+ <p>Healthy 💪</p>
333
+ </div>
334
+ """.format(metrics.get('gross_margin_2024', 0)), unsafe_allow_html=True)
335
+
336
+ with col4:
337
+ st.markdown("""
338
+ <div class="metric-card">
339
+ <h3>🎯 Net Margin</h3>
340
+ <h2>{:.1f}%</h2>
341
+ <p>Strong 📈</p>
342
+ </div>
343
+ """.format(metrics.get('net_margin_2024', 0)), unsafe_allow_html=True)
344
+
345
+ # Charts section
346
+ col1, col2 = st.columns(2)
347
+
348
+ with col1:
349
+ st.plotly_chart(analyzer.create_revenue_trend_chart(), use_container_width=True)
350
+
351
+ with col2:
352
+ st.plotly_chart(analyzer.create_financial_health_radar(), use_container_width=True)
353
+
354
+ # Quick insights
355
+ st.markdown("""
356
+ <div class="insight-box">
357
+ <h4>🎯 Quick Insights</h4>
358
+ <ul>
359
+ <li>✅ Revenue growth of {:.0f}% indicates explosive business development</li>
360
+ <li>💡 Net profit margin of {:.1f}% shows strong profitability</li>
361
+ <li>📈 Gross margin of {:.1f}% demonstrates healthy pricing power</li>
362
+ </ul>
363
+ </div>
364
+ """.format(
365
+ metrics.get('revenue_growth', 0),
366
+ metrics.get('net_margin_2024', 0),
367
+ metrics.get('gross_margin_2024', 0)
368
+ ), unsafe_allow_html=True)
369
+
370
+ def income_analysis_page(analyzer):
371
+ """Income statement analysis page"""
372
+ st.header("💰 Income Analysis")
373
+
374
+ if analyzer.data is None:
375
+ st.warning("Please upload data to begin analysis.")
376
+ return
377
+
378
+ # Revenue analysis
379
+ st.subheader("📈 Revenue Trend Analysis")
380
+ st.plotly_chart(analyzer.create_revenue_trend_chart(), use_container_width=True)
381
+
382
+ # Cost structure
383
+ st.subheader("🥧 Cost Structure Analysis")
384
+ if analyzer.processed_data:
385
+ data = analyzer.processed_data
386
+ costs = ['Cost of Goods Sold', 'Operating Expenses', 'Financial Expenses']
387
+ values = [data['cogs_2024'], 2000000, 234567] # Sample values
388
+
389
+ fig = px.pie(values=values, names=costs, title="Cost Breakdown 2024")
390
+ st.plotly_chart(fig, use_container_width=True)
391
+
392
+ # Profitability metrics
393
+ st.subheader("📊 Profitability Indicators")
394
+ metrics = analyzer.calculate_metrics()
395
+
396
+ col1, col2, col3 = st.columns(3)
397
+ with col1:
398
+ st.metric("Gross Margin", f"{metrics.get('gross_margin_2024', 0):.1f}%")
399
+ with col2:
400
+ st.metric("Net Margin", f"{metrics.get('net_margin_2024', 0):.1f}%")
401
+ with col3:
402
+ st.metric("Revenue Growth", f"{metrics.get('revenue_growth', 0):.1f}%")
403
+
404
+ def balance_sheet_page(analyzer):
405
+ """Balance sheet analysis page"""
406
+ st.header("🏛️ Balance Sheet Analysis")
407
+
408
+ if analyzer.data is None:
409
+ st.warning("Please upload balance sheet data to begin analysis.")
410
+ return
411
+
412
+ st.info("Balance sheet analysis requires additional data. Please upload complete financial statements.")
413
+
414
+ # Sample asset structure chart
415
+ assets = ['Current Assets', 'Fixed Assets', 'Intangible Assets']
416
+ values = [45, 35, 20]
417
+
418
+ fig = px.pie(values=values, names=assets, title="Asset Structure")
419
+ st.plotly_chart(fig, use_container_width=True)
420
+
421
+ def cash_flow_page(analyzer):
422
+ """Cash flow analysis page"""
423
+ st.header("💸 Cash Flow Analysis")
424
+
425
+ if analyzer.data is None:
426
+ st.warning("Please upload cash flow data to begin analysis.")
427
+ return
428
+
429
+ st.info("Cash flow analysis requires additional data. Please upload complete cash flow statements.")
430
+
431
+ # Sample cash flow chart
432
+ categories = ['Operating CF', 'Investing CF', 'Financing CF']
433
+ values = [5000000, -2000000, -1000000]
434
+
435
+ fig = go.Figure(go.Waterfall(
436
+ name="Cash Flow", orientation="v",
437
+ measure=["relative", "relative", "relative"],
438
+ x=categories, y=values,
439
+ text=[f"{v/1000000:.1f}M" for v in values]
440
+ ))
441
+ fig.update_layout(title="Cash Flow Waterfall")
442
+ st.plotly_chart(fig, use_container_width=True)
443
+
444
+ def ratios_page(analyzer):
445
+ """Financial ratios analysis page"""
446
+ st.header("📊 Financial Ratios Hub")
447
+
448
+ if analyzer.data is None:
449
+ st.warning("Please upload data to calculate ratios.")
450
+ return
451
+
452
+ # Ratio categories
453
+ col1, col2, col3, col4 = st.columns(4)
454
+
455
+ with col1:
456
+ if st.button("Profitability"):
457
+ st.session_state.ratio_category = "profitability"
458
+ with col2:
459
+ if st.button("Liquidity"):
460
+ st.session_state.ratio_category = "liquidity"
461
+ with col3:
462
+ if st.button("Efficiency"):
463
+ st.session_state.ratio_category = "efficiency"
464
+ with col4:
465
+ if st.button("Growth"):
466
+ st.session_state.ratio_category = "growth"
467
+
468
+ # Display ratios based on selection
469
+ metrics = analyzer.calculate_metrics()
470
+
471
+ st.subheader("Key Financial Ratios")
472
+
473
+ col1, col2, col3 = st.columns(3)
474
+ with col1:
475
+ st.metric("Gross Profit Margin", f"{metrics.get('gross_margin_2024', 0):.1f}%", "A+")
476
+ with col2:
477
+ st.metric("Net Profit Margin", f"{metrics.get('net_margin_2024', 0):.1f}%", "A")
478
+ with col3:
479
+ st.metric("Revenue Growth", f"{metrics.get('revenue_growth', 0):.1f}%", "A+")
480
+
481
+ def ai_assistant_page(analyzer):
482
+ """AI finance assistant page"""
483
+ st.header("🤖 AI Finance Assistant")
484
+
485
+ if analyzer.data is None:
486
+ st.warning("Please upload data to enable AI analysis.")
487
+ return
488
+
489
+ # Chat interface
490
+ st.subheader("💬 Ask Your Financial Questions")
491
+
492
+ # Predefined questions
493
+ col1, col2 = st.columns(2)
494
+ with col1:
495
+ if st.button("Analyze my financial health"):
496
+ st.session_state.ai_query = "financial_health"
497
+ if st.button("Find the biggest risks"):
498
+ st.session_state.ai_query = "risks"
499
+
500
+ with col2:
501
+ if st.button("Give investment advice"):
502
+ st.session_state.ai_query = "investment"
503
+ if st.button("Create improvement plan"):
504
+ st.session_state.ai_query = "improvement"
505
+
506
+ # Text input for custom questions
507
+ user_question = st.text_input("Or ask your own question:")
508
+
509
+ if user_question or 'ai_query' in st.session_state:
510
+ metrics = analyzer.calculate_metrics()
511
+
512
+ # Simple AI-like responses based on data
513
+ if user_question or st.session_state.get('ai_query') == 'financial_health':
514
+ st.markdown("""
515
+ <div class="insight-box">
516
+ <h4>🎯 Financial Health Analysis</h4>
517
+ <p>Based on your financial data:</p>
518
+ <ul>
519
+ <li>✅ <strong>Revenue Growth:</strong> {:.0f}% growth shows strong market performance</li>
520
+ <li>✅ <strong>Profitability:</strong> {:.1f}% net margin indicates healthy operations</li>
521
+ <li>📊 <strong>Overall Rating:</strong> A- (Strong financial position)</li>
522
+ </ul>
523
+ </div>
524
+ """.format(
525
+ metrics.get('revenue_growth', 0),
526
+ metrics.get('net_margin_2024', 0)
527
+ ), unsafe_allow_html=True)
528
+
529
+ # Clear the session state
530
+ if 'ai_query' in st.session_state:
531
+ del st.session_state.ai_query
532
+
533
+ if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
  main()