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("

Financial Dashboard

", unsafe_allow_html=True) st.markdown("

AI-powered financial insights at a glance

", 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("AI-Generated Insights", 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"""

Current Cash

${startup_data['cash']:,}

""", unsafe_allow_html=True) with col2: st.markdown(f"""

Monthly Burn

${startup_data['burn_rate']:,}

""", unsafe_allow_html=True) with col3: st.markdown(f"""

Monthly Revenue

${startup_data['revenue']:,}

""", unsafe_allow_html=True) with col4: st.markdown(f"""

Runway

{runway_months} months

""", 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("AI Financial Analysis", 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("

Expense Analysis

", 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("AI Recommendation", 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("
", unsafe_allow_html=True) st.markdown("AI Fundraising Assessment", unsafe_allow_html=True) st.markdown(f"

{st.session_state.insights_cache[fundraising_key]}

", unsafe_allow_html=True) st.markdown("
", 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)