walaa2022 commited on
Commit
25a5fd6
·
verified ·
1 Parent(s): 62489d9

Delete dashboard-page.py

Browse files
Files changed (1) hide show
  1. dashboard-page.py +0 -342
dashboard-page.py DELETED
@@ -1,342 +0,0 @@
1
- def render_financial_dashboard(startup_data, cash_flow_df):
2
- """
3
- Render the AI-powered financial dashboard page.
4
-
5
- This dashboard uses AI to analyze financial data and provide actionable insights
6
- to startup founders, helping them make better decisions about their runway,
7
- spending, and financial health.
8
- """
9
- st.markdown("<h1 class='main-header'>Financial Dashboard</h1>", unsafe_allow_html=True)
10
- st.markdown("<p class='sub-header'>AI-powered financial insights at a glance</p>", unsafe_allow_html=True)
11
-
12
- # How AI helps with financial dashboards
13
- with st.expander("ℹ️ How AI enhances your financial dashboard"):
14
- st.markdown("""
15
- ### How AI Powers Your Financial Dashboard
16
-
17
- The financial dashboard uses AI to transform raw financial data into actionable intelligence:
18
-
19
- - **Automated Analysis**: Instead of manually calculating runway and burn rates, our AI model analyzes your data and highlights critical trends
20
- - **Predictive Forecasting**: AI forecasts your runway using pattern recognition and predictive analytics to account for varying growth rates
21
- - **Anomaly Detection**: The system identifies unusual spending patterns or concerning financial trends that human analysis might miss
22
- - **Strategic Recommendations**: Based on your specific financial situation, the AI provides tailored recommendations to optimize your runway
23
- - **Benchmark Comparison**: Your metrics are automatically compared against industry standards for startups at your funding stage
24
-
25
- This helps founders save time, catch financial issues early, and make data-driven decisions without needing financial expertise.
26
- """)
27
-
28
- # AI Insights Summary
29
- insights_key = f"dashboard_{date.today().isoformat()}"
30
- if insights_key not in st.session_state.insights_cache:
31
- insights = generate_ai_response(f"""
32
- You are a financial advisor for startups. Based on this startup's data:
33
- - Current cash: ${startup_data['cash']}
34
- - Monthly burn rate: ${startup_data['burn_rate']}
35
- - Monthly revenue: ${startup_data['revenue']}
36
- - Monthly growth rate: {startup_data['growth_rate'] * 100}%
37
-
38
- Provide the top 3 most important financial insights that the founder should know today.
39
- Format each insight as a brief, action-oriented bullet point.
40
- """, simulate=True)
41
- st.session_state.insights_cache[insights_key] = insights
42
-
43
- with st.expander("📊 AI Financial Insights", expanded=True):
44
- st.markdown("<span class='ai-badge'>AI-Generated Insights</span>", unsafe_allow_html=True)
45
- st.markdown(st.session_state.insights_cache[insights_key])
46
-
47
- # Key metrics
48
- col1, col2, col3, col4 = st.columns(4)
49
-
50
- # Calculate runway
51
- runway_months, runway_df = calculate_runway(
52
- startup_data['cash'],
53
- startup_data['burn_rate'],
54
- startup_data['revenue'],
55
- startup_data['growth_rate']
56
- )
57
-
58
- # Determine status colors based on financial health indicators
59
- runway_status = "danger-metric" if runway_months < 6 else ("warning-metric" if runway_months < 9 else "good-metric")
60
- burn_status = "danger-metric" if startup_data['burn_rate'] > 100000 else ("warning-metric" if startup_data['burn_rate'] > 80000 else "good-metric")
61
- revenue_status = "good-metric" if startup_data['revenue'] > 20000 else ("warning-metric" if startup_data['revenue'] > 10000 else "danger-metric")
62
-
63
- with col1:
64
- st.markdown(f"""
65
- <div class='metric-card'>
66
- <p class='metric-label'>Current Cash</p>
67
- <p class='metric-value'>${startup_data['cash']:,}</p>
68
- </div>
69
- """, unsafe_allow_html=True)
70
-
71
- with col2:
72
- st.markdown(f"""
73
- <div class='metric-card'>
74
- <p class='metric-label'>Monthly Burn</p>
75
- <p class='metric-value {burn_status}'>${startup_data['burn_rate']:,}</p>
76
- </div>
77
- """, unsafe_allow_html=True)
78
-
79
- with col3:
80
- st.markdown(f"""
81
- <div class='metric-card'>
82
- <p class='metric-label'>Monthly Revenue</p>
83
- <p class='metric-value {revenue_status}'>${startup_data['revenue']:,}</p>
84
- </div>
85
- """, unsafe_allow_html=True)
86
-
87
- with col4:
88
- st.markdown(f"""
89
- <div class='metric-card'>
90
- <p class='metric-label'>Runway</p>
91
- <p class='metric-value {runway_status}'>{runway_months} months</p>
92
- </div>
93
- """, unsafe_allow_html=True)
94
-
95
- # Financial charts
96
- st.subheader("Financial Overview")
97
-
98
- tab1, tab2, tab3 = st.tabs(["Runway Projection", "Revenue vs. Expenses", "Burn Rate Trend"])
99
-
100
- with tab1:
101
- # Runway projection chart
102
- fig = px.line(runway_df.reset_index(), x='index', y='Cumulative_Cash',
103
- title="Cash Runway Projection",
104
- labels={'index': 'Date', 'Cumulative_Cash': 'Remaining Cash ($)'},
105
- color_discrete_sequence=['#0066cc'])
106
- fig.add_hline(y=0, line_dash="dash", line_color="red", annotation_text="Out of Cash")
107
- fig.update_layout(
108
- height=400,
109
- plot_bgcolor='rgba(240,247,255,0.8)',
110
- xaxis_title="Date",
111
- yaxis_title="Cash Balance ($)",
112
- font=dict(family="Arial, sans-serif", size=12),
113
- margin=dict(l=20, r=20, t=40, b=20),
114
- )
115
- st.plotly_chart(fig, use_container_width=True)
116
-
117
- # Get analysis from Gemini
118
- with st.expander("🔍 AI Financial Analysis", expanded=True):
119
- # Use cache to avoid repeated API calls
120
- analysis_key = f"runway_{date.today().isoformat()}"
121
- if analysis_key not in st.session_state.insights_cache:
122
- analysis = get_runway_analysis(startup_data)
123
- st.session_state.insights_cache[analysis_key] = analysis
124
-
125
- st.markdown("<span class='ai-badge'>AI Financial Analysis</span>", unsafe_allow_html=True)
126
- st.markdown(st.session_state.insights_cache[analysis_key])
127
-
128
- with tab2:
129
- # Revenue vs Expenses chart
130
- rev_exp_df = cash_flow_df.copy()
131
- fig = px.bar(rev_exp_df, x='Month', y=['Revenue', 'Total_Expenses'],
132
- title="Revenue vs. Expenses",
133
- barmode='group',
134
- labels={'value': 'Amount ($)', 'variable': 'Category'},
135
- color_discrete_sequence=['#28a745', '#dc3545'])
136
- fig.update_layout(
137
- height=400,
138
- plot_bgcolor='rgba(240,247,255,0.8)',
139
- xaxis_title="Month",
140
- yaxis_title="Amount ($)",
141
- font=dict(family="Arial, sans-serif", size=12),
142
- legend_title="",
143
- margin=dict(l=20, r=20, t=40, b=20),
144
- )
145
- st.plotly_chart(fig, use_container_width=True)
146
-
147
- # Calculate revenue growth
148
- revenue_growth = [(cash_flow_df['Revenue'].iloc[i] / cash_flow_df['Revenue'].iloc[i-1] - 1) * 100 if i > 0 else 0
149
- for i in range(len(cash_flow_df))]
150
- avg_growth = sum(revenue_growth[1:]) / len(revenue_growth[1:])
151
-
152
- col1, col2 = st.columns(2)
153
- with col1:
154
- st.metric("Average Monthly Revenue Growth", f"{avg_growth:.1f}%")
155
- with col2:
156
- expense_growth = (cash_flow_df['Total_Expenses'].iloc[-1] / cash_flow_df['Total_Expenses'].iloc[0] - 1) * 100
157
- st.metric("Total Expense Growth", f"{expense_growth:.1f}%", delta=f"{expense_growth - avg_growth:.1f}%", delta_color="inverse")
158
-
159
- with tab3:
160
- # Burn rate trend
161
- fig = px.line(cash_flow_df, x='Month', y='Net_Burn',
162
- title="Monthly Net Burn Trend",
163
- labels={'Net_Burn': 'Net Burn ($)'},
164
- color_discrete_sequence=['#dc3545'])
165
- fig.update_layout(
166
- height=400,
167
- plot_bgcolor='rgba(240,247,255,0.8)',
168
- xaxis_title="Month",
169
- yaxis_title="Net Burn ($)",
170
- font=dict(family="Arial, sans-serif", size=12),
171
- margin=dict(l=20, r=20, t=40, b=20),
172
- )
173
-
174
- # Add efficiency ratio as a second y-axis
175
- efficiency_ratio = [cash_flow_df['Revenue'].iloc[i] / cash_flow_df['Total_Expenses'].iloc[i] * 100
176
- for i in range(len(cash_flow_df))]
177
-
178
- fig.add_trace(go.Scatter(
179
- x=cash_flow_df['Month'],
180
- y=efficiency_ratio,
181
- name='Efficiency Ratio (%)',
182
- yaxis='y2',
183
- line=dict(color='#0066cc', width=2, dash='dot')
184
- ))
185
-
186
- fig.update_layout(
187
- yaxis2=dict(
188
- title='Efficiency Ratio (%)',
189
- overlaying='y',
190
- side='right',
191
- range=[0, max(efficiency_ratio) * 1.2]
192
- )
193
- )
194
-
195
- st.plotly_chart(fig, use_container_width=True)
196
-
197
- with st.expander("🔎 Understanding Efficiency Ratio"):
198
- 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.")
199
-
200
- # Expense breakdown
201
- st.subheader("Expense Breakdown")
202
-
203
- # Last month expenses
204
- last_month = cash_flow_df.iloc[-1]
205
- expense_categories = ['Payroll', 'Marketing', 'Office', 'Software', 'Travel', 'Legal', 'Misc']
206
- expense_values = [last_month[cat] for cat in expense_categories]
207
-
208
- col1, col2 = st.columns([2, 1])
209
-
210
- with col1:
211
- fig = px.pie(values=expense_values, names=expense_categories,
212
- title="Current Month Expense Breakdown",
213
- color_discrete_sequence=px.colors.sequential.Blues_r)
214
- fig.update_layout(
215
- height=400,
216
- font=dict(family="Arial, sans-serif", size=12),
217
- margin=dict(l=20, r=20, t=40, b=20),
218
- )
219
- fig.update_traces(textposition='inside', textinfo='percent+label')
220
- st.plotly_chart(fig, use_container_width=True)
221
-
222
- with col2:
223
- # Expense analysis
224
- st.markdown("<h4>Expense Analysis</h4>", unsafe_allow_html=True)
225
-
226
- # Calculate industry benchmarks (simulated)
227
- benchmarks = {
228
- "Payroll": "70-80%",
229
- "Marketing": "10-15%",
230
- "Office": "5-8%",
231
- "Software": "3-5%"
232
- }
233
-
234
- # Create a table with expense categories, amounts, and % of total
235
- expense_df = pd.DataFrame({
236
- "Category": expense_categories,
237
- "Amount": expense_values,
238
- "% of Total": [v / sum(expense_values) * 100 for v in expense_values]
239
- })
240
-
241
- # Add benchmark column
242
- expense_df["Industry Benchmark"] = expense_df["Category"].map(
243
- lambda x: benchmarks.get(x, "N/A")
244
- )
245
-
246
- # Format the dataframe for display
247
- formatted_df = expense_df.copy()
248
- formatted_df["Amount"] = formatted_df["Amount"].apply(lambda x: f"${x:,.0f}")
249
- formatted_df["% of Total"] = formatted_df["% of Total"].apply(lambda x: f"{x:.1f}%")
250
-
251
- st.table(formatted_df)
252
-
253
- # AI-powered spending optimization
254
- with st.expander("💡 AI Spending Optimization"):
255
- st.markdown("<span class='ai-badge'>AI Recommendation</span>", unsafe_allow_html=True)
256
-
257
- # Use cache to avoid repeated API calls
258
- spending_key = f"spending_{date.today().isoformat()}"
259
- if spending_key not in st.session_state.insights_cache:
260
- spending_recommendation = generate_ai_response("""
261
- Based on your expense breakdown, recommend 2-3 specific ways to optimize spending to extend runway.
262
- Focus on industry best practices for seed-stage startups.
263
- """, simulate=True)
264
- st.session_state.insights_cache[spending_key] = spending_recommendation
265
-
266
- st.markdown(st.session_state.insights_cache[spending_key])
267
-
268
- # Fundraising Readiness Assessment
269
- st.subheader("Fundraising Readiness")
270
-
271
- # Get AI analysis of fundraising readiness
272
- fundraising_key = f"fundraising_{date.today().isoformat()}"
273
- if fundraising_key not in st.session_state.insights_cache:
274
- fundraising_analysis = get_fundraising_readiness_analysis(startup_data, cash_flow_df)
275
- st.session_state.insights_cache[fundraising_key] = fundraising_analysis
276
-
277
- st.markdown("<div class='advisor-card'>", unsafe_allow_html=True)
278
- st.markdown("<span class='ai-badge'>AI Fundraising Assessment</span>", unsafe_allow_html=True)
279
- st.markdown(f"<p class='advice-text'>{st.session_state.insights_cache[fundraising_key]}</p>", unsafe_allow_html=True)
280
- st.markdown("</div>", unsafe_allow_html=True)
281
-
282
- # Call-to-action for advisor
283
- st.info("📅 Need personalized guidance on fundraising? [Book a session](#book-a-session) with our AI financial advisor.")
284
-
285
- def get_runway_analysis(financial_data):
286
- """Get runway analysis using Gemini."""
287
- prompt = f"""
288
- You are a financial advisor for startups. Analyze this startup's financial data:
289
- - Current cash: ${financial_data['cash']}
290
- - Monthly burn rate: ${financial_data['burn_rate']}
291
- - Monthly revenue: ${financial_data['revenue']}
292
- - Monthly growth rate: {financial_data['growth_rate'] * 100}%
293
-
294
- Provide a detailed analysis of their runway and financial health. Include:
295
- 1. Exact runway calculation in months
296
- 2. Assessment of financial health (critical, concerning, stable, or healthy)
297
- 3. Benchmarks compared to similar seed-stage startups
298
- 4. Three specific, actionable recommendations to improve runway
299
- 5. Key metrics they should focus on
300
-
301
- Format your response in a structured, easy-to-read format with clear sections and bullet points.
302
- """
303
-
304
- return generate_ai_response(prompt)
305
-
306
- def get_fundraising_readiness_analysis(startup_data, cash_flow_df):
307
- """Get AI analysis of fundraising readiness."""
308
- metrics = {
309
- "MRR Growth": f"{(cash_flow_df['Revenue'].iloc[-1] / cash_flow_df['Revenue'].iloc[-2] - 1) * 100:.1f}%",
310
- "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}%",
311
- "CAC": "$950", # Example value
312
- "LTV": "$4,500", # Example value
313
- "Churn": "3.2%", # Example value
314
- }
315
-
316
- metrics_text = "\n".join([f"- {k}: {v}" for k, v in metrics.items()])
317
-
318
- prompt = f"""
319
- You are a startup fundraising advisor. Analyze this startup's readiness for their next funding round:
320
-
321
- Company Profile:
322
- - Stage: {startup_data['stage']}
323
- - Last Funding: {startup_data['last_funding']}
324
- - Current Cash: ${startup_data['cash']}
325
- - Monthly Burn: ${startup_data['burn_rate']}
326
- - Runway: {startup_data['cash'] / (startup_data['burn_rate'] - startup_data['revenue']):.1f} months
327
-
328
- Key Metrics:
329
- {metrics_text}
330
-
331
- Provide a comprehensive fundraising readiness assessment:
332
- 1. Overall fundraising readiness score (0-10)
333
- 2. Assessment of current metrics compared to investor expectations for next round
334
- 3. Identify the 3 most critical metrics to improve before fundraising
335
- 4. Recommend specific targets for each key metric
336
- 5. Suggest timeline and specific milestones for fundraising preparation
337
- 6. Estimate reasonable valuation range based on metrics and market conditions
338
-
339
- Be specific with numbers, timelines, and actionable targets.
340
- """
341
-
342
- return generate_ai_response(prompt)