entropy25 commited on
Commit
1ab8d86
·
verified ·
1 Parent(s): 5402969

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +655 -824
app.py CHANGED
@@ -7,882 +7,713 @@ import numpy as np
7
  from datetime import datetime
8
  import io
9
 
10
- # Page config
11
  st.set_page_config(
12
  page_title="FinanceGPT Analyzer",
13
  page_icon="📊",
14
- layout="wide",
15
- initial_sidebar_state="expanded"
16
  )
17
 
18
- # Custom CSS
19
  st.markdown("""
20
  <style>
21
  .metric-card {
22
- background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
23
  padding: 1rem;
24
  border-radius: 10px;
25
  color: white;
26
  text-align: center;
27
- margin: 0.5rem 0;
28
  }
29
  .insight-box {
30
  background: #f8f9fa;
31
- border-left: 4px solid #007bff;
32
  padding: 1rem;
33
  margin: 1rem 0;
34
- border-radius: 5px;
35
  }
36
- .risk-high { border-left-color: #dc3545; }
37
- .risk-medium { border-left-color: #ffc107; }
38
- .risk-low { border-left-color: #28a745; }
39
- .stTab {
40
- background-color: white;
41
- }
42
- .chat-message {
43
  padding: 1rem;
44
- margin: 0.5rem 0;
45
- border-radius: 10px;
46
- background-color: #f0f2f6;
47
  }
48
  </style>
49
  """, unsafe_allow_html=True)
50
 
