File size: 24,756 Bytes
a3e7179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import google.generativeai as genai
import os
from datetime import datetime, timedelta
import base64
from io import BytesIO

# Initialize page configuration
st.set_page_config(
    page_title="StartupFinancePilot",
    page_icon="💰",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Constants
DEFAULT_GROWTH_RATE = 0.08  # 8% monthly growth
DEFAULT_BURN_RATE = 85000   # $85,000 monthly burn
ENGINEER_SALARY = 10000     # $10,000 monthly cost per engineer ($120K/year)
DEFAULT_MARKETING_BUDGET = 10000  # $10,000 monthly marketing budget

# Sample data
@st.cache_data
def load_sample_data():
    # TechHealth AI data
    startup_data = {
        "name": "TechHealth AI",
        "stage": "Seed",
        "founded": "18 months ago",
        "employees": 12,
        "last_funding": "$1.2M seed round 10 months ago",
        "cash": 320000,
        "burn_rate": 85000,
        "revenue": 15000,
        "growth_rate": 0.08
    }
    
    # Cash flow history
    cash_flow_data = {
        "Month": [f"Month {i}" for i in range(1, 11)],
        "Revenue": [8000, 8500, 9200, 10000, 10800, 11700, 12600, 13600, 14700, 15800],
        "Payroll": [60000, 60000, 62000, 62000, 65000, 65000, 70000, 70000, 75000, 75000],
        "Marketing": [8000, 9000, 10000, 12000, 15000, 18000, 15000, 12000, 10000, 8000],
        "Office": [5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000],
        "Software": [3000, 3200, 3500, 3800, 4000, 4200, 4500, 4800, 5000, 5200],
        "Travel": [2000, 1800, 2500, 3000, 4000, 4500, 3500, 3000, 2500, 2000],
        "Legal": [1500, 1000, 800, 1200, 800, 2000, 1500, 1000, 3000, 1200],
        "Misc": [1000, 1200, 1300, 1500, 1700, 1800, 2000, 2200, 2500, 2800]
    }
    
    # Add calculated fields
    df = pd.DataFrame(cash_flow_data)
    df["Total_Expenses"] = df[["Payroll", "Marketing", "Office", "Software", "Travel", "Legal", "Misc"]].sum(axis=1)
    df["Net_Burn"] = df["Total_Expenses"] - df["Revenue"]
    
    # Transaction data
    transactions = pd.DataFrame([
        {"Date": "2023-11-05", "Category": "Travel", "Vendor": "Caribbean Cruises", "Amount": 8500, "Description": "Team Retreat Planning", "Flag": "Suspicious"},
        {"Date": "2023-11-12", "Category": "Marketing", "Vendor": "LuxuryGifts Inc", "Amount": 4200, "Description": "Client Appreciation", "Flag": "Suspicious"},
        {"Date": "2023-11-22", "Category": "Office", "Vendor": "Premium Furniture", "Amount": 12000, "Description": "Office Upgrades", "Flag": "Suspicious"},
        {"Date": "2023-11-28", "Category": "Consulting", "Vendor": "Strategic Vision LLC", "Amount": 7500, "Description": "Strategy Consulting", "Flag": "Suspicious"},
        {"Date": "2023-12-05", "Category": "Software", "Vendor": "Personal Apple Store", "Amount": 3200, "Description": "Development Tools", "Flag": "Suspicious"},
        {"Date": "2023-12-12", "Category": "Legal", "Vendor": "Anderson Brothers", "Amount": 5800, "Description": "Legal Services", "Flag": "Normal"},
        {"Date": "2023-12-20", "Category": "Payroll", "Vendor": "November Payroll", "Amount": 75000, "Description": "Monthly Payroll", "Flag": "Normal"},
        {"Date": "2023-12-22", "Category": "Marketing", "Vendor": "Google Ads", "Amount": 8000, "Description": "Ad Campaign", "Flag": "Normal"},
        {"Date": "2023-12-25", "Category": "Office", "Vendor": "WeWork", "Amount": 5000, "Description": "Monthly Rent", "Flag": "Normal"},
        {"Date": "2023-12-28", "Category": "Software", "Vendor": "AWS", "Amount": 5200, "Description": "Cloud Services", "Flag": "Normal"},
        {"Date": "2024-01-05", "Category": "Travel", "Vendor": "Delta Airlines", "Amount": 1200, "Description": "Client Meeting Travel", "Flag": "Normal"},
        {"Date": "2024-01-10", "Category": "Marketing", "Vendor": "Facebook Ads", "Amount": 4500, "Description": "Social Media Campaign", "Flag": "Normal"},
        {"Date": "2024-01-15", "Category": "Software", "Vendor": "Atlassian", "Amount": 2800, "Description": "Development Tools", "Flag": "Normal"},
        {"Date": "2024-01-20", "Category": "Payroll", "Vendor": "January Payroll", "Amount": 75000, "Description": "Monthly Payroll", "Flag": "Normal"},
        {"Date": "2024-01-25", "Category": "Office", "Vendor": "WeWork", "Amount": 5000, "Description": "Monthly Rent", "Flag": "Normal"}
    ])
    
    return startup_data, df, transactions

# Setup Gemini API (with API key from secrets)
def setup_genai():
    if 'GOOGLE_API_KEY' in st.secrets:
        genai.configure(api_key=st.secrets['GOOGLE_API_KEY'])
        return True
    else:
        st.warning("Google API key not found. Please add it to the secrets.")
        return False

# Financial modeling functions
def calculate_runway(initial_cash, monthly_burn, monthly_revenue, growth_rate, months=24):
    """Calculate runway based on current burn rate and revenue growth."""
    dates = [datetime.now() + timedelta(days=30*i) for i in range(months)]
    df = pd.DataFrame(index=dates, columns=['Cash', 'Revenue', 'Expenses', 'Net_Burn', 'Cumulative_Cash'])
    
    current_cash = initial_cash
    current_revenue = monthly_revenue
    df.iloc[0, df.columns.get_loc('Cash')] = current_cash
    df.iloc[0, df.columns.get_loc('Revenue')] = current_revenue
    df.iloc[0, df.columns.get_loc('Expenses')] = monthly_burn
    df.iloc[0, df.columns.get_loc('Net_Burn')] = monthly_burn - current_revenue
    df.iloc[0, df.columns.get_loc('Cumulative_Cash')] = current_cash
    
    runway_months = months
    for i in range(1, months):
        current_revenue = current_revenue * (1 + growth_rate)
        net_burn = monthly_burn - current_revenue
        current_cash = current_cash - net_burn
        
        df.iloc[i, df.columns.get_loc('Cash')] = current_cash
        df.iloc[i, df.columns.get_loc('Revenue')] = current_revenue
        df.iloc[i, df.columns.get_loc('Expenses')] = monthly_burn
        df.iloc[i, df.columns.get_loc('Net_Burn')] = net_burn
        df.iloc[i, df.columns.get_loc('Cumulative_Cash')] = current_cash
        
        if current_cash <= 0:
            runway_months = i
            break
    
    return runway_months, df

def simulate_decision(initial_cash, monthly_burn, monthly_revenue, growth_rate, 
                     new_expenses=0, new_hires=0, new_marketing=0, growth_impact=0):
    """Simulate the impact of a business decision on runway."""
    # Calculate current runway
    current_runway, current_df = calculate_runway(initial_cash, monthly_burn, monthly_revenue, growth_rate)
    
    # Calculate additional expenses
    additional_expenses = new_expenses + (new_hires * ENGINEER_SALARY) + new_marketing
    
    # Calculate new runway
    new_runway, new_df = calculate_runway(
        initial_cash,
        monthly_burn + additional_expenses,
        monthly_revenue,
        growth_rate + growth_impact
    )
    
    return current_runway, new_runway, current_df, new_df

def detect_suspicious_transactions(transactions_df):
    """Simple rule-based suspicious transaction detection."""
    df = transactions_df.copy()
    
    # Define thresholds for each category
    category_thresholds = {
        "Travel": 3000,
        "Marketing": 10000,
        "Office": 7000,
        "Software": 6000,
        "Consulting": 5000,
        "Legal": 6000
    }
    
    # Define suspicious terms
    suspicious_terms = ['luxury', 'cruise', 'premium', 'personal', 'gift']
    
    # Add suspicious column
    df['Suspicious'] = False
    df['Reason'] = ""
    
    # Check for suspicious patterns
    for idx, row in df.iterrows():
        reasons = []
        
        # Check if amount exceeds category threshold
        if row['Category'] in category_thresholds:
            if row['Amount'] > category_thresholds[row['Category']]:
                reasons.append(f"Amount exceeds typical spending for {row['Category']}")
        
        # Check for suspicious vendors or descriptions
        if any(term in str(row['Vendor']).lower() for term in suspicious_terms):
            reasons.append(f"Vendor name contains suspicious term")
        
        if any(term in str(row['Description']).lower() for term in suspicious_terms):
            reasons.append(f"Description contains suspicious term")
        
        # Mark as suspicious if any reasons
        if reasons:
            df.at[idx, 'Suspicious'] = True
            df.at[idx, 'Reason'] = "; ".join(reasons)
    
    return df

# Gemini prompt functions
def get_runway_analysis(financial_data):
    """Get runway analysis using Gemini."""
    prompt = f"""
    You are a financial advisor for startups. Analyze this startup's financial data:
    - Current cash: ${financial_data['cash']}
    - Monthly burn rate: ${financial_data['burn_rate']}
    - Monthly revenue: ${financial_data['revenue']}
    - Monthly growth rate: {financial_data['growth_rate'] * 100}%

    Calculate and explain their runway, financial health, and recommendations in a concise paragraph.
    """
    
    model = genai.GenerativeModel('gemini-pro')
    response = model.generate_content(prompt)
    
    return response.text

def get_decision_analysis(question, financial_data):
    """Get analysis for a specific decision."""
    prompt = f"""
    You are a financial advisor for startups. A founder asks:
    "{question}"

    Here's their current financial situation:
    - Current cash: ${financial_data['cash']}
    - Monthly burn rate: ${financial_data['burn_rate']}
    - Monthly revenue: ${financial_data['revenue']}
    - Monthly growth rate: {financial_data['growth_rate'] * 100}%

    Analyze how this decision would impact their runway and financial health.
    Provide specific recommendations in 3-4 concise sentences.
    """
    
    model = genai.GenerativeModel('gemini-pro')
    response = model.generate_content(prompt)
    
    return response.text

def get_fraud_analysis(transactions_df):
    """Get analysis of potentially fraudulent transactions."""
    suspicious_df = transactions_df[transactions_df['Suspicious']]
    
    if len(suspicious_df) == 0:
        return "No suspicious transactions detected."
    
    transactions_text = suspicious_df.to_string(index=False)
    
    prompt = f"""
    You are a financial advisor specializing in startup spending oversight.
    Review these flagged transactions:

    {transactions_text}

    Explain why these transactions might concern investors and what actions the startup should take.
    Keep your response to 4-5 concise sentences focused on the most concerning issues.
    """
    
    model = genai.GenerativeModel('gemini-pro')
    response = model.generate_content(prompt)
    
    return response.text

def get_advisory_guidance(question, financial_data):
    """Get strategic guidance for a startup question."""
    prompt = f"""
    You are a strategic financial advisor for startups. A founder asks:
    "{question}"

    Here's their current financial situation:
    - Stage: {financial_data['stage']}
    - Current cash: ${financial_data['cash']}
    - Monthly burn rate: ${financial_data['burn_rate']}
    - Monthly revenue: ${financial_data['revenue']}
    - Monthly growth rate: {financial_data['growth_rate'] * 100}%
    - Last funding: {financial_data['last_funding']}
    - Team size: {financial_data['employees']}

    Provide specific, actionable advice addressing their question in 3-4 concise sentences.
    Include timelines and metrics where relevant.
    """
    
    model = genai.GenerativeModel('gemini-pro')
    response = model.generate_content(prompt)
    
    return response.text

# UI Components
def create_sidebar():
    """Create sidebar with company profile and filters."""
    st.sidebar.title("StartupFinancePilot")
    st.sidebar.image("https://img.freepik.com/premium-vector/business-finance-analytics-logo-design-vector-template_67715-552.jpg", width=150)
    
    # Company profile
    startup_data, _, _ = load_sample_data()
    
    st.sidebar.header("Company Profile")
    st.sidebar.write(f"**{startup_data['name']}**")
    st.sidebar.write(f"Stage: {startup_data['stage']}")
    st.sidebar.write(f"Founded: {startup_data['founded']}")
    st.sidebar.write(f"Employees: {startup_data['employees']}")
    st.sidebar.write(f"Last Funding: {startup_data['last_funding']}")
    
    # App navigation
    st.sidebar.header("Navigation")
    page = st.sidebar.radio("Go to", ["Financial Dashboard", "Decision Simulator", "Fund Monitoring", "Voice Advisory"])
    
    return page

def render_financial_dashboard(startup_data, cash_flow_df):
    """Render financial dashboard page."""
    st.title("Financial Dashboard")
    
    # Key metrics
    col1, col2, col3, col4 = st.columns(4)
    
    # Calculate runway
    runway_months, runway_df = calculate_runway(
        startup_data['cash'], 
        startup_data['burn_rate'], 
        startup_data['revenue'], 
        startup_data['growth_rate']
    )
    
    with col1:
        st.metric("Current Cash", f"${startup_data['cash']:,}")
    with col2:
        st.metric("Monthly Burn", f"${startup_data['burn_rate']:,}")
    with col3:
        st.metric("Monthly Revenue", f"${startup_data['revenue']:,}")
    with col4:
        st.metric("Runway", f"{runway_months} months")
    
    # Financial charts
    st.subheader("Financial Overview")
    
    tab1, tab2, tab3 = st.tabs(["Runway Projection", "Revenue vs. Expenses", "Burn Rate Trend"])
    
    with tab1:
        # Runway projection chart
        fig = px.line(runway_df.reset_index(), x='index', y='Cumulative_Cash', 
                     title="Cash Runway Projection",
                     labels={'index': 'Date', 'Cumulative_Cash': 'Remaining Cash'})
        fig.add_hline(y=0, line_dash="dash", line_color="red")
        fig.update_layout(height=400)
        st.plotly_chart(fig, use_container_width=True)
        
        # Get analysis from Gemini
        if setup_genai():
            with st.expander("AI Financial Analysis"):
                analysis = get_runway_analysis(startup_data)
                st.write(analysis)
    
    with tab2:
        # Revenue vs Expenses chart
        rev_exp_df = cash_flow_df.copy()
        fig = px.bar(rev_exp_df, x='Month', y=['Revenue', 'Total_Expenses'],
                    title="Revenue vs. Expenses",
                    barmode='group',
                    labels={'value': 'Amount ($)', 'variable': 'Category'})
        fig.update_layout(height=400)
        st.plotly_chart(fig, use_container_width=True)
    
    with tab3:
        # Burn rate trend
        fig = px.line(cash_flow_df, x='Month', y='Net_Burn',
                     title="Monthly Net Burn Trend",
                     labels={'Net_Burn': 'Net Burn ($)'})
        fig.update_layout(height=400)
        st.plotly_chart(fig, use_container_width=True)
    
    # Expense breakdown
    st.subheader("Expense Breakdown")
    
    # Last month expenses
    last_month = cash_flow_df.iloc[-1]
    expense_categories = ['Payroll', 'Marketing', 'Office', 'Software', 'Travel', 'Legal', 'Misc']
    expense_values = [last_month[cat] for cat in expense_categories]
    
    fig = px.pie(values=expense_values, names=expense_categories, 
                title="Current Month Expense Breakdown")
    fig.update_layout(height=400)
    st.plotly_chart(fig, use_container_width=True)

def render_decision_simulator(startup_data):
    """Render decision simulator page."""
    st.title("Decision Simulator")
    
    st.write("Simulate the impact of business decisions on your startup's financial runway.")
    
    # Decision input form
    with st.form("decision_form"):
        st.subheader("Enter Decision Parameters")
        
        col1, col2 = st.columns(2)
        
        with col1:
            new_hires = st.number_input("New Engineering Hires", min_value=0, max_value=10, value=0, 
                                         help=f"Each engineer costs ${ENGINEER_SALARY:,} per month")
            new_marketing = st.number_input("Additional Monthly Marketing Budget", min_value=0, max_value=50000, value=0, step=1000,
                                           help="Additional marketing spend per month")
        
        with col2:
            other_expenses = st.number_input("Other Additional Monthly Expenses", min_value=0, max_value=50000, value=0, step=1000,
                                            help="Any other additional monthly expenses")
            growth_impact = st.slider("Estimated Impact on Monthly Growth Rate", min_value=0.0, max_value=0.10, value=0.0, step=0.01, 
                                     format="%.2f",
                                     help="Estimated increase in monthly growth rate due to these investments")
        
        question = st.text_area("Describe your decision scenario", height=100, 
                               placeholder="E.g., We're considering hiring two more engineers and increasing our marketing budget...")
        
        submitted = st.form_submit_button("Simulate Decision")
    
    if submitted:
        # Calculate current and new runway
        current_runway, new_runway, current_df, new_df = simulate_decision(
            startup_data['cash'],
            startup_data['burn_rate'],
            startup_data['revenue'],
            startup_data['growth_rate'],
            other_expenses,
            new_hires,
            new_marketing,
            growth_impact
        )
        
        # Display results
        st.subheader("Decision Impact")
        
        # Summary metrics
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.metric("Current Runway", f"{current_runway} months")
        with col2:
            st.metric("New Runway", f"{new_runway} months", delta=new_runway-current_runway)
        with col3:
            new_burn = startup_data['burn_rate'] + other_expenses + (new_hires * ENGINEER_SALARY) + new_marketing
            st.metric("New Monthly Burn", f"${new_burn:,}", delta=new_burn-startup_data['burn_rate'], delta_color="inverse")
        
        # Cash projection comparison
        st.subheader("Cash Projection Comparison")
        
        # Combine dataframes for comparison
        current_df['Scenario'] = 'Current'
        new_df['Scenario'] = 'After Decision'
        
        combined_df = pd.concat([current_df, new_df])
        combined_df = combined_df.reset_index()
        combined_df = combined_df.rename(columns={'index': 'Date'})
        
        # Plot comparison
        fig = px.line(combined_df, x='Date', y='Cumulative_Cash', color='Scenario',
                     title="Cash Runway Comparison",
                     labels={'Cumulative_Cash': 'Remaining Cash'})
        fig.add_hline(y=0, line_dash="dash", line_color="red")
        fig.update_layout(height=400)
        st.plotly_chart(fig, use_container_width=True)
        
        # Get AI analysis
        if setup_genai() and question:
            st.subheader("AI Analysis")
            analysis = get_decision_analysis(question, startup_data)
            st.success(analysis)

def render_fund_monitoring(transactions_df):
    """Render fund monitoring page."""
    st.title("Investor Fund Monitoring")
    
    st.write("Monitor your startup's spending to maintain investor trust and ensure proper fund usage.")
    
    # Process transactions to detect suspicious ones
    processed_df = detect_suspicious_transactions(transactions_df)
    
    # Summary metrics
    total_transactions = len(processed_df)
    suspicious_transactions = processed_df[processed_df['Suspicious']].copy()
    suspicious_count = len(suspicious_transactions)
    suspicious_amount = suspicious_transactions['Amount'].sum()
    total_amount = processed_df['Amount'].sum()
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.metric("Total Transactions", total_transactions)
    with col2:
        st.metric("Flagged Transactions", suspicious_count, 
                 delta=f"{suspicious_count/total_transactions:.1%}" if total_transactions > 0 else "0%")
    with col3:
        st.metric("Flagged Amount", f"${suspicious_amount:,}", 
                delta=f"{suspicious_amount/total_amount:.1%}" if total_amount > 0 else "0%")
    
    # Tabs for different views
    tab1, tab2 = st.tabs(["Flagged Transactions", "All Transactions"])
    
    with tab1:
        if suspicious_count > 0:
            st.dataframe(suspicious_transactions[['Date', 'Category', 'Vendor', 'Amount', 'Description', 'Reason']], 
                        use_container_width=True)
            
            # Get AI analysis of suspicious transactions
            if setup_genai():
                st.subheader("AI Fraud Analysis")
                analysis = get_fraud_analysis(suspicious_transactions)
                st.warning(analysis)
        else:
            st.success("No suspicious transactions detected.")
    
    with tab2:
        st.dataframe(processed_df[['Date', 'Category', 'Vendor', 'Amount', 'Description', 'Suspicious']], 
                    use_container_width=True)
    
    # Spending patterns
    st.subheader("Spending Patterns")
    
    # Category breakdown
    category_spending = processed_df.groupby('Category')['Amount'].sum().reset_index()
    
    fig = px.bar(category_spending, x='Category', y='Amount',
                title="Spending by Category",
                labels={'Amount': 'Total Spent ($)'})
    fig.update_layout(height=400)
    st.plotly_chart(fig, use_container_width=True)
    
    # Time series of spending
    processed_df['Date'] = pd.to_datetime(processed_df['Date'])
    processed_df['Week'] = processed_df['Date'].dt.isocalendar().week
    weekly_spending = processed_df.groupby(['Week', 'Category'])['Amount'].sum().reset_index()
    
    fig = px.line(weekly_spending, x='Week', y='Amount', color='Category',
                title="Weekly Spending Trends",
                labels={'Amount': 'Amount Spent ($)'})
    fig.update_layout(height=400)
    st.plotly_chart(fig, use_container_width=True)

def render_voice_advisory(startup_data):
    """Render voice advisory page."""
    st.title("Financial Advisory")
    
    st.write("Get strategic financial guidance from our AI advisor.")
    
    # Common financial questions
    st.subheader("Select a Question or Ask Your Own")
    
    common_questions = [
        "Select a question...",
        "How much runway do we have at our current burn rate?",
        "If we hire two more engineers, how will it affect our runway?",
        "Should we increase our marketing spend given our current growth rate?",
        "Is our current burn rate sustainable given our revenue growth?",
        "Should we consider raising a bridge round in the next 3 months?",
        "What's our projected cash position at the end of next quarter?",
        "Are there any concerning spending patterns in our recent expenses?",
        "What metrics should we focus on improving before our next fundraise?"
    ]
    
    selected_question = st.selectbox("Common Questions", common_questions)
    
    custom_question = st.text_area("Or ask your own question", height=100,
                                 placeholder="Enter your financial question here...")
    
    question = custom_question if custom_question else (selected_question if selected_question != common_questions[0] else "")
    
    if st.button("Get Advice") and question and setup_genai():
        with st.spinner("Generating advisory response..."):
            advice = get_advisory_guidance(question, startup_data)
            
            # Display advice
            st.subheader("Financial Advice")
            st.info(advice)
            
            # Note about voice generation
            st.write("In the full version, this advice would be delivered as a voice response using ElevenLabs.")
            
            # Add a sample conversation
            with st.expander("View sample conversation"):
                st.write("**You:** " + question)
                st.write("**Financial Advisor:** " + advice)

# Main application
def main():
    # Load sample data
    startup_data, cash_flow_df, transactions_df = load_sample_data()
    
    # Create sidebar and get selected page
    page = create_sidebar()
    
    # Render selected page
    if page == "Financial Dashboard":
        render_financial_dashboard(startup_data, cash_flow_df)
    elif page == "Decision Simulator":
        render_decision_simulator(startup_data)
    elif page == "Fund Monitoring":
        render_fund_monitoring(transactions_df)
    elif page == "Voice Advisory":
        render_voice_advisory(startup_data)

if __name__ == "__main__":
    main()