File size: 15,838 Bytes
5b593c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
def render_financial_dashboard(startup_data, cash_flow_df):
    """
    Render the AI-powered financial dashboard page.
    
    This dashboard uses AI to analyze financial data and provide actionable insights
    to startup founders, helping them make better decisions about their runway,
    spending, and financial health.
    """
    st.markdown("<h1 class='main-header'>Financial Dashboard</h1>", unsafe_allow_html=True)
    st.markdown("<p class='sub-header'>AI-powered financial insights at a glance</p>", unsafe_allow_html=True)
    
    # How AI helps with financial dashboards
    with st.expander("ℹ️ How AI enhances your financial dashboard"):
        st.markdown("""
        ### How AI Powers Your Financial Dashboard
        
        The financial dashboard uses AI to transform raw financial data into actionable intelligence:
        
        - **Automated Analysis**: Instead of manually calculating runway and burn rates, our AI model analyzes your data and highlights critical trends
        - **Predictive Forecasting**: AI forecasts your runway using pattern recognition and predictive analytics to account for varying growth rates
        - **Anomaly Detection**: The system identifies unusual spending patterns or concerning financial trends that human analysis might miss
        - **Strategic Recommendations**: Based on your specific financial situation, the AI provides tailored recommendations to optimize your runway
        - **Benchmark Comparison**: Your metrics are automatically compared against industry standards for startups at your funding stage
        
        This helps founders save time, catch financial issues early, and make data-driven decisions without needing financial expertise.
        """)
    
    # AI Insights Summary
    insights_key = f"dashboard_{date.today().isoformat()}"
    if insights_key not in st.session_state.insights_cache:
        insights = generate_ai_response(f"""
        You are a financial advisor for startups. Based on this startup's data:
        - Current cash: ${startup_data['cash']}
        - Monthly burn rate: ${startup_data['burn_rate']}
        - Monthly revenue: ${startup_data['revenue']}
        - Monthly growth rate: {startup_data['growth_rate'] * 100}%
        
        Provide the top 3 most important financial insights that the founder should know today.
        Format each insight as a brief, action-oriented bullet point.
        """, simulate=True)
        st.session_state.insights_cache[insights_key] = insights
    
    with st.expander("πŸ“Š AI Financial Insights", expanded=True):
        st.markdown("<span class='ai-badge'>AI-Generated Insights</span>", unsafe_allow_html=True)
        st.markdown(st.session_state.insights_cache[insights_key])
    
    # 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']
    )
    
    # Determine status colors based on financial health indicators
    runway_status = "danger-metric" if runway_months < 6 else ("warning-metric" if runway_months < 9 else "good-metric")
    burn_status = "danger-metric" if startup_data['burn_rate'] > 100000 else ("warning-metric" if startup_data['burn_rate'] > 80000 else "good-metric")
    revenue_status = "good-metric" if startup_data['revenue'] > 20000 else ("warning-metric" if startup_data['revenue'] > 10000 else "danger-metric")
    
    with col1:
        st.markdown(f"""
        <div class='metric-card'>
            <p class='metric-label'>Current Cash</p>
            <p class='metric-value'>${startup_data['cash']:,}</p>
        </div>
        """, unsafe_allow_html=True)
    
    with col2:
        st.markdown(f"""
        <div class='metric-card'>
            <p class='metric-label'>Monthly Burn</p>
            <p class='metric-value {burn_status}'>${startup_data['burn_rate']:,}</p>
        </div>
        """, unsafe_allow_html=True)
    
    with col3:
        st.markdown(f"""
        <div class='metric-card'>
            <p class='metric-label'>Monthly Revenue</p>
            <p class='metric-value {revenue_status}'>${startup_data['revenue']:,}</p>
        </div>
        """, unsafe_allow_html=True)
    
    with col4:
        st.markdown(f"""
        <div class='metric-card'>
            <p class='metric-label'>Runway</p>
            <p class='metric-value {runway_status}'>{runway_months} months</p>
        </div>
        """, unsafe_allow_html=True)
    
    # 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 ($)'},
                     color_discrete_sequence=['#0066cc'])
        fig.add_hline(y=0, line_dash="dash", line_color="red", annotation_text="Out of Cash")
        fig.update_layout(
            height=400,
            plot_bgcolor='rgba(240,247,255,0.8)',
            xaxis_title="Date",
            yaxis_title="Cash Balance ($)",
            font=dict(family="Arial, sans-serif", size=12),
            margin=dict(l=20, r=20, t=40, b=20),
        )
        st.plotly_chart(fig, use_container_width=True)
        
        # Get analysis from Gemini
        with st.expander("πŸ” AI Financial Analysis", expanded=True):
            # Use cache to avoid repeated API calls
            analysis_key = f"runway_{date.today().isoformat()}"
            if analysis_key not in st.session_state.insights_cache:
                analysis = get_runway_analysis(startup_data)
                st.session_state.insights_cache[analysis_key] = analysis
                
            st.markdown("<span class='ai-badge'>AI Financial Analysis</span>", unsafe_allow_html=True)
            st.markdown(st.session_state.insights_cache[analysis_key])
    
    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'},
                    color_discrete_sequence=['#28a745', '#dc3545'])
        fig.update_layout(
            height=400,
            plot_bgcolor='rgba(240,247,255,0.8)',
            xaxis_title="Month",
            yaxis_title="Amount ($)",
            font=dict(family="Arial, sans-serif", size=12),
            legend_title="",
            margin=dict(l=20, r=20, t=40, b=20),
        )
        st.plotly_chart(fig, use_container_width=True)
        
        # Calculate revenue growth
        revenue_growth = [(cash_flow_df['Revenue'].iloc[i] / cash_flow_df['Revenue'].iloc[i-1] - 1) * 100 if i > 0 else 0 
                          for i in range(len(cash_flow_df))]
        avg_growth = sum(revenue_growth[1:]) / len(revenue_growth[1:])
        
        col1, col2 = st.columns(2)
        with col1:
            st.metric("Average Monthly Revenue Growth", f"{avg_growth:.1f}%")
        with col2:
            expense_growth = (cash_flow_df['Total_Expenses'].iloc[-1] / cash_flow_df['Total_Expenses'].iloc[0] - 1) * 100
            st.metric("Total Expense Growth", f"{expense_growth:.1f}%", delta=f"{expense_growth - avg_growth:.1f}%", delta_color="inverse")
    
    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 ($)'},
                     color_discrete_sequence=['#dc3545'])
        fig.update_layout(
            height=400,
            plot_bgcolor='rgba(240,247,255,0.8)',
            xaxis_title="Month",
            yaxis_title="Net Burn ($)",
            font=dict(family="Arial, sans-serif", size=12),
            margin=dict(l=20, r=20, t=40, b=20),
        )
        
        # Add efficiency ratio as a second y-axis
        efficiency_ratio = [cash_flow_df['Revenue'].iloc[i] / cash_flow_df['Total_Expenses'].iloc[i] * 100 
                            for i in range(len(cash_flow_df))]
        
        fig.add_trace(go.Scatter(
            x=cash_flow_df['Month'], 
            y=efficiency_ratio,
            name='Efficiency Ratio (%)',
            yaxis='y2',
            line=dict(color='#0066cc', width=2, dash='dot')
        ))
        
        fig.update_layout(
            yaxis2=dict(
                title='Efficiency Ratio (%)',
                overlaying='y',
                side='right',
                range=[0, max(efficiency_ratio) * 1.2]
            )
        )
        
        st.plotly_chart(fig, use_container_width=True)
        
        with st.expander("πŸ”Ž Understanding Efficiency Ratio"):
            st.info("The efficiency ratio measures how efficiently your startup is generating revenue relative to expenses. A higher percentage means you're getting more revenue per dollar spent. Venture-backed startups typically aim for at least 40% before Series B funding.")
    
    # 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]
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        fig = px.pie(values=expense_values, names=expense_categories, 
                    title="Current Month Expense Breakdown",
                    color_discrete_sequence=px.colors.sequential.Blues_r)
        fig.update_layout(
            height=400,
            font=dict(family="Arial, sans-serif", size=12),
            margin=dict(l=20, r=20, t=40, b=20),
        )
        fig.update_traces(textposition='inside', textinfo='percent+label')
        st.plotly_chart(fig, use_container_width=True)
    
    with col2:
        # Expense analysis
        st.markdown("<h4>Expense Analysis</h4>", unsafe_allow_html=True)
        
        # Calculate industry benchmarks (simulated)
        benchmarks = {
            "Payroll": "70-80%",
            "Marketing": "10-15%",
            "Office": "5-8%",
            "Software": "3-5%"
        }
        
        # Create a table with expense categories, amounts, and % of total
        expense_df = pd.DataFrame({
            "Category": expense_categories,
            "Amount": expense_values,
            "% of Total": [v / sum(expense_values) * 100 for v in expense_values]
        })
        
        # Add benchmark column
        expense_df["Industry Benchmark"] = expense_df["Category"].map(
            lambda x: benchmarks.get(x, "N/A")
        )
        
        # Format the dataframe for display
        formatted_df = expense_df.copy()
        formatted_df["Amount"] = formatted_df["Amount"].apply(lambda x: f"${x:,.0f}")
        formatted_df["% of Total"] = formatted_df["% of Total"].apply(lambda x: f"{x:.1f}%")
        
        st.table(formatted_df)
        
        # AI-powered spending optimization
        with st.expander("πŸ’‘ AI Spending Optimization"):
            st.markdown("<span class='ai-badge'>AI Recommendation</span>", unsafe_allow_html=True)
            
            # Use cache to avoid repeated API calls
            spending_key = f"spending_{date.today().isoformat()}"
            if spending_key not in st.session_state.insights_cache:
                spending_recommendation = generate_ai_response("""
                Based on your expense breakdown, recommend 2-3 specific ways to optimize spending to extend runway.
                Focus on industry best practices for seed-stage startups.
                """, simulate=True)
                st.session_state.insights_cache[spending_key] = spending_recommendation
                
            st.markdown(st.session_state.insights_cache[spending_key])
            
    # Fundraising Readiness Assessment
    st.subheader("Fundraising Readiness")
    
    # Get AI analysis of fundraising readiness
    fundraising_key = f"fundraising_{date.today().isoformat()}"
    if fundraising_key not in st.session_state.insights_cache:
        fundraising_analysis = get_fundraising_readiness_analysis(startup_data, cash_flow_df)
        st.session_state.insights_cache[fundraising_key] = fundraising_analysis
    
    st.markdown("<div class='advisor-card'>", unsafe_allow_html=True)
    st.markdown("<span class='ai-badge'>AI Fundraising Assessment</span>", unsafe_allow_html=True)
    st.markdown(f"<p class='advice-text'>{st.session_state.insights_cache[fundraising_key]}</p>", unsafe_allow_html=True)
    st.markdown("</div>", unsafe_allow_html=True)
    
    # Call-to-action for advisor
    st.info("πŸ“… Need personalized guidance on fundraising? [Book a session](#book-a-session) with our AI financial advisor.")

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}%

    Provide a detailed analysis of their runway and financial health. Include:
    1. Exact runway calculation in months
    2. Assessment of financial health (critical, concerning, stable, or healthy)
    3. Benchmarks compared to similar seed-stage startups
    4. Three specific, actionable recommendations to improve runway
    5. Key metrics they should focus on

    Format your response in a structured, easy-to-read format with clear sections and bullet points.
    """
    
    return generate_ai_response(prompt)

def get_fundraising_readiness_analysis(startup_data, cash_flow_df):
    """Get AI analysis of fundraising readiness."""
    metrics = {
        "MRR Growth": f"{(cash_flow_df['Revenue'].iloc[-1] / cash_flow_df['Revenue'].iloc[-2] - 1) * 100:.1f}%",
        "Gross Margin": f"{(cash_flow_df['Revenue'].iloc[-1] - cash_flow_df['Total_Expenses'].iloc[-1] / 2) / cash_flow_df['Revenue'].iloc[-1] * 100:.1f}%",
        "CAC": "$950",  # Example value
        "LTV": "$4,500",  # Example value
        "Churn": "3.2%",  # Example value
    }
    
    metrics_text = "\n".join([f"- {k}: {v}" for k, v in metrics.items()])
    
    prompt = f"""
    You are a startup fundraising advisor. Analyze this startup's readiness for their next funding round:
    
    Company Profile:
    - Stage: {startup_data['stage']}
    - Last Funding: {startup_data['last_funding']}
    - Current Cash: ${startup_data['cash']}
    - Monthly Burn: ${startup_data['burn_rate']}
    - Runway: {startup_data['cash'] / (startup_data['burn_rate'] - startup_data['revenue']):.1f} months
    
    Key Metrics:
    {metrics_text}
    
    Provide a comprehensive fundraising readiness assessment:
    1. Overall fundraising readiness score (0-10)
    2. Assessment of current metrics compared to investor expectations for next round
    3. Identify the 3 most critical metrics to improve before fundraising
    4. Recommend specific targets for each key metric
    5. Suggest timeline and specific milestones for fundraising preparation
    6. Estimate reasonable valuation range based on metrics and market conditions
    
    Be specific with numbers, timelines, and actionable targets.
    """
    
    return generate_ai_response(prompt)