51
- # Sample data (real Norwegian company data)
52
- @st.cache_data
53
- def get_sample_data():
54
- data = {
55
- 'Year': [2024] * 70,
56
- 'Statement_Type': (['Income Statement'] * 20 + ['Balance Sheet'] * 46 + ['Additional Info'] * 1 + ['Cash Flow Statement'] * 23),
57
- 'Account_Name_Norwegian': [
58
- 'Salgsinntekt', 'Sum inntekter', 'Varekostnad', 'Lønnskostnad', 'Avskrivning på varige driftsmidler og immaterielle eiendeler',
59
- 'Annen driftskostnad', 'Sum kostnader', 'Driftsresultat', 'Annen renteinntekt', 'Annen finansinntekt',
60
- 'Sum finansinntekter', 'Annen rentekostnad', 'Annen finanskostnad', 'Sum finanskostnader', 'Netto finans',
61
- 'Resultat før skattekostnad', 'Skattekostnad', 'Årsresultat', 'Overføringer til/fra annen egenkapital', 'Sum overføringer og disponeringer'
62
- ] + [
63
- 'Tomter bygninger og annen fast eiendom', 'Maskiner og anlegg', 'Driftsløsøre inventar verktøy kontormaskiner og lignende',
64
- 'Sum varige driftsmidler', 'Andre fordringer', 'Sum finansielle anleggsmidler', 'Sum anleggsmidler',
65
- 'Kundefordringer', 'Andre fordringer', 'Sum fordringer', 'Bankinnskudd kontanter og lignende',
66
- 'Sum bankinnskudd kontanter og lignende', 'Sum omløpsmidler', 'SUM EIENDELER', 'Selskapskapital',
67
- 'Sum innskutt egenkapital', 'Annen egenkapital', 'Sum opptjent egenkapital', 'Sum egenkapital',
68
- 'Utsatt skatt', 'Sum avsetninger for forpliktelser', 'Gjeld til kredittinstitusjoner', 'Øvrig langsiktig gjeld',
69
- 'Sum annen langsiktig gjeld', 'Sum langsiktig gjeld', 'Leverandørgjeld', 'Betalbar skatt',
70
- 'Skyldige offentlige avgifter', 'Annen kortsiktig gjeld', 'Sum kortsiktig gjeld', 'Sum gjeld',
71
- 'SUM EGENKAPITAL OG GJELD'
72
- ] + ['Antall årsverk i regnskapsåret'] + [
73
- 'Årsresultat', 'Avskrivninger', 'Endring i utsatt skatt', 'Endring i kundefordringer', 'Endring i andre fordringer',
74
- 'Endring i leverandørgjeld', 'Endring i betalbar skatt', 'Endring i skyldige offentlige avgifter', 'Endring i annen kortsiktig gjeld',
75
- 'Netto kontantstrøm fra driftsaktiviteter', 'Kjøp av varige driftsmidler', 'Endring i finansielle anleggsmidler',
76
- 'Netto kontantstrøm fra investeringsaktiviteter', 'Endring i langsiktig gjeld til kredittinstitusjoner', 'Endring i øvrig langsiktig gjeld',
77
- 'Netto kontantstrøm fra finansieringsaktiviteter', 'NETTO ENDRING I KONTANTER', 'Kontanter ved periodens begynnelse',
78
- 'Kontanter ved periodens slutt', 'Kontroll mot balanse', 'Differanse'
79
- ],
80
- 'Account_Name_English': [
81
- 'Sales Revenue', 'Total Income', 'Cost of Goods Sold', 'Payroll Expenses', 'Depreciation on Fixed Assets and Intangible Assets',
82
- 'Other Operating Expenses', 'Total Expenses', 'Operating Result', 'Other Interest Income', 'Other Financial Income',
83
- 'Total Financial Income', 'Other Interest Expenses', 'Other Financial Expenses', 'Total Financial Expenses', 'Net Financial Result',
84
- 'Result Before Tax', 'Tax Expense', 'Annual Result', 'Transfers to/from Other Equity', 'Total Transfers and Allocations'
85
- ] + [
86
- 'Land Buildings and Other Real Estate', 'Machinery and Equipment', 'Operating Equipment Inventory Tools Office Machines etc',
87
- 'Total Fixed Assets', 'Other Receivables', 'Total Financial Fixed Assets', 'Total Fixed Assets',
88
- 'Customer Receivables', 'Other Receivables', 'Total Receivables', 'Bank Deposits Cash and Similar',
89
- 'Total Bank Deposits Cash and Similar', 'Total Current Assets', 'TOTAL ASSETS', 'Share Capital',
90
- 'Total Paid-in Capital', 'Other Equity', 'Total Retained Earnings', 'Total Equity',
91
- 'Deferred Tax', 'Total Provisions for Liabilities', 'Debt to Credit Institutions', 'Other Long-term Debt',
92
- 'Total Other Long-term Debt', 'Total Long-term Debt', 'Accounts Payable', 'Payable Tax',
93
- 'Public Charges Payable', 'Other Short-term Debt', 'Total Short-term Debt', 'Total Debt',
94
- 'TOTAL EQUITY AND DEBT'
95
- ] + ['Number of Full-time Employees'] + [
96
- 'Net Income', 'Depreciation', 'Change in Deferred Tax', 'Change in Customer Receivables', 'Change in Other Receivables',
97
- 'Change in Accounts Payable', 'Change in Payable Tax', 'Change in Public Charges Payable', 'Change in Other Short-term Debt',
98
- 'Net Cash Flow from Operating Activities', 'Purchase of Fixed Assets', 'Change in Financial Fixed Assets',
99
- 'Net Cash Flow from Investing Activities', 'Change in Long-term Debt to Credit Institutions', 'Change in Other Long-term Debt',
100
- 'Net Cash Flow from Financing Activities', 'NET CHANGE IN CASH', 'Cash at Beginning of Period',
101
- 'Cash at End of Period', 'Control vs Balance Sheet', 'Difference'
102
- ],
103
- '2024_Amount_NOK': [
104
- 25107008, 25107008, 9880032, 3700289, 316180, 4355621, 18252121, 6854887, 11439, 1230,
105
- 12669, 51288, 3916, 55205, -42536, 6812351, 1498717, 5313634, 5313634, 5313634,
106
- 394022, 928281, 1010616, 2332919, 1949477, 1949477, 4282396, 5575707, 178797, 5754504,
107
- 1595549, 1595549, 7350053, 11632449, 30000, 30000, 5572404, 5572404, 5602404,
108
- 89409, 89409, 364050, 200000, 564050, 653459, 3162252, 1421220, 526789, 266325,
109
- 5376586, 6030045, 11632449, 7, 5313634, 316180, 60522, -3575556, 54597,
110
- 1860815, 1438195, 17187, -1099762, 3385812, -1885519, -1660609, -3546128, -37736, 0,
111
- -37736, 801948, 793599, 1595549, 1595549, 0
112
- ],
113
- '2023_Amount_NOK': [
114
- 4891891, 4891891, 770840, 2703253, 0, 1330101, 4804194, 87697, 385, 0,
115
- 385, 59498, 0, 59498, -59113, 28584, 32524, -3940, -3940, -3940,
116
- 0, 334817, 428763, 763580, 288868, 288868, 1052447, 2000151, 233394, 2233546,
117
- 793599, 793599, 3027145, 4079592, 30000, 30000, 258770, 258770, 288770,
118
- 28887, 28887, 401786, 200000, 601786, 630673, 1301437, -16975, 509602, 1366087,
119
- 3160150, 3790823, 4079592, 0, -3940, 0, 28887, -2000151, -233394,
120
- 1301437, -16975, 509602, 1366087, 951553, -763580, -288868, -1052448, 401786, 200000,
121
- 601786, 500891, 292708, 793599, 793599, 0
122
- ]
123
- }
124
- return pd.DataFrame(data)
125
-
126
- # Data processing functions
127
- def get_account_value(df, english_name, year='2024'):
128
- column = f'{year}_Amount_NOK'
129
- try:
130
- result = df[df['Account_Name_English'] == english_name][column]
131
- return result.iloc[0] if len(result) > 0 else 0
132
- except:
133
- return 0
134
-
135
- def calculate_ratios(df):
136
- ratios = {}
137
-
138
- # Get key financial figures
139
- revenue = get_account_value(df, 'Sales Revenue', '2024')
140
- revenue_prev = get_account_value(df, 'Sales Revenue', '2023')
141
- net_income = get_account_value(df, 'Annual Result', '2024')
142
- net_income_prev = get_account_value(df, 'Annual Result', '2023')
143
- total_assets = get_account_value(df, 'TOTAL ASSETS', '2024')
144
- total_assets_prev = get_account_value(df, 'TOTAL ASSETS', '2023')
145
- current_assets = get_account_value(df, 'Total Current Assets', '2024')
146
- current_liabilities = get_account_value(df, 'Total Short-term Debt', '2024')
147
- total_debt = get_account_value(df, 'Total Debt', '2024')
148
- total_equity = get_account_value(df, 'Total Equity', '2024')
149
- cogs = get_account_value(df, 'Cost of Goods Sold', '2024')
150
- operating_result = get_account_value(df, 'Operating Result', '2024')
151
-
152
- # Calculate ratios with error handling
153
- ratios['Revenue Growth'] = ((revenue - revenue_prev) / revenue_prev * 100) if revenue_prev != 0 else 0
154
- ratios['Net Margin'] = (net_income / revenue * 100) if revenue != 0 else 0
155
- ratios['Operating Margin'] = (operating_result / revenue * 100) if revenue != 0 else 0
156
- ratios['ROA'] = (net_income / total_assets * 100) if total_assets != 0 else 0
157
- ratios['ROE'] = (net_income / total_equity * 100) if total_equity != 0 else 0
158
- ratios['Current Ratio'] = (current_assets / current_liabilities) if current_liabilities != 0 else 0
159
- ratios['Debt to Equity'] = (total_debt / total_equity) if total_equity != 0 else 0
160
- ratios['Debt Ratio'] = (total_debt / total_assets * 100) if total_assets != 0 else 0
161
- ratios['Gross Margin'] = ((revenue - cogs) / revenue * 100) if revenue != 0 else 0
162
- ratios['Asset Turnover'] = (revenue / total_assets) if total_assets != 0 else 0
163
-
164
- return ratios
165
-
166
- def get_ratio_grade(ratio_name, value):
167
- grades = {
168
- 'Revenue Growth': {'A': 20, 'B': 10, 'C': 5, 'D': 0},
169
- 'Net Margin': {'A': 15, 'B': 10, 'C': 5, 'D': 0},
170
- 'Operating Margin': {'A': 20, 'B': 15, 'C': 10, 'D': 5},
171
- 'ROA': {'A': 15, 'B': 10, 'C': 5, 'D': 0},
172
- 'ROE': {'A': 20, 'B': 15, 'C': 10, 'D': 0},
173
- 'Current Ratio': {'A': 2.0, 'B': 1.5, 'C': 1.2, 'D': 1.0},
174
- 'Debt Ratio': {'A': 30, 'B': 50, 'C': 70, 'D': 100},
175
- 'Debt to Equity': {'A': 0.5, 'B': 1.0, 'C': 1.5, 'D': 2.0},
176
- 'Gross Margin': {'A': 50, 'B': 30, 'C': 20, 'D': 10}
177
- }
178
-
179
- if ratio_name not in grades:
180
- return 'N/A'
181
-
182
- thresholds = grades[ratio_name]
183
- if ratio_name in ['Debt Ratio', 'Debt to Equity']: # Lower is better
184
- if value <= thresholds['A']: return 'A'
185
- elif value <= thresholds['B']: return 'B'
186
- elif value <= thresholds['C']: return 'C'
187
- else: return 'D'
188
- else: # Higher is better
189
- if value >= thresholds['A']: return 'A'
190
- elif value >= thresholds['B']: return 'B'
191
- elif value >= thresholds['C']: return 'C'
192
- else: return 'D'
193
-
194
- def generate_insights(df, ratios):
195
- insights = []
196
-
197
- revenue_growth = ratios['Revenue Growth']
198
- if revenue_growth > 400:
199
- insights.append(("🚀 Explosive Growth", f"Revenue grew {revenue_growth:.0f}% - exceptional performance!", "success"))
200
- elif revenue_growth > 50:
201
- insights.append(("📈 Strong Growth", f"Revenue increased {revenue_growth:.1f}% year-over-year", "success"))
202
-
203
- if ratios['Current Ratio'] < 1.0:
204
- insights.append(("⚠️ Liquidity Risk", "Current ratio below 1.0 indicates potential cash flow issues", "warning"))
205
- elif ratios['Current Ratio'] < 1.5:
206
- insights.append(("⚠️ Liquidity Watch", f"Current ratio of {ratios['Current Ratio']:.1f} is below optimal", "warning"))
207
-
208
- if ratios['Debt Ratio'] > 70:
209
- insights.append(("🔴 High Leverage", "Debt ratio above 70% suggests high financial risk", "error"))
210
- elif ratios['Debt Ratio'] > 50:
211
- insights.append(("⚠️ Moderate Leverage", f"Debt ratio of {ratios['Debt Ratio']:.1f}% requires monitoring", "warning"))
212
-
213
- # Customer receivables analysis
214
- receivables = get_account_value(df, 'Customer Receivables', '2024')
215
- revenue = get_account_value(df, 'Sales Revenue', '2024')
216
- if revenue > 0 and (receivables / revenue) > 0.2:
217
- insights.append(("💳 Receivables Risk", f"Customer receivables is {receivables/1000000:.1f}M NOK ({receivables/revenue*100:.0f}% of revenue)", "warning"))
218
-
219
- if ratios['Net Margin'] > 20:
220
- insights.append(("💰 Excellent Profitability", f"Net margin of {ratios['Net Margin']:.1f}% shows excellent profitability", "success"))
221
- elif ratios['Net Margin'] > 10:
222
- insights.append(("💰 Good Profitability", f"Net margin of {ratios['Net Margin']:.1f}% shows good profitability", "success"))
223
-
224
- # Turnaround story
225
- net_prev = get_account_value(df, 'Annual Result', '2023')
226
- net_current = get_account_value(df, 'Annual Result', '2024')
227
- if net_prev < 0 and net_current > 0:
228
- insights.append(("🔄 Successful Turnaround", "Company moved from loss to profit - remarkable recovery!", "success"))
229
-
230
- return insights
231
-
232
- # Sidebar navigation
233
- st.sidebar.title("📊 FinanceGPT Analyzer")
234
- page = st.sidebar.selectbox("Choose Analysis", [
235
- "🏠 Dashboard",
236
- "💰 Income Analysis",
237
- "🏛️ Balance Sheet",
238
- "💸 Cash Flow",
239
- "📊 Financial Ratios",
240
- "🤖 AI Assistant"
241
- ])
242
-
243
- # File upload
244
- st.sidebar.subheader("📁 Data Upload")
245
- uploaded_file = st.sidebar.file_uploader("Upload CSV file", type=['csv'])
246
- use_sample = st.sidebar.button("Use Sample Data")
247
-
248
- # Load data
249
- if uploaded_file is not None:
250
- try:
251
- df = pd.read_csv(uploaded_file)
252
- st.sidebar.success("✅ File uploaded successfully!")
253
- # Validate required columns
254
- required_cols = ['Account_Name_English', '2024_Amount_NOK', '2023_Amount_NOK']
255
- if not all(col in df.columns for col in required_cols):
256
- st.sidebar.error("❌ CSV must have columns: Account_Name_English, 2024_Amount_NOK, 2023_Amount_NOK")
257
- df = get_sample_data()
258
- except Exception as e:
259
- st.sidebar.error(f"❌ Error reading file: {str(e)}")
260
- df = get_sample_data()
261
- elif use_sample:
262
- df = get_sample_data()
263
- st.sidebar.success("✅ Sample data loaded!")
264
- else:
265
- df = get_sample_data()
266
-
267
- # Calculate ratios and insights
268
- ratios = calculate_ratios(df)
269
- insights = generate_insights(df, ratios)
270
-
271
- # Main content based on selected page
272
- if page == "🏠 Dashboard":
273
- st.title("📊 FinanceGPT Analyzer Dashboard")
274
-
275
- # Key metrics
276
- col1, col2, col3, col4 = st.columns(4)
277
-
278
- with col1:
279
- revenue = get_account_value(df, 'Sales Revenue', '2024')
280
- revenue_prev = get_account_value(df, 'Sales Revenue', '2023')
281
- growth = ((revenue - revenue_prev) / revenue_prev * 100) if revenue_prev != 0 else 0
282
- st.metric("💰 Revenue", f"{revenue/1000000:.1f}M NOK", f"{growth:+.0f}%")
283
-
284
- with col2:
285
- net_income = get_account_value(df, 'Annual Result', '2024')
286
- net_income_prev = get_account_value(df, 'Annual Result', '2023')
287
- profit_change = net_income - net_income_prev
288
- st.metric("📈 Net Profit", f"{net_income/1000000:.1f}M NOK", f"{profit_change/1000000:+.1f}M NOK")
289
-
290
- with col3:
291
- assets = get_account_value(df, 'TOTAL ASSETS', '2024')
292
- assets_prev = get_account_value(df, 'TOTAL ASSETS', '2023')
293
- asset_growth = ((assets - assets_prev) / assets_prev * 100) if assets_prev != 0 else 0
294
- st.metric("🏛️ Total Assets", f"{assets/1000000:.1f}M NOK", f"{asset_growth:+.0f}%")
295
-
296
- with col4:
297
- cash = get_account_value(df, 'Cash at End of Period', '2024')
298
- cash_prev = get_account_value(df, 'Cash at Beginning of Period', '2024')
299
- cash_change = ((cash - cash_prev) / cash_prev * 100) if cash_prev != 0 else 0
300
- st.metric("💸 Cash", f"{cash/1000000:.1f}M NOK", f"{cash_change:+.0f}%")
301
-
302
- # Charts section
303
- col1, col2 = st.columns(2)
304
-
305
- with col1:
306
- st.subheader("📈 Revenue vs Profit Trend")
307
- trend_data = pd.DataFrame({
308
- 'Year': ['2023', '2024'],
309
- 'Revenue': [revenue_prev/1000000, revenue/1000000],
310
- 'Net Income': [net_income_prev/1000000, net_income/1000000]
311
- })
312
-
313
- fig = px.line(trend_data, x='Year', y=['Revenue', 'Net Income'],
314
- title="Revenue vs Net Income (Million NOK)")
315
- fig.update_layout(height=400)
316
- st.plotly_chart(fig, use_container_width=True)
317
 
