File size: 7,234 Bytes
36f6a1d
 
 
 
 
623e602
36f6a1d
 
623e602
 
 
 
 
 
 
 
 
 
 
 
 
36f6a1d
623e602
36f6a1d
623e602
36f6a1d
623e602
36f6a1d
623e602
 
 
 
 
 
 
 
 
 
36f6a1d
 
 
623e602
 
 
36f6a1d
 
 
 
 
 
 
623e602
 
 
 
 
 
 
36f6a1d
 
623e602
 
 
 
 
 
36f6a1d
 
623e602
 
 
 
 
 
 
 
 
 
36f6a1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623e602
 
 
36f6a1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623e602
36f6a1d
 
 
 
 
 
 
 
 
 
 
623e602
36f6a1d
 
 
 
 
623e602
36f6a1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import plotly.express as px
import pandas as pd
import google.generativeai as genai

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
        try:
            if setup_genai():
                with st.expander("AI Financial Analysis"):
                    analysis = get_runway_analysis(startup_data)
                    st.write(analysis)
        except Exception as e:
            st.error(f"Error generating AI analysis: {e}")
    
    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 calculate_runway(initial_cash, monthly_burn, monthly_revenue, growth_rate, months=24):
    """Calculate runway based on current burn rate and revenue growth."""
    from datetime import datetime, timedelta
    import pandas as pd
    
    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 get_runway_analysis(financial_data):
    """Get runway analysis using Gemini."""
    try:
        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
    except Exception as e:
        return f"Error generating runway analysis: {e}"

def get_fundraising_readiness_analysis(financial_data):
    """Analyze startup's readiness for fundraising."""
    try:
        prompt = f"""
        You are a fundraising advisor for startups. Evaluate this startup's fundraising readiness:
        - 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.get('last_funding', 'Not specified')}
        - Company stage: {financial_data.get('stage', 'Not specified')}

        Provide insights on:
        1. Current runway and funding needs
        2. Attractiveness to potential investors
        3. Recommended fundraising strategy
        4. Key metrics to improve before fundraising

        Respond in a concise, actionable paragraph.
        """
        
        model = genai.GenerativeModel('gemini-pro')
        response = model.generate_content(prompt)
        
        return response.text
    except Exception as e:
        return f"Error generating fundraising readiness analysis: {e}"

def setup_genai():
    """Setup Google Generative AI"""
    try:
        import os
        import streamlit as st
        
        # Try getting API key from Streamlit secrets first
        if 'GOOGLE_API_KEY' in st.secrets:
            api_key = st.secrets['GOOGLE_API_KEY']
        # Fall back to environment variable
        elif 'GOOGLE_API_KEY' in os.environ:
            api_key = os.environ['GOOGLE_API_KEY']
        else:
            st.warning("Google API key not found. Using simulated AI responses.")
            return False
            
        genai.configure(api_key=api_key)
        return True
    except Exception as e:
        st.error(f"Error setting up Generative AI: {e}")
        return False