Delete fund-monitoring.py
Browse files- fund-monitoring.py +0 -334
fund-monitoring.py
DELETED
@@ -1,334 +0,0 @@
|
|
1 |
-
def render_fund_monitoring(transactions_df):
|
2 |
-
"""
|
3 |
-
Render the AI-powered fund monitoring page.
|
4 |
-
|
5 |
-
This feature helps startups monitor spending, detect fraudulent transactions,
|
6 |
-
and maintain investor trust through AI-powered analysis.
|
7 |
-
"""
|
8 |
-
st.markdown("<h1 class='main-header'>Investor Fund Monitoring</h1>", unsafe_allow_html=True)
|
9 |
-
st.markdown("<p class='sub-header'>AI-powered fraud detection and spending analysis</p>", unsafe_allow_html=True)
|
10 |
-
|
11 |
-
# How AI helps with fund monitoring
|
12 |
-
with st.expander("ℹ️ How AI enhances fund monitoring"):
|
13 |
-
st.markdown("""
|
14 |
-
### How AI Powers Your Fund Monitoring
|
15 |
-
|
16 |
-
The fund monitoring system uses AI to help maintain investor trust and optimize spending:
|
17 |
-
|
18 |
-
- **Anomaly Detection**: Our AI models identify unusual transactions that don't match typical startup spending patterns
|
19 |
-
- **Risk Scoring**: Each transaction is assigned a risk score based on multiple factors like amount, category, vendor, and description
|
20 |
-
- **Pattern Recognition**: The system identifies potentially concerning spending trends across categories over time
|
21 |
-
- **Fraud Prevention**: AI algorithms flag transactions that match known patterns of misuse before they become issues
|
22 |
-
- **Investor-Ready Reporting**: Generate reports that demonstrate responsible financial stewardship to investors
|
23 |
-
|
24 |
-
This helps founders maintain investor trust, prevent misuse of funds, and create transparency in financial operations.
|
25 |
-
""")
|
26 |
-
|
27 |
-
st.write("Monitor your startup's spending to maintain investor trust and ensure proper fund usage. Our AI algorithms automatically flag suspicious transactions and identify spending patterns.")
|
28 |
-
|
29 |
-
# AI insights for fund monitoring
|
30 |
-
insights_key = f"fund_monitoring_{date.today().isoformat()}"
|
31 |
-
if insights_key not in st.session_state.insights_cache:
|
32 |
-
insights = generate_ai_response("""
|
33 |
-
You are a financial fraud detection expert. Provide 2-3 critical spending patterns that investors typically look for when monitoring startup fund usage.
|
34 |
-
Format as brief bullet points focused on maintaining investor trust.
|
35 |
-
""", simulate=True)
|
36 |
-
st.session_state.insights_cache[insights_key] = insights
|
37 |
-
|
38 |
-
with st.expander("🔍 AI Monitoring Insights", expanded=True):
|
39 |
-
st.markdown("<span class='ai-badge'>AI-Generated Insights</span>", unsafe_allow_html=True)
|
40 |
-
st.markdown(st.session_state.insights_cache[insights_key])
|
41 |
-
|
42 |
-
# Process transactions to detect suspicious ones with AI enhancement
|
43 |
-
processed_df = detect_suspicious_transactions(transactions_df)
|
44 |
-
|
45 |
-
# Summary metrics
|
46 |
-
total_transactions = len(processed_df)
|
47 |
-
suspicious_transactions = processed_df[processed_df['Suspicious']].copy()
|
48 |
-
suspicious_count = len(suspicious_transactions)
|
49 |
-
suspicious_amount = suspicious_transactions['Amount'].sum()
|
50 |
-
total_amount = processed_df['Amount'].sum()
|
51 |
-
|
52 |
-
col1, col2, col3, col4 = st.columns(4)
|
53 |
-
|
54 |
-
with col1:
|
55 |
-
st.markdown(f"""
|
56 |
-
<div class='metric-card'>
|
57 |
-
<p class='metric-label'>Total Transactions</p>
|
58 |
-
<p class='metric-value'>{total_transactions}</p>
|
59 |
-
</div>
|
60 |
-
""", unsafe_allow_html=True)
|
61 |
-
|
62 |
-
with col2:
|
63 |
-
flagged_percent = suspicious_count/total_transactions*100 if total_transactions > 0 else 0
|
64 |
-
status = "danger-metric" if flagged_percent > 10 else ("warning-metric" if flagged_percent > 5 else "good-metric")
|
65 |
-
st.markdown(f"""
|
66 |
-
<div class='metric-card'>
|
67 |
-
<p class='metric-label'>Flagged Transactions</p>
|
68 |
-
<p class='metric-value {status}'>{suspicious_count} ({flagged_percent:.1f}%)</p>
|
69 |
-
</div>
|
70 |
-
""", unsafe_allow_html=True)
|
71 |
-
|
72 |
-
with col3:
|
73 |
-
amount_percent = suspicious_amount/total_amount*100 if total_amount > 0 else 0
|
74 |
-
status = "danger-metric" if amount_percent > 15 else ("warning-metric" if amount_percent > 7 else "good-metric")
|
75 |
-
st.markdown(f"""
|
76 |
-
<div class='metric-card'>
|
77 |
-
<p class='metric-label'>Flagged Amount</p>
|
78 |
-
<p class='metric-value {status}'>${suspicious_amount:,.0f} ({amount_percent:.1f}%)</p>
|
79 |
-
</div>
|
80 |
-
""", unsafe_allow_html=True)
|
81 |
-
|
82 |
-
with col4:
|
83 |
-
avg_risk = suspicious_transactions['Risk_Score'].mean() if not suspicious_transactions.empty else 0
|
84 |
-
status = "danger-metric" if avg_risk > 50 else ("warning-metric" if avg_risk > 30 else "good-metric")
|
85 |
-
st.markdown(f"""
|
86 |
-
<div class='metric-card'>
|
87 |
-
<p class='metric-label'>Average Risk Score</p>
|
88 |
-
<p class='metric-value {status}'>{avg_risk:.1f}/100</p>
|
89 |
-
</div>
|
90 |
-
""", unsafe_allow_html=True)
|
91 |
-
|
92 |
-
# Tabs for different views
|
93 |
-
tab1, tab2 = st.tabs(["Flagged Transactions", "All Transactions"])
|
94 |
-
|
95 |
-
with tab1:
|
96 |
-
if suspicious_count > 0:
|
97 |
-
# Add risk score visualization (color coded)
|
98 |
-
suspicious_view = suspicious_transactions.copy()
|
99 |
-
|
100 |
-
# Format for display
|
101 |
-
def colorize_risk(val):
|
102 |
-
color = "red" if val > 50 else ("orange" if val > 30 else "blue")
|
103 |
-
return f'background-color: {color}; color: white; font-weight: bold'
|
104 |
-
|
105 |
-
# Apply styling
|
106 |
-
styled_suspicious = suspicious_view.style.applymap(
|
107 |
-
lambda x: colorize_risk(x) if x > 0 else '',
|
108 |
-
subset=['Risk_Score']
|
109 |
-
)
|
110 |
-
|
111 |
-
st.dataframe(
|
112 |
-
suspicious_view[['Date', 'Category', 'Vendor', 'Amount', 'Description', 'Risk_Score', 'Reason']],
|
113 |
-
use_container_width=True
|
114 |
-
)
|
115 |
-
|
116 |
-
# Get AI analysis of suspicious transactions
|
117 |
-
fraud_key = f"fraud_{date.today().isoformat()}"
|
118 |
-
if fraud_key not in st.session_state.insights_cache:
|
119 |
-
fraud_analysis = get_fraud_analysis(suspicious_transactions)
|
120 |
-
st.session_state.insights_cache[fraud_key] = fraud_analysis
|
121 |
-
|
122 |
-
st.markdown("<div class='advisor-card'>", unsafe_allow_html=True)
|
123 |
-
st.markdown("<span class='ai-badge'>AI Fraud Analysis</span>", unsafe_allow_html=True)
|
124 |
-
st.markdown(f"<p class='advice-text'>{st.session_state.insights_cache[fraud_key]}</p>", unsafe_allow_html=True)
|
125 |
-
st.markdown("</div>", unsafe_allow_html=True)
|
126 |
-
|
127 |
-
# Action buttons
|
128 |
-
st.subheader("Recommended Actions")
|
129 |
-
|
130 |
-
col1, col2, col3 = st.columns(3)
|
131 |
-
with col1:
|
132 |
-
if st.button("🔍 Investigate All Flagged"):
|
133 |
-
st.session_state.investigation_started = True
|
134 |
-
with col2:
|
135 |
-
if st.button("📝 Generate Investor Report"):
|
136 |
-
st.session_state.report_generated = True
|
137 |
-
with col3:
|
138 |
-
if st.button("✅ Mark Reviewed"):
|
139 |
-
st.session_state.marked_reviewed = True
|
140 |
-
|
141 |
-
# Simulate action responses
|
142 |
-
if 'investigation_started' in st.session_state and st.session_state.investigation_started:
|
143 |
-
st.success("Investigation initiated for all flagged transactions. Your financial team will be notified.")
|
144 |
-
|
145 |
-
if 'report_generated' in st.session_state and st.session_state.report_generated:
|
146 |
-
st.success("Investor report generated and ready for review before sending.")
|
147 |
-
|
148 |
-
if 'marked_reviewed' in st.session_state and st.session_state.marked_reviewed:
|
149 |
-
st.success("All transactions marked as reviewed. Status will be updated in the system.")
|
150 |
-
else:
|
151 |
-
st.success("No suspicious transactions detected by our AI system. Your spending appears to be normal for a startup at your stage.")
|
152 |
-
|
153 |
-
with tab2:
|
154 |
-
st.dataframe(processed_df[['Date', 'Category', 'Vendor', 'Amount', 'Description', 'Suspicious', 'Risk_Score']],
|
155 |
-
use_container_width=True)
|
156 |
-
|
157 |
-
# Spending patterns
|
158 |
-
st.subheader("Spending Pattern Analysis")
|
159 |
-
|
160 |
-
# Category breakdown
|
161 |
-
category_spending = processed_df.groupby('Category')['Amount'].sum().reset_index()
|
162 |
-
|
163 |
-
col1, col2 = st.columns(2)
|
164 |
-
|
165 |
-
with col1:
|
166 |
-
fig = px.bar(category_spending, x='Category', y='Amount',
|
167 |
-
title="Spending by Category",
|
168 |
-
labels={'Amount': 'Total Spent ($)'},
|
169 |
-
color='Amount',
|
170 |
-
color_continuous_scale='Blues')
|
171 |
-
fig.update_layout(
|
172 |
-
height=400,
|
173 |
-
plot_bgcolor='rgba(240,247,255,0.8)',
|
174 |
-
xaxis_title="Category",
|
175 |
-
yaxis_title="Amount Spent ($)",
|
176 |
-
font=dict(family="Arial, sans-serif", size=12),
|
177 |
-
margin=dict(l=20, r=20, t=40, b=20),
|
178 |
-
)
|
179 |
-
st.plotly_chart(fig, use_container_width=True)
|
180 |
-
|
181 |
-
with col2:
|
182 |
-
# AI spending pattern analysis
|
183 |
-
spending_key = f"spending_pattern_{date.today().isoformat()}"
|
184 |
-
if spending_key not in st.session_state.insights_cache:
|
185 |
-
spending_pattern_analysis = generate_ai_response("""
|
186 |
-
You are a startup spending analyst. Review the spending patterns and provide 3 key insights about:
|
187 |
-
1. Categories that appear to have unusually high spending
|
188 |
-
2. Potential areas where spending could be optimized
|
189 |
-
3. Changes in spending patterns that investors might find concerning
|
190 |
-
|
191 |
-
Format as concise, actionable bullet points.
|
192 |
-
""", simulate=True)
|
193 |
-
st.session_state.insights_cache[spending_key] = spending_pattern_analysis
|
194 |
-
|
195 |
-
st.markdown("<div class='insight-card'>", unsafe_allow_html=True)
|
196 |
-
st.markdown("<span class='ai-badge'>AI Spending Analysis</span>", unsafe_allow_html=True)
|
197 |
-
st.markdown(st.session_state.insights_cache[spending_key])
|
198 |
-
st.markdown("</div>", unsafe_allow_html=True)
|
199 |
-
|
200 |
-
# Time series of spending
|
201 |
-
processed_df['Date'] = pd.to_datetime(processed_df['Date'])
|
202 |
-
processed_df['Week'] = processed_df['Date'].dt.isocalendar().week
|
203 |
-
weekly_spending = processed_df.groupby(['Week', 'Category'])['Amount'].sum().reset_index()
|
204 |
-
|
205 |
-
fig = px.line(weekly_spending, x='Week', y='Amount', color='Category',
|
206 |
-
title="Weekly Spending Trends",
|
207 |
-
labels={'Amount': 'Amount Spent ($)'},
|
208 |
-
color_discrete_sequence=px.colors.qualitative.Bold)
|
209 |
-
fig.update_layout(
|
210 |
-
height=400,
|
211 |
-
plot_bgcolor='rgba(240,247,255,0.8)',
|
212 |
-
xaxis_title="Week",
|
213 |
-
yaxis_title="Amount Spent ($)",
|
214 |
-
font=dict(family="Arial, sans-serif", size=12),
|
215 |
-
margin=dict(l=20, r=20, t=40, b=20),
|
216 |
-
)
|
217 |
-
st.plotly_chart(fig, use_container_width=True)
|
218 |
-
|
219 |
-
# AI-powered spending controls recommendation
|
220 |
-
st.subheader("AI-Recommended Spending Controls")
|
221 |
-
|
222 |
-
# Get AI recommendations for spending controls
|
223 |
-
controls_key = f"spending_controls_{date.today().isoformat()}"
|
224 |
-
if controls_key not in st.session_state.insights_cache:
|
225 |
-
controls_recommendations = generate_ai_response("""
|
226 |
-
You are a financial controls expert for startups. Based on the spending patterns and suspicious transactions,
|
227 |
-
recommend 3-4 specific spending controls that the startup should implement to prevent misuse of funds.
|
228 |
-
|
229 |
-
For each control, provide:
|
230 |
-
1. A clear policy statement
|
231 |
-
2. Implementation steps
|
232 |
-
3. Expected impact
|
233 |
-
|
234 |
-
Format as concise, actionable recommendations.
|
235 |
-
""", simulate=True)
|
236 |
-
st.session_state.insights_cache[controls_key] = controls_recommendations
|
237 |
-
|
238 |
-
st.markdown("<div class='advisor-card'>", unsafe_allow_html=True)
|
239 |
-
st.markdown("<span class='ai-badge'>AI Control Recommendations</span>", unsafe_allow_html=True)
|
240 |
-
st.markdown(f"<p class='advice-text'>{st.session_state.insights_cache[controls_key]}</p>", unsafe_allow_html=True)
|
241 |
-
st.markdown("</div>", unsafe_allow_html=True)
|
242 |
-
|
243 |
-
# Call-to-action
|
244 |
-
st.info("📅 Need help implementing financial controls? [Book a session](#book-a-session) with our AI financial advisor.")
|
245 |
-
|
246 |
-
def detect_suspicious_transactions(transactions_df):
|
247 |
-
"""AI-enhanced suspicious transaction detection."""
|
248 |
-
df = transactions_df.copy()
|
249 |
-
|
250 |
-
# Define thresholds for each category
|
251 |
-
category_thresholds = {
|
252 |
-
"Travel": 3000,
|
253 |
-
"Marketing": 10000,
|
254 |
-
"Office": 7000,
|
255 |
-
"Software": 6000,
|
256 |
-
"Consulting": 5000,
|
257 |
-
"Legal": 6000
|
258 |
-
}
|
259 |
-
|
260 |
-
# Define suspicious terms
|
261 |
-
suspicious_terms = ['luxury', 'cruise', 'premium', 'personal', 'gift']
|
262 |
-
|
263 |
-
# Add suspicious column
|
264 |
-
df['Suspicious'] = False
|
265 |
-
df['Reason'] = ""
|
266 |
-
df['Risk_Score'] = 0
|
267 |
-
|
268 |
-
# Check for suspicious patterns
|
269 |
-
for idx, row in df.iterrows():
|
270 |
-
reasons = []
|
271 |
-
risk_score = 0
|
272 |
-
|
273 |
-
# Check if amount exceeds category threshold
|
274 |
-
if row['Category'] in category_thresholds:
|
275 |
-
if row['Amount'] > category_thresholds[row['Category']]:
|
276 |
-
reasons.append(f"Amount exceeds typical spending for {row['Category']}")
|
277 |
-
risk_score += 30
|
278 |
-
|
279 |
-
# Higher risk for significantly exceeding threshold
|
280 |
-
excess_percentage = (row['Amount'] - category_thresholds[row['Category']]) / category_thresholds[row['Category']] * 100
|
281 |
-
if excess_percentage > 100: # More than double the threshold
|
282 |
-
risk_score += 20
|
283 |
-
|
284 |
-
# Check for suspicious vendors or descriptions
|
285 |
-
if any(term in str(row['Vendor']).lower() for term in suspicious_terms):
|
286 |
-
reasons.append(f"Vendor name contains suspicious term")
|
287 |
-
risk_score += 25
|
288 |
-
|
289 |
-
if any(term in str(row['Description']).lower() for term in suspicious_terms):
|
290 |
-
reasons.append(f"Description contains suspicious term")
|
291 |
-
risk_score += 20
|
292 |
-
|
293 |
-
# Check for rounded amounts (potential indicator of estimation/fabrication)
|
294 |
-
if row['Amount'] % 1000 == 0 and row['Amount'] > 3000:
|
295 |
-
reasons.append(f"Suspiciously round amount")
|
296 |
-
risk_score += 15
|
297 |
-
|
298 |
-
# Mark as suspicious if risk score is high enough
|
299 |
-
if risk_score >= 30:
|
300 |
-
df.at[idx, 'Suspicious'] = True
|
301 |
-
df.at[idx, 'Reason'] = "; ".join(reasons)
|
302 |
-
df.at[idx, 'Risk_Score'] = risk_score
|
303 |
-
|
304 |
-
# Sort by risk score
|
305 |
-
df = df.sort_values(by='Risk_Score', ascending=False)
|
306 |
-
|
307 |
-
return df
|
308 |
-
|
309 |
-
def get_fraud_analysis(transactions_df):
|
310 |
-
"""Get AI analysis of potentially fraudulent transactions."""
|
311 |
-
suspicious_df = transactions_df[transactions_df['Suspicious']].copy()
|
312 |
-
|
313 |
-
if len(suspicious_df) == 0:
|
314 |
-
return "No suspicious transactions detected."
|
315 |
-
|
316 |
-
transactions_text = suspicious_df[['Date', 'Category', 'Vendor', 'Amount', 'Description', 'Risk_Score']].to_string(index=False)
|
317 |
-
|
318 |
-
prompt = f"""
|
319 |
-
You are a financial forensics expert specializing in startup spending oversight.
|
320 |
-
Review these flagged transactions:
|
321 |
-
|
322 |
-
{transactions_text}
|
323 |
-
|
324 |
-
Provide a detailed analysis:
|
325 |
-
1. Identify the most concerning transactions and explain why
|
326 |
-
2. Calculate the total financial impact of these suspicious transactions
|
327 |
-
3. Identify spending patterns or potential policy violations
|
328 |
-
4. Recommend specific actions the startup should take immediately
|
329 |
-
5. Suggest controls to prevent similar issues in the future
|
330 |
-
|
331 |
-
Be specific about which transactions are most concerning and why investors would have questions.
|
332 |
-
"""
|
333 |
-
|
334 |
-
return generate_ai_response(prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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