318
- with col2:
319
- st.subheader("🎯 Financial Health Score")
320
- categories = ['Profitability', 'Liquidity', 'Efficiency', 'Leverage', 'Growth']
321
- scores = [85, 65, 75, 60, 95] # Based on ratios
 
 
 
 
 
 
 
 
 
322
 
323
- fig = go.Figure(data=go.Scatterpolar(
324
- r=scores,
 
 
325
  theta=categories,
326
  fill='toself',
327
- name='Current Performance'
 
 
328
  ))
 
329
  fig.update_layout(
330
- polar=dict(radialaxis=dict(visible=True, range=[0, 100])),
331
- height=400
 
 
 
 
 
332
  )
333
- st.plotly_chart(fig, use_container_width=True)
334
-
335
- # Second row of charts
336
- col1, col2 = st.columns(2)
337
-
338
- with col1:
339
- st.subheader("🏛️ Asset vs Liability Structure")
340
- structure_data = pd.DataFrame({
341
- 'Category': ['Total Assets', 'Total Debt', 'Total Equity'],
342
- 'Amount': [assets/1000000, get_account_value(df, 'Total Debt', '2024')/1000000, get_account_value(df, 'Total Equity', '2024')/1000000]
343
- })
344
-
345
- fig = px.bar(structure_data, x='Category', y='Amount',
346
- title="Financial Structure (Million NOK)")
347
- fig.update_traces(marker_color=['#3498db', '#e74c3c', '#2ecc71'])
348
- fig.update_layout(height=400)
349
- st.plotly_chart(fig, use_container_width=True)
350
-
351
- with col2:
352
- st.subheader("💸 Cash Flow Overview")
353
- # Create sample cash flow data
354
- operating_cf = get_account_value(df, 'Net Cash Flow from Operating Activities', '2024')
355
- investing_cf = get_account_value(df, 'Net Cash Flow from Investing Activities', '2024')
356
- financing_cf = get_account_value(df, 'Net Cash Flow from Financing Activities', '2024')
357
-
358
- categories = ['Operating', 'Investing', 'Financing']
359
- values = [operating_cf/1000000, investing_cf/1000000, financing_cf/1000000]
360
- colors = ['green' if v > 0 else 'red' for v in values]
361
-
362
- fig = go.Figure(data=[go.Bar(x=categories, y=values, marker_color=colors)])
363
- fig.update_layout(title="Cash Flow by Activity (Million NOK)", height=400)
364
- st.plotly_chart(fig, use_container_width=True)
365
-
366
- # Insights section
367
- st.subheader("🎯 Key Insights")
368
- for title, message, type in insights:
369
- if type == "success":
370
- st.success(f"**{title}**: {message}")
371
- elif type == "warning":
372
- st.warning(f"**{title}**: {message}")
373
- else:
374
- st.error(f"**{title}**: {message}")
375
-
376
- elif page == "💰 Income Analysis":
377
- st.title("💰 Income Statement Analysis")
378
-
379
- # Income statement data
380
- income_data = df[df['Statement_Type'] == 'Income Statement'].copy()
381
-
382
- col1, col2 = st.columns(2)
383
-
384
- with col1:
385
- st.subheader("📊 Revenue Breakdown")
386
- revenue = get_account_value(df, 'Sales Revenue', '2024')
387
- cogs = get_account_value(df, 'Cost of Goods Sold', '2024')
388
- other_opex = get_account_value(df, 'Other Operating Expenses', '2024')
389
- payroll = get_account_value(df, 'Payroll Expenses', '2024')
390
-
391
- breakdown = pd.DataFrame({
392
- 'Category': ['Gross Profit', 'COGS', 'Payroll', 'Other OpEx'],
393
- 'Amount': [revenue - cogs, cogs, payroll, other_opex]
394
- })
395
-
396
- fig = px.pie(breakdown, values='Amount', names='Category',
397
- title="Revenue Allocation (2024)")
398
- st.plotly_chart(fig, use_container_width=True)
399
-
400
- with col2:
401
- st.subheader("📈 Profitability Metrics")
402
- metrics_df = pd.DataFrame({
403
- 'Metric': ['Gross Margin', 'Net Margin', 'ROA', 'ROE'],
404
- 'Value': [ratios['Gross Margin'], ratios['Net Margin'],
405
- ratios['ROA'], ratios['ROE']],
406
- 'Grade': [get_ratio_grade('Gross Margin', ratios['Gross Margin']),
407
- get_ratio_grade('Net Margin', ratios['Net Margin']),
408
- get_ratio_grade('ROA', ratios['ROA']),
409
- get_ratio_grade('ROE', ratios['ROE'])]
410
- })
411
-
412
- for _, row in metrics_df.iterrows():
413
- col_a, col_b, col_c = st.columns([2, 1, 1])
414
- with col_a:
415
- st.write(row['Metric'])
416
- with col_b:
417
- st.write(f"{row['Value']:.1f}%")
418
- with col_c:
419
- color = {"A": "🟢", "B": "🟡", "C": "🟠", "D": "🔴"}.get(row['Grade'], "⚪")
420
- st.write(f"{color} {row['Grade']}")
421
-
422
- # Year over year comparison
423
- st.subheader("📊 Year-over-Year Comparison")
424
- comparison_data = pd.DataFrame({
425
- 'Account': ['Sales Revenue', 'Cost of Goods Sold', 'Operating Result', 'Annual Result'],
426
- '2023': [
427
- get_account_value(df, 'Sales Revenue', '2023')/1000000,
428
- get_account_value(df, 'Cost of Goods Sold', '2023')/1000000,
429
- get_account_value(df, 'Operating Result', '2023')/1000000,
430
- get_account_value(df, 'Annual Result', '2023')/1000000
431
- ],
432
- '2024': [
433
- get_account_value(df, 'Sales Revenue', '2024')/1000000,
434
- get_account_value(df, 'Cost of Goods Sold', '2024')/1000000,
435
- get_account_value(df, 'Operating Result', '2024')/1000000,
436
- get_account_value(df, 'Annual Result', '2024')/1000000
437
- ]
438
- })
439
-
440
- fig = go.Figure()
441
- fig.add_trace(go.Bar(name='2023', x=comparison_data['Account'], y=comparison_data['2023'], marker_color='lightblue'))
442
- fig.add_trace(go.Bar(name='2024', x=comparison_data['Account'], y=comparison_data['2024'], marker_color='darkblue'))
443
- fig.update_layout(title="Income Statement Comparison (Million NOK)", barmode='group')
444
- st.plotly_chart(fig, use_container_width=True)
445
-
446
- elif page == "🏛️ Balance Sheet":
447
- st.title("🏛️ Balance Sheet Analysis")
448
-
449
- col1, col2 = st.columns(2)
450
-
451
- with col1:
452
- st.subheader("🏦 Asset Structure")
453
- current_assets = get_account_value(df, 'Total Current Assets', '2024')
454
- fixed_assets = get_account_value(df, 'Total Fixed Assets', '2024')
455
-
456
- asset_structure = pd.DataFrame({
457
- 'Asset Type': ['Current Assets', 'Fixed Assets'],
458
- 'Amount': [current_assets/1000000, fixed_assets/1000000]
459
- })
460
-
461
- fig = px.bar(asset_structure, x='Asset Type', y='Amount',
462
- title="Asset Composition (Million NOK)")
463
- fig.update_traces(marker_color=['#3498db', '#e74c3c'])
464
- st.plotly_chart(fig, use_container_width=True)
465
-
466
- with col2:
467
- st.subheader("⚖️ Solvency Ratios")
468
- solvency_metrics = pd.DataFrame({
469
- 'Ratio': ['Current Ratio', 'Debt Ratio', 'Equity Ratio'],
470
- 'Value': [ratios['Current Ratio'], ratios['Debt Ratio'],
471
- 100 - ratios['Debt Ratio']],
472
- 'Benchmark': [1.5, 50, 50]
473
- })
474
 
