fin-ai / huggingface-setup.py
walaa2022's picture
Upload 6 files
a3e7179 verified
raw
history blame
24.8 kB
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()