nniehaus's picture
Update app.py
e5ce29f verified
import streamlit as st
from openai import OpenAI
import os
import re
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def search_market_data(location, property_type):
"""
Uses AI to search for current market data and trends for the specified location and property type.
"""
try:
messages = [{
"role": "system",
"content": """You are a real estate market analyst with access to current market data.
When asked about market conditions, search for and provide current information about:
- Average home prices and recent trends
- Market inventory levels
- Days on market
- Interest rate impacts
- Local economic factors
- Seasonal trends
Always search for the most recent data available."""
}]
query = f"""Search for current real estate market data for {location} focusing on {property_type} properties.
Include recent price trends, inventory levels, average days on market, and local market conditions as of 2025."""
messages.append({"role": "user", "content": query})
response = client.chat.completions.create(
model="gpt-5",
messages=messages
)
return response.choices[0].message.content
except Exception as e:
return f"Unable to fetch current market data. Error: {str(e)}"
def calculate_financial_analysis(current_rent, target_purchase_price, down_payment_percent,
interest_rate, max_monthly_budget, annual_income):
"""
Performs detailed financial calculations for renting vs buying scenarios.
"""
# Estimate utilities based on rent (typically 10-15% of rent)
utilities = current_rent * 0.12
# Current rental costs
total_current_monthly = current_rent + utilities
# Buying scenario calculations
down_payment = target_purchase_price * (down_payment_percent / 100)
loan_amount = target_purchase_price - down_payment
# Calculate mortgage payment
monthly_rate = interest_rate / 100 / 12
num_payments = 30 * 12 # 30-year mortgage
if monthly_rate > 0:
mortgage_payment = loan_amount * (monthly_rate * (1 + monthly_rate)**num_payments) / ((1 + monthly_rate)**num_payments - 1)
else:
mortgage_payment = loan_amount / num_payments
# Additional homeownership costs
property_taxes = target_purchase_price * 0.015 / 12 # Estimated 1.5% annually
homeowners_insurance = target_purchase_price * 0.004 / 12 # Estimated 0.4% annually
maintenance = target_purchase_price * 0.02 / 12 # Estimated 2% annually
utilities_owned = utilities * 1.2 # Typically 20% higher for owned vs rented
# PMI if down payment < 20%
pmi = 0
if down_payment_percent < 20:
pmi = loan_amount * 0.005 / 12 # Estimated 0.5% annually
total_monthly_ownership = mortgage_payment + property_taxes + homeowners_insurance + maintenance + utilities_owned + pmi
monthly_difference = total_monthly_ownership - total_current_monthly
# Affordability check
affordable = total_monthly_ownership <= max_monthly_budget
budget_shortfall = max(0, total_monthly_ownership - max_monthly_budget)
# Calculate maximum affordable home price based on income (28% rule)
max_monthly_by_income = (annual_income / 12) * 0.28
max_affordable_payment = min(max_monthly_budget, max_monthly_by_income) - property_taxes - homeowners_insurance - maintenance - utilities_owned - pmi
if monthly_rate > 0:
max_loan_amount = max_affordable_payment * ((1 + monthly_rate)**num_payments - 1) / (monthly_rate * (1 + monthly_rate)**num_payments)
else:
max_loan_amount = max_affordable_payment * num_payments
max_affordable_price = max_loan_amount + down_payment
# Closing costs
closing_costs = target_purchase_price * 0.03 # Estimated 3% closing costs
total_upfront_costs = down_payment + closing_costs
# Auto-calculate available savings needed (recommend 25% buffer above minimum)
recommended_savings = total_upfront_costs * 1.25
return {
'estimated_utilities': utilities,
'current_monthly_total': total_current_monthly,
'down_payment': down_payment,
'loan_amount': loan_amount,
'mortgage_payment': mortgage_payment,
'property_taxes': property_taxes,
'homeowners_insurance': homeowners_insurance,
'maintenance': maintenance,
'pmi': pmi,
'total_monthly_ownership': total_monthly_ownership,
'monthly_difference': monthly_difference,
'affordable': affordable,
'budget_shortfall': budget_shortfall,
'max_affordable_price': max_affordable_price,
'closing_costs': closing_costs,
'total_upfront_costs': total_upfront_costs,
'recommended_savings': recommended_savings
}
def generate_comprehensive_analysis(user_situation, financial_data, market_data, goals):
"""
Generates a comprehensive renting vs buying analysis using AI.
"""
try:
# Format all numbers with proper spacing
down_payment_formatted = "${:,.0f}".format(financial_data['down_payment'])
total_upfront_formatted = "${:,.0f}".format(financial_data['total_upfront_costs'])
monthly_diff_amount = "${:,.0f}".format(abs(financial_data['monthly_difference']))
max_affordable_formatted = "${:,.0f}".format(financial_data['max_affordable_price'])
current_monthly_formatted = "${:,.0f}".format(financial_data['current_monthly_total'])
ownership_monthly_formatted = "${:,.0f}".format(financial_data['total_monthly_ownership'])
recommended_savings_formatted = "${:,.0f}".format(financial_data['recommended_savings'])
# Create properly spaced monthly difference text
monthly_diff_direction = "higher" if financial_data['monthly_difference'] > 0 else "lower"
monthly_difference_text = f"{monthly_diff_amount} {monthly_diff_direction} to own"
# Create properly spaced affordability status
if financial_data['affordable']:
affordability_status = "within budget"
else:
budget_shortfall_formatted = "${:,.0f}".format(financial_data['budget_shortfall'])
affordability_status = f"{budget_shortfall_formatted} over budget"
analysis_prompt = f"""
Based on the following information, provide a comprehensive renting vs buying analysis:
**Current Rental Situation:**
{user_situation}
**Financial Analysis:**
- Current monthly rental costs: {current_monthly_formatted} (including estimated utilities)
- Total monthly homeownership costs: {ownership_monthly_formatted}
- Monthly difference: {monthly_difference_text}
- Down payment required: {down_payment_formatted}
- Total upfront costs: {total_upfront_formatted}
- Recommended savings needed: {recommended_savings_formatted}
- Target home affordability: {affordability_status}
- Maximum affordable home price: {max_affordable_formatted}
**Market Data:**
{market_data}
**Goals:** {goals}
Provide a detailed analysis with the following sections:
1. **Executive Summary**: Clear recommendation on whether to continue renting or buy now
2. **Financial Impact Analysis**: Break down costs, long-term wealth building, and cash flow implications
3. **Market Timing Considerations**: How current market conditions affect first-time buyers
4. **Renting vs Buying Comparison**: Detailed pros and cons specific to their situation
5. **Affordability Assessment**: Whether their target home is realistic and alternatives if not
6. **First-Time Buyer Considerations**: Programs, incentives, and special considerations
7. **Action Plan**: Step-by-step next steps to prepare for homeownership
8. **Timeline Recommendations**: Best timing based on their goals and market conditions
9. **Risk Mitigation**: What could go wrong and how to prepare
10. **Alternative Scenarios**: What if interest rates change, prices drop, or income changes
Make this analysis practical and actionable for someone transitioning from renting to buying.
Include specific numbers, timeframes, and realistic expectations.
Address common first-time buyer concerns and misconceptions.
"""
messages = [{
"role": "system",
"content": """You are a senior mortgage advisor and first-time homebuyer specialist with 20+ years of experience.
You understand the unique challenges renters face when considering homeownership.
Provide thorough, unbiased analysis that considers financial readiness, market conditions, and personal factors.
Focus on practical steps and realistic expectations for first-time buyers.
Always include both the benefits and challenges of homeownership vs renting."""
}]
messages.append({"role": "user", "content": analysis_prompt})
response = client.chat.completions.create(
model="gpt-5",
messages=messages,
temperature=0.7
)
return response.choices[0].message.content
except Exception as e:
return f"Unable to generate analysis. Please check your inputs and try again. Error: {str(e)}"
# Streamlit setup
st.set_page_config(layout="wide", page_title="Rent vs Buy Decision Tool")
# Initialize session state
if "analysis_result" not in st.session_state:
st.session_state["analysis_result"] = None
if "show_processing" not in st.session_state:
st.session_state["show_processing"] = False
# Header
st.markdown("<h1 style='text-align: center; color: #2E4057;'>🏠 Rent vs Buy Analysis Tool</h1>", unsafe_allow_html=True)
st.markdown("<h3 style='text-align: center; color: #666;'>Get your personalized analysis in under 2 minutes</h3>", unsafe_allow_html=True)
# Simplified form in a single column for better flow
st.markdown("### πŸ“ Tell us about your situation")
# Essential inputs only - reduced from 14 to 6 fields
location = st.text_input("πŸ“ Where are you looking to buy?", placeholder="e.g., Austin, TX")
col1, col2 = st.columns(2)
with col1:
current_rent = st.number_input("πŸ’° Current Monthly Rent ($)", min_value=0, step=100, value=1500)
target_purchase_price = st.number_input("🏠 Target Home Price ($)", min_value=0, step=10000, value=350000)
annual_income = st.number_input("πŸ“Š Annual Household Income ($)", min_value=0, step=10000, value=75000)
with col2:
max_monthly_budget = st.number_input("πŸ“‹ Max Monthly Payment You Want ($)", min_value=0, step=100, value=2200)
down_payment_percent = st.slider("πŸ’³ Down Payment %", min_value=3, max_value=25, value=10,
help="Most first-time buyers put down 3-10%")
goals = st.text_area("🎯 Why are you considering buying?", placeholder="e.g., Build equity, want stability, growing family")
# Auto-filled/calculated values shown as info
st.markdown("---")
st.markdown("### πŸ“Š We'll automatically calculate:")
info_col1, info_col2, info_col3 = st.columns(3)
with info_col1:
st.info("πŸ“ˆ Current market interest rates")
with info_col2:
st.info("πŸ”§ Utilities & maintenance costs")
with info_col3:
st.info("πŸ’‘ First-time buyer programs")
# Analysis button
if st.button("πŸ” Get My Rent vs Buy Analysis", type="primary", use_container_width=True):
if not location or current_rent == 0 or max_monthly_budget == 0 or annual_income == 0:
st.error("Please fill in all the required fields to get your analysis.")
else:
st.session_state["show_processing"] = True
with st.spinner("Analyzing market data and generating your personalized report..."):
# Use current market rates (auto-calculated)
interest_rate = 7.0 # Can be fetched from current market data
# Gather market data
market_data = search_market_data(location, "Single Family Home") # Default to most common
# Calculate financial scenarios
financial_data = calculate_financial_analysis(
current_rent, target_purchase_price, down_payment_percent,
interest_rate, max_monthly_budget, annual_income
)
# Compile user situation with auto-calculated values
user_situation = f"""
Location: {location}
Current Monthly Rent: ${current_rent:,}
Total Current Monthly: ${financial_data['current_monthly_total']:,} (including estimated utilities)
Annual Income: ${annual_income:,}
Maximum Monthly Budget: ${max_monthly_budget:,}
Target Home Price: ${target_purchase_price:,}
Down Payment: {down_payment_percent}% (${financial_data['down_payment']:,})
Interest Rate: {interest_rate}% (current market rate)
"""
# Generate comprehensive analysis
st.session_state["analysis_result"] = generate_comprehensive_analysis(
user_situation, financial_data, market_data, goals
)
st.session_state["show_processing"] = False
# Display processing message
if st.session_state["show_processing"]:
st.info("πŸ”„ Analyzing current market conditions and generating your personalized report. This may take 1-2 minutes...")
# Display results
if st.session_state["analysis_result"]:
st.markdown("---")
st.markdown("<h2 style='text-align: center; color: #2E4057;'>πŸ“Š Your Personalized Rent vs Buy Analysis</h2>", unsafe_allow_html=True)
# Quick financial summary
if 'financial_data' in locals():
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Current Monthly Cost", f"${financial_data['current_monthly_total']:,.0f}")
with col2:
st.metric("Monthly Cost to Own", f"${financial_data['total_monthly_ownership']:,.0f}")
with col3:
monthly_change = financial_data['monthly_difference']
st.metric("Monthly Difference", f"${abs(monthly_change):,.0f}",
delta=f"{'More' if monthly_change > 0 else 'Less'}")
with col4:
st.metric("Down Payment Needed", f"${financial_data['down_payment']:,.0f}")
# Affordability indicator
if financial_data['affordable']:
st.success("βœ… This home is within your budget!")
else:
st.warning(f"⚠️ This home is ${financial_data['budget_shortfall']:,.0f} over your monthly budget.")
st.info(f"πŸ’‘ Based on your income and budget, you can afford up to ${financial_data['max_affordable_price']:,.0f}")
st.markdown("---")
st.markdown(st.session_state["analysis_result"])
# Call-to-action
st.markdown("---")
st.markdown("""
### 🎯 Ready to Take the Next Step?
This analysis provides a foundation for your rent vs buy decision, but every situation is unique.
Consider speaking with a mortgage advisor who can help you understand your financing options
and a local real estate agent who knows your target market.
**Next Steps:**
- Get pre-approved for a mortgage to know your exact budget
- Start following local market trends and inventory
- Consider working with a buyer's agent who represents your interests
- Review first-time homebuyer programs in your area
""")
# Footer
st.markdown("---")
st.markdown("""
<div style='text-align: center; color: #666; font-size: 12px;'>
πŸ“ˆ Market data and analysis are for informational purposes only. Consult with qualified professionals before making financial decisions.
</div>
""", unsafe_allow_html=True)