475
- fig = go.Figure()
476
- fig.add_trace(go.Bar(name='Current', x=solvency_metrics['Ratio'],
477
- y=solvency_metrics['Value'], marker_color='lightblue'))
478
- fig.add_trace(go.Bar(name='Benchmark', x=solvency_metrics['Ratio'],
479
- y=solvency_metrics['Benchmark'], marker_color='orange'))
480
- fig.update_layout(title="Solvency Analysis", barmode='group')
481
- st.plotly_chart(fig, use_container_width=True)
482
-
483
- # Balance sheet details
484
- st.subheader("📋 Balance Sheet Details")
485
-
486
- tab1, tab2, tab3 = st.tabs(["📊 Assets", "💳 Liabilities", "🏦 Equity"])
487
-
488
- with tab1:
489
- st.write("**Asset Breakdown (2024)**")
490
- asset_details = pd.DataFrame({
491
- 'Asset Category': [
492
- 'Customer Receivables',
493
- 'Other Receivables',
494
- 'Bank Deposits Cash',
495
- 'Machinery and Equipment',
496
- 'Land Buildings'
497
- ],
498
- 'Amount (NOK)': [
499
- get_account_value(df, 'Customer Receivables', '2024'),
500
- get_account_value(df, 'Other Receivables', '2024'),
501
- get_account_value(df, 'Bank Deposits Cash and Similar', '2024'),
502
- get_account_value(df, 'Machinery and Equipment', '2024'),
503
- get_account_value(df, 'Land Buildings and Other Real Estate', '2024')
504
- ]
505
- })
506
- asset_details['Amount (Million NOK)'] = asset_details['Amount (NOK)'] / 1000000
507
- asset_details['Percentage'] = (asset_details['Amount (NOK)'] / asset_details['Amount (NOK)'].sum() * 100).round(1)
508
- st.dataframe(asset_details[['Asset Category', 'Amount (Million NOK)', 'Percentage']], use_container_width=True)
509
-
510
- with tab2:
511
- st.write("**Liability Breakdown (2024)**")
512
- liability_details = pd.DataFrame({
513
- 'Liability Category': [
514
- 'Accounts Payable',
515
- 'Short-term Debt',
516
- 'Long-term Debt',
517
- 'Payable Tax'
518
- ],
519
- 'Amount (NOK)': [
520
- get_account_value(df, 'Accounts Payable', '2024'),
521
- get_account_value(df, 'Total Short-term Debt', '2024'),
522
- get_account_value(df, 'Total Long-term Debt', '2024'),
523
- get_account_value(df, 'Payable Tax', '2024')
524
- ]
525
- })
526
- liability_details['Amount (Million NOK)'] = liability_details['Amount (NOK)'] / 1000000
527
- liability_details['Percentage'] = (liability_details['Amount (NOK)'] / liability_details['Amount (NOK)'].sum() * 100).round(1)
528
- st.dataframe(liability_details[['Liability Category', 'Amount (Million NOK)', 'Percentage']], use_container_width=True)
529
-
530
- with tab3:
531
- st.write("**Equity Breakdown (2024)**")
532
- equity_details = pd.DataFrame({
533
- 'Equity Category': [
534
- 'Share Capital',
535
- 'Retained Earnings'
536
- ],
537
- 'Amount (NOK)': [
538
- get_account_value(df, 'Share Capital', '2024'),
539
- get_account_value(df, 'Other Equity', '2024')
540
- ]
541
- })
542
- equity_details['Amount (Million NOK)'] = equity_details['Amount (NOK)'] / 1000000
543
- equity_details['Percentage'] = (equity_details['Amount (NOK)'] / equity_details['Amount (NOK)'].sum() * 100).round(1)
544
- st.dataframe(equity_details[['Equity Category', 'Amount (Million NOK)', 'Percentage']], use_container_width=True)
545
-
546
- elif page == "💸 Cash Flow":
547
- st.title("💸 Cash Flow Analysis")
548
-
549
- # Cash flow waterfall
550
- st.subheader("🌊 Cash Flow Waterfall")
551
-
552
- operating_cf = get_account_value(df, 'Net Cash Flow from Operating Activities', '2024')
553
- investing_cf = get_account_value(df, 'Net Cash Flow from Investing Activities', '2024')
554
- financing_cf = get_account_value(df, 'Net Cash Flow from Financing Activities', '2024')
555
- net_change = get_account_value(df, 'NET CHANGE IN CASH', '2024')
556
 
557
- categories = ['Operating', 'Investing', 'Financing', 'Net Change']
558
- values = [operating_cf, investing_cf, financing_cf, net_change]
559
-
560
- fig = go.Figure(go.Waterfall(
561
- name="Cash Flow", orientation="v",
562
- measure=["relative", "relative", "relative", "total"],
563
- x=categories,
564
- textposition="outside",
565
- text=[f"{v/1000000:.1f}M" for v in values],
566
- y=[v/1000000 for v in values],
567
- connector={"line": {"color": "rgb(63, 63, 63)"}},
568
- ))
569
- fig.update_layout(title="Cash Flow Waterfall (Million NOK)", showlegend=False)
570
- st.plotly_chart(fig, use_container_width=True)
571
-
572
- # Cash flow quality metrics
573
- col1, col2, col3 = st.columns(3)
574
-
575
- with col1:
576
- net_income = get_account_value(df, 'Annual Result', '2024')
577
- quality_ratio = operating_cf / net_income if net_income != 0 else 0
578
- st.metric("💧 Cash Quality Ratio", f"{quality_ratio:.2f}",
579
- "Healthy" if quality_ratio > 1 else "Needs attention")
580
-
581
- with col2:
582
- fcf = operating_cf + investing_cf # OCF + Investing
583
- st.metric("🆓 Free Cash Flow", f"{fcf/1000000:.1f}M NOK",
584
- "Positive" if fcf > 0 else "Negative")
585
-
586
- with col3:
587
- cash_current = get_account_value(df, 'Cash at End of Period', '2024')
588
- cash_prev = get_account_value(df, 'Cash at Beginning of Period', '2024')
589
- cash_growth = ((cash_current - cash_prev) / cash_prev * 100) if cash_prev != 0 else 0
590
- st.metric("💰 Cash Growth", f"{cash_growth:+.1f}%")
591
-
592
- # Detailed cash flow analysis
593
- st.subheader("📊 Cash Flow Components")
594
-
595
- tab1, tab2, tab3 = st.tabs(["🏭 Operating", "🏗️ Investing", "💰 Financing"])
596
-
597
- with tab1:
598
- st.write("**Operating Cash Flow Components**")
599
- operating_components = pd.DataFrame({
600
- 'Component': [
601
- 'Net Income',
602
- 'Depreciation',
603
- 'Change in Receivables',
604
- 'Change in Payables'
605
- ],
606
- 'Amount (Million NOK)': [
607
- get_account_value(df, 'Net Income', '2024')/1000000,
608
- get_account_value(df, 'Depreciation', '2024')/1000000,
609
- get_account_value(df, 'Change in Customer Receivables', '2024')/1000000,
610
- get_account_value(df, 'Change in Accounts Payable', '2024')/1000000
611
- ]
612
- })
613
- st.dataframe(operating_components, use_container_width=True)
614
-
615
- with tab2:
616
- st.write("**Investing Cash Flow Components**")
617
- investing_components = pd.DataFrame({
618
- 'Component': [
619
- 'Purchase of Fixed Assets',
620
- 'Change in Financial Assets'
621
- ],
622
- 'Amount (Million NOK)': [
623
- get_account_value(df, 'Purchase of Fixed Assets', '2024')/1000000,
624
- get_account_value(df, 'Change in Financial Fixed Assets', '2024')/1000000
625
- ]
626
- })
627
- st.dataframe(investing_components, use_container_width=True)
628
-
629
- with tab3:
630
- st.write("**Financing Cash Flow Components**")
631
- financing_components = pd.DataFrame({
632
- 'Component': [
633
- 'Change in Long-term Debt',
634
- 'Change in Other Long-term Debt'
635
- ],
636
- 'Amount (Million NOK)': [
637
- get_account_value(df, 'Change in Long-term Debt to Credit Institutions', '2024')/1000000,
638
- get_account_value(df, 'Change in Other Long-term Debt', '2024')/1000000
639
- ]
640
- })
641
- st.dataframe(financing_components, use_container_width=True)
642
 
643
- elif page == "📊 Financial Ratios":
644
- st.title("📊 Financial Ratios Hub")
645
-
646
- # Ratio categories
647
- ratio_categories = {
648
- 'Profitability': ['Net Margin', 'ROA', 'ROE', 'Gross Margin', 'Operating Margin'],
649
- 'Liquidity': ['Current Ratio'],
650
- 'Efficiency': ['Asset Turnover'],
651
- 'Leverage': ['Debt Ratio', 'Debt to Equity']
652
  }
653
-
654
- selected_category = st.selectbox("Select Ratio Category",
655
- ['All'] + list(ratio_categories.keys()))
656
-
657
- # Display ratios
658
- for category, ratio_names in ratio_categories.items():
659
- if selected_category == 'All' or selected_category == category:
660
- st.subheader(f"📈 {category} Ratios")
661
-
662
- cols = st.columns(min(len(ratio_names), 4)) # Max 4 columns
663
- for i, ratio_name in enumerate(ratio_names):
664
- with cols[i % 4]:
665
- value = ratios[ratio_name]
666
- grade = get_ratio_grade(ratio_name, value)
667
- grade_color = {"A": "🟢", "B": "🟡", "C": "🟠", "D": "🔴"}.get(grade, "⚪")
668
-
669
- if ratio_name in ['Current Ratio', 'Asset Turnover', 'Debt to Equity']:
670
- st.metric(ratio_name, f"{value:.2f}", f"Grade: {grade_color} {grade}")
671
- else:
672
- st.metric(ratio_name, f"{value:.1f}%", f"Grade: {grade_color} {grade}")
673
-
674
- # Industry benchmark comparison
675
- st.subheader("🎯 Industry Benchmark Comparison")
676
-
677
- benchmark_data = pd.DataFrame({
678
- 'Ratio': ['ROE (%)', 'ROA (%)', 'Current Ratio', 'Debt Ratio (%)'],
679
- 'Your Company': [ratios['ROE'], ratios['ROA'], ratios['Current Ratio'], ratios['Debt Ratio']],
680
- 'Industry Average': [15.0, 8.0, 1.5, 45.0]
681
- })
682
-
683
- fig = go.Figure()
684
- fig.add_trace(go.Bar(name='Your Company', x=benchmark_data['Ratio'],
685
- y=benchmark_data['Your Company'], marker_color='lightblue'))
686
- fig.add_trace(go.Bar(name='Industry Average', x=benchmark_data['Ratio'],
687
- y=benchmark_data['Industry Average'], marker_color='orange'))
688
- fig.update_layout(title="Performance vs Industry Benchmarks", barmode='group')
689
- st.plotly_chart(fig, use_container_width=True)
690
-
691
- # Ratio trend analysis
692
- st.subheader("📈 Ratio Trends")
693
-
694
- # Create sample trend data
695
- trend_ratios = pd.DataFrame({
696
- 'Year': ['2023', '2024'],
697
- 'ROE': [
698
- (get_account_value(df, 'Annual Result', '2023') / get_account_value(df, 'Total Equity', '2023') * 100),
699
- ratios['ROE']
700
- ],
701
- 'Current Ratio': [
702
- (get_account_value(df, 'Total Current Assets', '2023') / get_account_value(df, 'Total Short-term Debt', '2023')),
703
- ratios['Current Ratio']
704
- ],
705
- 'Debt Ratio': [
706
- (get_account_value(df, 'Total Debt', '2023') / get_account_value(df, 'TOTAL ASSETS', '2023') * 100),
707
- ratios['Debt Ratio']
708
- ]
709
- })
710
-
711
- fig = px.line(trend_ratios, x='Year', y=['ROE', 'Debt Ratio'],
712
- title="Key Ratios Trend Analysis")
713
- st.plotly_chart(fig, use_container_width=True)
714
 
715
- elif page == "🤖 AI Assistant":
716
- st.title("🤖 AI Financial Assistant")
 
 
 
 
 
 
 
 
 
 
 
717
 
718
- # Quick analysis buttons
719
- st.subheader("🎯 Quick Analysis")
720
- col1, col2, col3 = st.columns(3)
721
 
722
- with col1:
723
- if st.button("📊 Overall Health Check", key="health_check"):
724
- st.success("**Financial Health Assessment:**")
725
- st.write("• Revenue growth of 413% indicates explosive business growth")
726
- st.write("• Strong profitability with 21.2% net margin")
727
- st.write("• Good liquidity with current ratio of 1.37")
728
- st.write("• Moderate leverage at 51.8% debt ratio")
729
- st.write("• **Overall Grade: A- (Excellent performance)**")
730
 
731
- with col2:
732
- if st.button("⚠️ Risk Analysis", key="risk_analysis"):
733
- st.warning("**Key Risk Factors:**")
734
- st.write(" High accounts receivable (5.6M NOK - 22% of revenue)")
735
- st.write("• Rapid growth may strain working capital")
736
- st.write("• Customer concentration risk needs monitoring")
737
- st.write("• **Recommendation: Strengthen cash collection processes**")
738
 
739
- with col3:
740
- if st.button("💡 Strategic Recommendations", key="recommendations"):
741
- st.info("**Strategic Recommendations:**")
742
- st.write("• Implement automated invoicing and follow-up systems")
743
- st.write("• Consider factoring high-quality receivables")
744
- st.write("• Build cash reserves to 15-20% of revenue")
745
- st.write("• **Focus: Scale operations while maintaining profitability**")
746
 
747
- # Interactive chat interface
748
- st.subheader("💬 Ask Me Anything About Your Finances")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
749
 
750
- # Initialize chat history
751
- if "messages" not in st.session_state:
752
- st.session_state.messages = [
753
- {"role": "assistant", "content": "Hello! I'm your AI Financial Assistant. I can help you analyze your financial data, identify trends, and provide strategic recommendations. What would you like to know?"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
754
  ]
755
-
756
- # Display chat history
757
- for message in st.session_state.messages:
758
- with st.chat_message(message["role"]):
759
- st.markdown(message["content"])
760
-
761
- # Chat input
762
- if prompt := st.chat_input("Ask about your financial data..."):
763
- # Add user message to chat history
764
- st.session_state.messages.append({"role": "user", "content": prompt})
765
-
766
- # Display user message
767
- with st.chat_message("user"):
768
- st.markdown(prompt)
769
-
770
- # Generate AI response
771
- with st.chat_message("assistant"):
772
- # Simple rule-based responses (in real app, this would use LLM)
773
- prompt_lower = prompt.lower()
 
774
 
775
- if any(word in prompt_lower for word in ["revenue", "sales", "income"]):
776
- response = f"""**Revenue Analysis:**
777
- • Your revenue grew from {get_account_value(df, 'Sales Revenue', '2023')/1000000:.1f}M to {get_account_value(df, 'Sales Revenue', '2024')/1000000:.1f}M NOK ({ratios['Revenue Growth']:.1f}% growth)
778
- This is exceptional growth indicating strong market demand
779
- Gross margin is {ratios['Gross Margin']:.1f}%, showing good pricing power
780
- **Key insight:** Focus on maintaining this growth trajectory while improving operational efficiency"""
781
-
782
- elif any(word in prompt_lower for word in ["profit", "profitability", "margin"]):
783
- response = f"""**Profitability Analysis:**
784
- Net margin improved to {ratios['Net Margin']:.1f}% (excellent level)
785
- • ROE of {ratios['ROE']:.1f}% shows strong returns to shareholders
786
- Operating margin of {ratios['Operating Margin']:.1f}% indicates efficient operations
787
- • **Recommendation:** Continue optimizing cost structure while scaling"""
 
 
 
 
 
 
 
 
 
 
 
788
 
789
- elif any(word in prompt_lower for word in ["cash", "liquidity", "flow"]):
790
- cash = get_account_value(df, 'Cash at End of Period', '2024')
791
- operating_cf = get_account_value(df, 'Net Cash Flow from Operating Activities', '2024')
792
- response = f"""**Cash Flow Analysis:**
793
- Cash position: {cash/1000000:.1f}M NOK (strong)
794
- • Operating cash flow: {operating_cf/1000000:.1f}M NOK
795
- Current ratio: {ratios['Current Ratio']:.1f} (acceptable but could improve)
796
- **Focus area:** Monitor working capital management closely"""
 
 
797
 
798
- elif any(word in prompt_lower for word in ["risk", "debt", "leverage"]):
799
- response = f"""**Risk Assessment:**
800
- • Debt ratio: {ratios['Debt Ratio']:.1f}% (moderate level)
801
- Key risk: High receivables ({get_account_value(df, 'Customer Receivables', '2024')/1000000:.1f}M NOK)
802
- • Liquidity risk: Current ratio could be stronger
803
- • **Priority:** Improve collection processes and build cash reserves"""
804
 
805
- elif any(word in prompt_lower for word in ["compare", "benchmark", "industry"]):
806
- response = f"""**Benchmark Comparison:**
807
- • Your ROE ({ratios['ROE']:.1f}%) vs Industry avg (15%): **Excellent**
808
- • Your ROA ({ratios['ROA']:.1f}%) vs Industry avg (8%): **Outstanding**
809
- • Your current ratio ({ratios['Current Ratio']:.1f}) vs Industry avg (1.5): **Needs improvement**
810
- • **Overall:** You're outperforming on profitability, focus on liquidity"""
811
 
812
- elif any(word in prompt_lower for word in ["improve", "strategy", "plan"]):
813
- response = """**Strategic Improvement Plan:**
814
- 1. **Short-term (3 months):**
815
- - Implement automated invoice management
816
- - Negotiate better payment terms with major customers
817
-
818
- 2. **Medium-term (6-12 months):**
819
- - Build cash reserves to 15-20% of revenue
820
- - Consider factoring receivables if needed
821
-
822
- 3. **Long-term (12+ months):**
823
- - Diversify customer base to reduce concentration risk
824
- - Optimize working capital cycle"""
825
 
826
- else:
827
- response = """I can help you analyze various aspects of your financial data:
828
-
829
- **Revenue & Growth:** Ask about sales trends, growth drivers
830
- **Profitability:** Inquire about margins, ROE, ROA analysis
831
- **Cash Flow:** Questions about liquidity, working capital
832
- **Risk Assessment:** Ask about leverage, debt, financial risks
833
- • **Benchmarking:** Compare your performance to industry standards
834
- • **Strategy:** Get recommendations for improvement
835
-
836
- What specific area interests you most?"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
837
 
838
- st.markdown(response)
839
- st.session_state.messages.append({"role": "assistant", "content": response})
840
 
841
- # Data context sidebar
842
- with st.expander("📋 Current Financial Context", expanded=False):
843
- col1, col2 = st.columns(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
844
 
845
  with col1:
846
- st.write("**Key Figures (2024):**")
847
- st.write(f" Revenue: {get_account_value(df, 'Sales Revenue', '2024')/1000000:.1f}M NOK")
848
- st.write(f"• Net Income: {get_account_value(df, 'Annual Result', '2024')/1000000:.1f}M NOK")
849
- st.write(f"• Total Assets: {get_account_value(df, 'TOTAL ASSETS', '2024')/1000000:.1f}M NOK")
850
- st.write(f"• Cash: {get_account_value(df, 'Cash at End of Period', '2024')/1000000:.1f}M NOK")
851
 
852
  with col2:
853
- st.write("**Key Ratios:**")
854
- st.write(f" Revenue Growth: {ratios['Revenue Growth']:.1f}%")
855
- st.write(f"• Net Margin: {ratios['Net Margin']:.1f}%")
856
- st.write(f"• ROE: {ratios['ROE']:.1f}%")
857
- st.write(f"• Current Ratio: {ratios['Current Ratio']:.1f}")
858
-
859
- # Footer
860
- st.sidebar.markdown("---")
861
- st.sidebar.markdown("📊 **FinanceGPT Analyzer**")
862
- st.sidebar.markdown("AI-Powered Financial Analysis")
863
- st.sidebar.markdown("Built with Streamlit & Plotly")
864
-
865
- # Additional sidebar info
866
- with st.sidebar.expander("ℹ️ How to Use"):
867
- st.write("""
868
- **Getting Started:**
869
- 1. Upload your CSV file or use sample data
870
- 2. Navigate through different analysis pages
871
- 3. Use the AI Assistant for specific questions
872
-
873
- **Required CSV Format:**
874
- - Account_Name_English
875
- - 2024_Amount_NOK
876
- - 2023_Amount_NOK
877
- - Statement_Type (optional)
878
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
879
 
880
- with st.sidebar.expander("📈 Key Features"):
881
- st.write("""
882
- • **Dashboard:** Overview & key metrics
883
- • **Income Analysis:** Profitability deep-dive
884
- • **Balance Sheet:** Asset/liability structure
885
- • **Cash Flow:** Liquidity analysis
886
- • **Ratios Hub:** Comprehensive ratio analysis
887
- • **AI Assistant:** Interactive financial insights
888
- """)
 
7
  from datetime import datetime
8
  import io
9
 
10
+ # Page configuration
11
  st.set_page_config(
12
  page_title="FinanceGPT Analyzer",
13
  page_icon="📊",
14
+ layout="wide"
 
15
  )
16
 
17
+ # Custom CSS for better styling
18
  st.markdown("""
19
  <style>
20
  .metric-card {
21
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
22
  padding: 1rem;
23
  border-radius: 10px;
24
  color: white;
25
  text-align: center;
 
26
  }
27
  .insight-box {
28
  background: #f8f9fa;
29
+ border-left: 4px solid #28a745;
30
  padding: 1rem;
31
  margin: 1rem 0;
 
32
  }
33
+ .risk-alert {
34
+ background: #fff3cd;
35
+ border-left: 4px solid #ffc107;
 
 
 
 
36
  padding: 1rem;
37
+ margin: 1rem 0;
 
 
38
  }
39
  </style>
40
  """, unsafe_allow_html=True)
41
 
42
+ class FinancialAnalyzer:
43
+ def __init__(self, df):
44
+ self.df = df.copy()
45
+ self.process_data()
46
+
47
+ def process_data(self):
48
+ """Process and structure financial data"""
49
+ # Create pivot table for easier analysis
50
+ self.pivot_df = self.df.pivot_table(
51
+ index=['Year', 'Statement_Type'],
52
+ columns='Account_Name_English',
53
+ values=['2024_Amount_NOK', '2023_Amount_NOK'],
54
+ aggfunc='first'
55
+ ).fillna(0)
56
+
57
+ # Flatten column names
58
+ self.pivot_df.columns = ['_'.join(col).strip() for col in self.pivot_df.columns]
59
+ self.pivot_df = self.pivot_df.reset_index()
60
+
61
+ def get_key_metrics(self):
62
+ """Calculate key financial metrics"""
63
+ try:
64
+ # Extract key values
65
+ revenue_2024 = self.df[self.df['Account_Name_English'] == 'Sales Revenue']['2024_Amount_NOK'].iloc[0]
66
+ revenue_2023 = self.df[self.df['Account_Name_English'] == 'Sales Revenue']['2023_Amount_NOK'].iloc[0]
67
+
68
+ # Try to get net profit (might have different names)
69
+ net_profit_2024 = 0
70
+ net_profit_2023 = 0
71
+
72
+ profit_accounts = ['Net Profit', 'Net Income', 'Profit After Tax', 'Result']
73
+ for account in profit_accounts:
74
+ profit_data = self.df[self.df['Account_Name_English'].str.contains(account, case=False, na=False)]
75
+ if not profit_data.empty:
76
+ net_profit_2024 = profit_data['2024_Amount_NOK'].iloc[0]
77
+ net_profit_2023 = profit_data['2023_Amount_NOK'].iloc[0]
78
+ break
79
+
80
+ # Calculate growth rates
81
+ revenue_growth = ((revenue_2024 - revenue_2023) / revenue_2023 * 100) if revenue_2023 != 0 else 0
82
+ profit_growth = ((net_profit_2024 - net_profit_2023) / abs(net_profit_2023) * 100) if net_profit_2023 != 0 else 0
83
+
84
+ return {
85
+ 'revenue_2024': revenue_2024,
86
+ 'revenue_2023': revenue_2023,
87
+ 'revenue_growth': revenue_growth,
88
+ 'net_profit_2024': net_profit_2024,
89
+ 'net_profit_2023': net_profit_2023,
90
+ 'profit_growth': profit_growth
91
+ }
92
+ except:
93
+ return {
94
+ 'revenue_2024': 0, 'revenue_2023': 0, 'revenue_growth': 0,
95
+ 'net_profit_2024': 0, 'net_profit_2023': 0, 'profit_growth': 0
96
+ }
97
+
98
+ def create_revenue_trend_chart(self):
99
+ """Create revenue trend visualization"""
100
+ metrics = self.get_key_metrics()
101
+
102
+ fig = go.Figure()
103
+
104
+ years = ['2023', '2024']
105
+ revenues = [metrics['revenue_2023'], metrics['revenue_2024']]
106
+ profits = [metrics['net_profit_2023'], metrics['net_profit_2024']]
107
+
108
+ # Revenue line
109
+ fig.add_trace(go.Scatter(
110
+ x=years, y=revenues,
111
+ mode='lines+markers',
112
+ name='Revenue',
113
+ line=dict(color='#1f77b4', width=3),
114
+ marker=dict(size=10)
115
+ ))
116
+
117
+ # Profit line (secondary y-axis)
118
+ fig.add_trace(go.Scatter(
119
+ x=years, y=profits,
120
+ mode='lines+markers',
121
+ name='Net Profit',
122
+ line=dict(color='#ff7f0e', width=3),
123
+ marker=dict(size=10),
124
+ yaxis='y2'
125
+ ))
126
+
127
+ fig.update_layout(
128
+ title='Revenue vs Profit Trend',
129
+ xaxis_title='Year',
130
+ yaxis=dict(title='Revenue (NOK)', side='left'),
131
+ yaxis2=dict(title='Net Profit (NOK)', side='right', overlaying='y'),
132
+ hovermode='x unified',
133
+ template='plotly_white'
134
+ )
135
+
136
+ return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
+ def create_financial_health_radar(self):
139
+ """Create financial health radar chart"""
140
+ metrics = self.get_key_metrics()
141
+
142
+ # Calculate health scores (0-100)
143
+ revenue_score = min(100, max(0, metrics['revenue_growth'] + 50)) # Base 50, adjust by growth
144
+ profit_score = 85 if metrics['net_profit_2024'] > 0 else 25
145
+ growth_score = min(100, max(0, metrics['revenue_growth']))
146
+ stability_score = 75 # Default for demo
147
+ efficiency_score = 70 # Default for demo
148
+
149
+ categories = ['Revenue Growth', 'Profitability', 'Growth Rate', 'Stability', 'Efficiency']
150
+ values = [revenue_score, profit_score, growth_score, stability_score, efficiency_score]
151
 
152
+ fig = go.Figure()
153
+
154
+ fig.add_trace(go.Scatterpolar(
155
+ r=values,
156
  theta=categories,
157
  fill='toself',
158
+ name='Financial Health',
159
+ line=dict(color='#2E86AB'),
160
+ fillcolor='rgba(46, 134, 171, 0.3)'
161
  ))
162
+
163
  fig.update_layout(
164
+ polar=dict(
165
+ radialaxis=dict(
166
+ visible=True,
167
+ range=[0, 100]
168
+ )),
169
+ showlegend=False,
170
+ title="Financial Health Score"
171
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
+ return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
+ def generate_insights(self):
176
+ """Generate AI-powered insights"""
177
+ metrics = self.get_key_metrics()
178
+ insights = []
179
+
180
+ if metrics['revenue_growth'] > 100:
181
+ insights.append("🚀 Exceptional revenue growth of {:.1f}% indicates strong business expansion".format(metrics['revenue_growth']))
182
+ elif metrics['revenue_growth'] > 20:
183
+ insights.append("📈 Strong revenue growth of {:.1f}% shows healthy business development".format(metrics['revenue_growth']))
184
+ elif metrics['revenue_growth'] < 0:
185
+ insights.append("⚠️ Revenue declined by {:.1f}%, requires immediate attention".format(abs(metrics['revenue_growth'])))
186
+
187
+ if metrics['net_profit_2024'] > 0 and metrics['net_profit_2023'] <= 0:
188
+ insights.append("✅ Company achieved profitability in 2024, turning around from previous losses")
189
+ elif metrics['net_profit_2024'] > metrics['net_profit_2023'] and metrics['net_profit_2023'] > 0:
190
+ insights.append("💰 Profit increased by {:.1f}%, showing improved efficiency".format(metrics['profit_growth']))
191
+
192
+ if not insights:
193
+ insights.append("📊 Financial data processed successfully. Consider uploading more detailed statements for deeper analysis.")
194
+
195
+ return insights
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
+ def create_sample_data():
198
+ """Create sample financial data"""
199
+ sample_data = {
200
+ 'Year': [2024, 2024, 2024, 2024, 2024] * 2,
201
+ 'Statement_Type': ['Income Statement'] * 5 + ['Balance Sheet'] * 5,
202
+ 'Account_Name_Norwegian': ['Salgsinntekt', 'Varekostnad', 'Driftsresultat', 'Nettoresultat', 'Kontanter'] * 2,
203
+ 'Account_Name_English': ['Sales Revenue', 'Cost of Goods Sold', 'Operating Result', 'Net Result', 'Cash'] * 2,
204
+ '2024_Amount_NOK': [25107008, -15000000, 8000000, 5300000, 1600000] * 2,
205
+ '2023_Amount_NOK': [4891891, -3000000, 1500000, -500000, 800000] * 2
206
  }
207
+ return pd.DataFrame(sample_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
 
209
+ def main():
210
+ st.title("📊 FinanceGPT Analyzer")
211
+ st.markdown("### Professional Financial Analysis Platform")
212
+
213
+ # Sidebar navigation
214
+ pages = {
215
+ "🏠 Dashboard": "dashboard",
216
+ "💰 Income Analysis": "income",
217
+ "🏛️ Balance Sheet": "balance",
218
+ "💸 Cash Flow": "cashflow",
219
+ "📊 Financial Ratios": "ratios",
220
+ "🤖 AI Assistant": "ai"
221
+ }
222
 
223
+ selected_page = st.sidebar.selectbox("Navigation", list(pages.keys()))
224
+ current_page = pages[selected_page]
 
225
 
226
+ # File upload section
227
+ st.sidebar.markdown("---")
228
+ st.sidebar.subheader("📁 Data Upload")
 
 
 
 
 
229
 
230
+ uploaded_file = st.sidebar.file_uploader(
231
+ "Upload CSV file",
232
+ type=['csv'],
233
+ help="Upload your financial statement CSV file"
234
+ )
 
 
235
 
236
+ use_sample = st.sidebar.button("📊 Use Sample Data")
 
 
 
 
 
 
237
 
238
+ # Load data
239
+ if uploaded_file is not None:
240
+ df = pd.read_csv(uploaded_file)
241
+ st.sidebar.success("✅ File uploaded successfully!")
242
+ elif use_sample:
243
+ df = create_sample_data()
244
+ st.sidebar.success("✅ Sample data loaded!")
245
+ else:
246
+ st.info("👆 Please upload a CSV file or use sample data to get started")
247
+ st.markdown("""
248
+ ### Expected CSV Format:
249
+ - **Year**: Year of the financial statement
250
+ - **Statement_Type**: Income Statement, Balance Sheet, Cash Flow
251
+ - **Account_Name_Norwegian**: Norwegian account name
252
+ - **Account_Name_English**: English account name
253
+ - **2024_Amount_NOK**: Amount for 2024 in NOK
254
+ - **2023_Amount_NOK**: Amount for 2023 in NOK
255
+ """)
256
+ return
257
+
258
+ # Initialize analyzer
259
+ analyzer = FinancialAnalyzer(df)
260
+
261
+ # Dashboard Page
262
+ if current_page == "dashboard":
263
+ st.markdown("## 🏠 Financial Dashboard")
264
+
265
+ # Key Metrics Cards
266
+ metrics = analyzer.get_key_metrics()
267
+
268
+ col1, col2, col3, col4 = st.columns(4)
269
+
270
+ with col1:
271
+ st.metric(
272
+ "💰 Revenue 2024",
273
+ f"{metrics['revenue_2024']:,.0f} NOK",
274
+ delta=f"{metrics['revenue_growth']:+.1f}%"
275
+ )
276
+
277
+ with col2:
278
+ st.metric(
279
+ "📈 Net Profit 2024",
280
+ f"{metrics['net_profit_2024']:,.0f} NOK",
281
+ delta="Turnaround ✅" if metrics['net_profit_2024'] > 0 and metrics['net_profit_2023'] <= 0 else f"{metrics['profit_growth']:+.1f}%"
282
+ )
283
+
284
+ with col3:
285
+ st.metric(
286
+ "📊 Revenue Growth",
287
+ f"{metrics['revenue_growth']:+.1f}%",
288
+ delta="Strong Growth 🚀" if metrics['revenue_growth'] > 100 else "Growth 📈"
289
+ )
290
+
291
+ with col4:
292
+ total_accounts = len(df['Account_Name_English'].unique())
293
+ st.metric(
294
+ "📋 Accounts Analyzed",
295
+ f"{total_accounts}",
296
+ delta="Data Points"
297
+ )
298
+
299
+ # Charts Section
300
+ col1, col2 = st.columns(2)
301
+
302
+ with col1:
303
+ fig_trend = analyzer.create_revenue_trend_chart()
304
+ st.plotly_chart(fig_trend, use_container_width=True)
305
+
306
+ with col2:
307
+ fig_radar = analyzer.create_financial_health_radar()
308
+ st.plotly_chart(fig_radar, use_container_width=True)
309
+
310
+ # Quick Insights
311
+ st.markdown("## 🎯 Quick Insights")
312
+ insights = analyzer.generate_insights()
313
+
314
+ for insight in insights:
315
+ st.markdown(f"""
316
+ <div class="insight-box">
317
+ <strong>{insight}</strong>
318
+ </div>
319
+ """, unsafe_allow_html=True)
320
+
321
+ # Income Analysis Page
322
+ elif current_page == "income":
323
+ st.markdown("## 💰 Income Analysis")
324
+
325
+ # Filter income statement data
326
+ income_data = df[df['Statement_Type'] == 'Income Statement']
327
+
328
+ if income_data.empty:
329
+ st.warning("No income statement data found in the uploaded file.")
330
+ return
331
+
332
+ # Revenue analysis
333
+ st.subheader("📈 Revenue Trend Analysis")
334
+
335
+ revenue_data = income_data[income_data['Account_Name_English'].str.contains('Revenue|Sales', case=False, na=False)]
336
+
337
+ if not revenue_data.empty:
338
+ fig = go.Figure()
339
+
340
+ for _, row in revenue_data.iterrows():
341
+ fig.add_trace(go.Bar(
342
+ x=['2023', '2024'],
343
+ y=[row['2023_Amount_NOK'], row['2024_Amount_NOK']],
344
+ name=row['Account_Name_English'],
345
+ text=[f"{row['2023_Amount_NOK']:,.0f}", f"{row['2024_Amount_NOK']:,.0f}"],
346
+ textposition='auto'
347
+ ))
348
+
349
+ fig.update_layout(
350
+ title="Revenue Comparison 2023 vs 2024",
351
+ xaxis_title="Year",
352
+ yaxis_title="Amount (NOK)",
353
+ template='plotly_white'
354
+ )
355
+
356
+ st.plotly_chart(fig, use_container_width=True)
357
+
358
+ # Cost analysis
359
+ st.subheader("🥧 Cost Structure Analysis")
360
+
361
+ cost_data = income_data[income_data['Account_Name_English'].str.contains('Cost|Expense', case=False, na=False)]
362
+
363
+ if not cost_data.empty:
364
+ # Create pie chart for 2024 costs
365
+ fig_pie = px.pie(
366
+ cost_data,
367
+ values='2024_Amount_NOK',
368
+ names='Account_Name_English',
369
+ title="Cost Structure 2024"
370
+ )
371
+ st.plotly_chart(fig_pie, use_container_width=True)
372
+
373
+ # Profitability metrics
374
+ st.subheader("📊 Profitability Indicators")
375
+
376
+ metrics = analyzer.get_key_metrics()
377
+
378
+ col1, col2, col3 = st.columns(3)
379
+
380
+ with col1:
381
+ if metrics['revenue_2024'] > 0:
382
+ profit_margin = (metrics['net_profit_2024'] / metrics['revenue_2024']) * 100
383
+ st.metric("Net Profit Margin", f"{profit_margin:.1f}%")
384
+
385
+ with col2:
386
+ st.metric("Revenue Growth", f"{metrics['revenue_growth']:+.1f}%")
387
+
388
+ with col3:
389
+ if metrics['net_profit_2023'] != 0:
390
+ st.metric("Profit Growth", f"{metrics['profit_growth']:+.1f}%")
391
 
392
+ # Balance Sheet Page
393
+ elif current_page == "balance":
394
+ st.markdown("## 🏛️ Balance Sheet Analysis")
395
+
396
+ balance_data = df[df['Statement_Type'] == 'Balance Sheet']
397
+
398
+ if balance_data.empty:
399
+ st.warning("No balance sheet data found. Please upload data with Balance Sheet entries.")
400
+ st.markdown("### Sample Balance Sheet Accounts:")
401
+ st.markdown("- Cash, Accounts Receivable, Inventory (Assets)")
402
+ st.markdown("- Accounts Payable, Long-term Debt (Liabilities)")
403
+ st.markdown("- Equity, Retained Earnings (Equity)")
404
+ return
405
+
406
+ # Asset analysis
407
+ st.subheader("📊 Asset Structure")
408
+
409
+ asset_keywords = ['Cash', 'Receivable', 'Inventory', 'Asset', 'Equipment', 'Property']
410
+ asset_data = balance_data[
411
+ balance_data['Account_Name_English'].str.contains('|'.join(asset_keywords), case=False, na=False)
412
  ]
413
+
414
+ if not asset_data.empty:
415
+ fig_assets = px.bar(
416
+ asset_data,
417
+ x='Account_Name_English',
418
+ y=['2023_Amount_NOK', '2024_Amount_NOK'],
419
+ title="Asset Comparison 2023 vs 2024",
420
+ barmode='group'
421
+ )
422
+ st.plotly_chart(fig_assets, use_container_width=True)
423
+
424
+ # Liquidity ratios (if we have the right accounts)
425
+ st.subheader("⚖️ Financial Ratios")
426
+
427
+ cash_data = balance_data[balance_data['Account_Name_English'].str.contains('Cash', case=False, na=False)]
428
+ debt_data = balance_data[balance_data['Account_Name_English'].str.contains('Debt|Payable', case=False, na=False)]
429
+
430
+ if not cash_data.empty:
431
+ cash_2024 = cash_data['2024_Amount_NOK'].iloc[0]
432
+ cash_2023 = cash_data['2023_Amount_NOK'].iloc[0]
433
 
434
+ col1, col2 = st.columns(2)
435
+ with col1:
436
+ st.metric("Cash 2024", f"{cash_2024:,.0f} NOK")
437
+ with col2:
438
+ cash_growth = ((cash_2024 - cash_2023) / cash_2023 * 100) if cash_2023 != 0 else 0
439
+ st.metric("Cash Growth", f"{cash_growth:+.1f}%")
440
+
441
+ # Cash Flow Page
442
+ elif current_page == "cashflow":
443
+ st.markdown("## 💸 Cash Flow Analysis")
444
+
445
+ cash_flow_data = df[df['Statement_Type'] == 'Cash Flow']
446
+
447
+ if cash_flow_data.empty:
448
+ st.warning("No cash flow statement data found.")
449
+ st.markdown("### Cash Flow Analysis from Available Data:")
450
+
451
+ # Analyze cash changes from balance sheet
452
+ cash_data = df[df['Account_Name_English'].str.contains('Cash', case=False, na=False)]
453
+
454
+ if not cash_data.empty:
455
+ cash_2024 = cash_data['2024_Amount_NOK'].iloc[0]
456
+ cash_2023 = cash_data['2023_Amount_NOK'].iloc[0]
457
+ cash_change = cash_2024 - cash_2023
458
 
459
+ fig = go.Figure(go.Waterfall(
460
+ name="Cash Flow",
461
+ orientation="v",
462
+ measure=["absolute", "relative", "absolute"],
463
+ x=["Starting Cash (2023)", "Net Change", "Ending Cash (2024)"],
464
+ textposition="outside",
465
+ text=[f"{cash_2023:,.0f}", f"{cash_change:+,.0f}", f"{cash_2024:,.0f}"],
466
+ y=[cash_2023, cash_change, cash_2024],
467
+ connector={"line":{"color":"rgb(63, 63, 63)"}},
468
+ ))
469
 
470
+ fig.update_layout(
471
+ title="Cash Position Change 2023-2024",
472
+ showlegend=False,
473
+ yaxis_title="Amount (NOK)"
474
+ )
 
475
 
476
+ st.plotly_chart(fig, use_container_width=True)
 
 
 
 
 
477
 
478
+ # Cash metrics
479
+ col1, col2, col3 = st.columns(3)
 
 
 
 
 
 
 
 
 
 
 
480
 
481
+ with col1:
482
+ st.metric("Starting Cash", f"{cash_2023:,.0f} NOK")
483
+ with col2:
484
+ st.metric("Ending Cash", f"{cash_2024:,.0f} NOK")
485
+ with col3:
486
+ growth = (cash_change / cash_2023 * 100) if cash_2023 != 0 else 0
487
+ st.metric("Cash Growth", f"{growth:+.1f}%")
488
+
489
+ return
490
+
491
+ # If we have cash flow data, display it
492
+ st.subheader("🌊 Cash Flow Structure")
493
+
494
+ operating_cf = cash_flow_data[cash_flow_data['Account_Name_English'].str.contains('Operating', case=False, na=False)]
495
+ investing_cf = cash_flow_data[cash_flow_data['Account_Name_English'].str.contains('Investing', case=False, na=False)]
496
+ financing_cf = cash_flow_data[cash_flow_data['Account_Name_English'].str.contains('Financing', case=False, na=False)]
497
+
498
+ if not operating_cf.empty or not investing_cf.empty or not financing_cf.empty:
499
+ fig = go.Figure()
500
+
501
+ categories = []
502
+ values_2024 = []
503
+ values_2023 = []
504
+
505
+ for cf_type, cf_data in [("Operating", operating_cf), ("Investing", investing_cf), ("Financing", financing_cf)]:
506
+ if not cf_data.empty:
507
+ categories.append(cf_type)
508
+ values_2024.append(cf_data['2024_Amount_NOK'].iloc[0])
509
+ values_2023.append(cf_data['2023_Amount_NOK'].iloc[0])
510
+
511
+ fig.add_trace(go.Bar(name='2023', x=categories, y=values_2023))
512
+ fig.add_trace(go.Bar(name='2024', x=categories, y=values_2024))
513
+
514
+ fig.update_layout(
515
+ title="Cash Flow by Category",
516
+ xaxis_title="Cash Flow Type",
517
+ yaxis_title="Amount (NOK)",
518
+ barmode='group'
519
+ )
520
 
521
+ st.plotly_chart(fig, use_container_width=True)
 
522
 
523
+ # Financial Ratios Page
524
+ elif current_page == "ratios":
525
+ st.markdown("## 📊 Financial Ratios Center")
526
+
527
+ # Ratio categories
528
+ ratio_type = st.selectbox(
529
+ "Select Ratio Category",
530
+ ["Profitability", "Liquidity", "Growth", "All Ratios"]
531
+ )
532
+
533
+ metrics = analyzer.get_key_metrics()
534
+
535
+ st.subheader(f"📈 {ratio_type} Ratios")
536
+
537
+ # Calculate ratios based on available data
538
+ ratios = {}
539
+
540
+ if metrics['revenue_2024'] > 0:
541
+ ratios['Net Profit Margin'] = (metrics['net_profit_2024'] / metrics['revenue_2024']) * 100
542
+ ratios['Revenue Growth Rate'] = metrics['revenue_growth']
543
+
544
+ if metrics['net_profit_2023'] != 0:
545
+ ratios['Profit Growth Rate'] = metrics['profit_growth']
546
+
547
+ # Display ratios
548
+ if ratios:
549
+ cols = st.columns(len(ratios))
550
+
551
+ for i, (ratio_name, ratio_value) in enumerate(ratios.items()):
552
+ with cols[i]:
553
+ # Determine rating
554
+ if 'Margin' in ratio_name:
555
+ rating = 'A' if ratio_value > 20 else 'B' if ratio_value > 10 else 'C'
556
+ elif 'Growth' in ratio_name:
557
+ rating = 'A+' if ratio_value > 50 else 'A' if ratio_value > 20 else 'B'
558
+ else:
559
+ rating = 'B'
560
+
561
+ st.metric(
562
+ ratio_name,
563
+ f"{ratio_value:.1f}%",
564
+ delta=f"Rating: {rating}"
565
+ )
566
+
567
+ # Ratio definitions
568
+ st.subheader("📖 Ratio Definitions")
569
+
570
+ with st.expander("Net Profit Margin"):
571
+ st.markdown("""
572
+ **Formula:** (Net Profit / Revenue) × 100
573
+
574
+ **Interpretation:** Measures how much profit a company makes for every NOK of revenue.
575
+ - **A (>20%):** Excellent profitability
576
+ - **B (10-20%):** Good profitability
577
+ - **C (<10%):** Needs improvement
578
+ """)
579
+
580
+ with st.expander("Revenue Growth Rate"):
581
+ st.markdown("""
582
+ **Formula:** ((Current Year Revenue - Previous Year Revenue) / Previous Year Revenue) × 100
583
+
584
+ **Interpretation:** Measures the rate of revenue increase year-over-year.
585
+ - **A+ (>50%):** Exceptional growth
586
+ - **A (20-50%):** Strong growth
587
+ - **B (0-20%):** Moderate growth
588
+ """)
589
+
590
+ # AI Assistant Page
591
+ elif current_page == "ai":
592
+ st.markdown("## 🤖 AI Financial Assistant")
593
+
594
+ st.markdown("### 💬 Ask me about your financial data")
595
+
596
+ # Quick action buttons
597
+ st.markdown("#### 🎯 Quick Analysis")
598
+
599
+ col1, col2, col3 = st.columns(3)
600
 
601
  with col1:
602
+ if st.button("🏥 Health Check"):
603
+ st.markdown("### Financial Health Analysis")
604
+ insights = analyzer.generate_insights()
605
+ for insight in insights:
606
+ st.success(insight)
607
 
608
  with col2:
609
+ if st.button("⚠️ Risk Assessment"):
610
+ st.markdown("### Risk Analysis")
611
+ metrics = analyzer.get_key_metrics()
612
+
613
+ risks = []
614
+ if metrics['revenue_growth'] < 0:
615
+ risks.append("🔴 Revenue Decline Risk - Immediate attention needed")
616
+ if metrics['net_profit_2024'] < 0:
617
+ risks.append("🔴 Profitability Risk - Company is operating at a loss")
618
+
619
+ if not risks:
620
+ risks.append("🟢 No major risks identified in current data")
621
+
622
+ for risk in risks:
623
+ if "🔴" in risk:
624
+ st.error(risk)
625
+ else:
626
+ st.success(risk)
627
+
628
+ with col3:
629
+ if st.button("💡 Recommendations"):
630
+ st.markdown("### Strategic Recommendations")
631
+ metrics = analyzer.get_key_metrics()
632
+
633
+ recommendations = []
634
+
635
+ if metrics['revenue_growth'] > 100:
636
+ recommendations.append("🚀 Scale operations to support rapid growth")
637
+ recommendations.append("💰 Consider investing in infrastructure")
638
+
639
+ if metrics['net_profit_2024'] > 0 and metrics['net_profit_2023'] <= 0:
640
+ recommendations.append("✅ Maintain current profitable strategies")
641
+ recommendations.append("📊 Focus on sustainable growth")
642
+
643
+ recommendations.append("📈 Continue monitoring key financial metrics")
644
+ recommendations.append("🔍 Consider more detailed financial analysis")
645
+
646
+ for rec in recommendations:
647
+ st.info(rec)
648
+
649
+ # Chat interface
650
+ st.markdown("---")
651
+ st.markdown("#### 💭 Custom Analysis")
652
+
653
+ user_question = st.text_area(
654
+ "Ask a specific question about your financial data:",
655
+ placeholder="e.g., What are the main drivers of our revenue growth?"
656
+ )
657
+
658
+ if st.button("🔍 Analyze") and user_question:
659
+ st.markdown("### Analysis Result")
660
+
661
+ # Simple rule-based responses
662
+ question_lower = user_question.lower()
663
+
664
+ if 'revenue' in question_lower and 'growth' in question_lower:
665
+ metrics = analyzer.get_key_metrics()
666
+ st.markdown(f"""
667
+ **Revenue Growth Analysis:**
668
+
669
+ Your revenue grew from {metrics['revenue_2023']:,.0f} NOK in 2023 to {metrics['revenue_2024']:,.0f} NOK in 2024,
670
+ representing a {metrics['revenue_growth']:.1f}% increase.
671
+
672
+ This indicates {"exceptional" if metrics['revenue_growth'] > 100 else "strong" if metrics['revenue_growth'] > 20 else "moderate"}
673
+ business growth.
674
+ """)
675
+
676
+ elif 'profit' in question_lower:
677
+ metrics = analyzer.get_key_metrics()
678
+ st.markdown(f"""
679
+ **Profitability Analysis:**
680
+
681
+ Your net profit changed from {metrics['net_profit_2023']:,.0f} NOK in 2023 to {metrics['net_profit_2024']:,.0f} NOK in 2024.
682
+
683
+ {"The company achieved profitability turnaround! 🎉" if metrics['net_profit_2024'] > 0 and metrics['net_profit_2023'] <= 0 else
684
+ "Profit increased significantly! 📈" if metrics['profit_growth'] > 50 else
685
+ "Company maintains profitability ✅" if metrics['net_profit_2024'] > 0 else
686
+ "Focus needed on achieving profitability ⚠️"}
687
+ """)
688
+
689
+ else:
690
+ st.markdown(f"""
691
+ **General Financial Overview:**
692
+
693
+ Based on your uploaded data, here's what I can tell you:
694
+
695
+ {analyzer.generate_insights()[0] if analyzer.generate_insights() else "Your financial data has been processed successfully."}
696
+
697
+ For more specific analysis, try asking about:
698
+ - Revenue growth trends
699
+ - Profitability analysis
700
+ - Cost structure
701
+ - Financial health assessment
702
+ """)
703
+
704
+ # Data preview in sidebar
705
+ st.sidebar.markdown("---")
706
+ st.sidebar.subheader("📋 Data Preview")
707
+
708
+ if st.sidebar.checkbox("Show uploaded data"):
709
+ st.sidebar.dataframe(df.head(), use_container_width=True)
710
+
711
+ # Export functionality
712
+ st.sidebar.markdown("---")
713
+ st.sidebar.subheader("📤 Export")
714
+
715
+ if st.sidebar.button("📊 Generate Report"):
716
+ st.sidebar.success("Report functionality will be implemented in future versions!")
717
 
718
+ if __name__ == "__main__":
719
+ main()