import streamlit as st import pandas as pd import numpy as np import matplotlib.pyplot as plt import yfinance as yf from utils.quantum_algorithms import QuantumInspiredOptimizer from utils.deepseek_api import DeepSeekAI from datetime import datetime # ⚛️ Initialize Quantum Optimizer & DeepSeek AI quantum_optimizer = QuantumInspiredOptimizer() deepseek_ai = DeepSeekAI() # 🎯 Page Config st.set_page_config(page_title="Investor Portfolio", layout="wide") st.title("📊 Investor Portfolio Management") # 📤 Upload Portfolio File uploaded_file = st.file_uploader("📂 Upload Portfolio CSV/Excel file", type=["csv", "xlsx"]) if uploaded_file: st.success("✅ Portfolio Uploaded Successfully!") # 📌 Read File file_extension = uploaded_file.name.split(".")[-1] if file_extension == "csv": df = pd.read_csv(uploaded_file) else: df = pd.read_excel(uploaded_file) # 📊 Display Portfolio Preview st.subheader("📊 Portfolio Overview") st.write(df.head()) # Ensure required columns exist required_columns = ["Stock Symbol", "Quantity", "Purchase Price"] missing_columns = [col for col in required_columns if col not in df.columns] if missing_columns: st.error(f"⚠️ Missing required columns: {missing_columns}") else: st.success("✅ Valid Portfolio File Detected") # 🎯 **Fetch Live Market Data** st.subheader("📈 Live Market Tracking") df["Current Price"] = df["Stock Symbol"].apply(lambda x: yf.Ticker(x).history(period="1d")["Close"].iloc[-1] if not yf.Ticker(x).history(period="1d").empty else np.nan) df["Market Value"] = df["Quantity"] * df["Current Price"] df["Unrealized Gain/Loss (%)"] = ((df["Current Price"] - df["Purchase Price"]) / df["Purchase Price"]) * 100 # 📊 Show Updated Portfolio st.dataframe(df) # 📉 **Portfolio Performance Visualization** st.subheader("📉 Portfolio Performance") fig, ax = plt.subplots(figsize=(12, 6)) ax.bar(df["Stock Symbol"], df["Unrealized Gain/Loss (%)"], color=["green" if x > 0 else "red" for x in df["Unrealized Gain/Loss (%)"]]) ax.set_ylabel("Unrealized Gain/Loss (%)") ax.set_title("Portfolio Stock Performance") st.pyplot(fig) # ⚛️ **Quantum Analysis on Portfolio** st.subheader("⚛️ Quantum Portfolio Insights") portfolio_prices = df["Current Price"].dropna().values quantum_patterns = quantum_optimizer.quantum_pattern_detection(portfolio_prices) # Plot Quantum Patterns fig, ax1 = plt.subplots(figsize=(12, 6)) ax1.plot(df["Stock Symbol"], portfolio_prices, label="Current Price", color="blue") ax2 = ax1.twinx() ax2.plot(df["Stock Symbol"], quantum_patterns, label="Quantum Pattern Strength", color="orange", linestyle="dashed") ax1.set_title("Quantum Stock Pattern Detection") ax1.set_ylabel("Price") ax2.set_ylabel("Pattern Strength") ax1.legend(loc="upper left") ax2.legend(loc="upper right") st.pyplot(fig) # 🔮 **DeepSeek AI Investment Insights** st.subheader("🤖 AI-Powered Investment Insights") portfolio_summary = df[["Stock Symbol", "Unrealized Gain/Loss (%)"]].to_dict(orient="records") ai_prompt = f""" Analyze the following investor portfolio using AI and quantum methods. Provide risk assessment, investment insights, and potential improvements. Portfolio Data: {portfolio_summary} """ with st.spinner("🔍 Generating AI Insights..."): deepseek_response = deepseek_ai.analyze_portfolio(ai_prompt) st.write(deepseek_response) # 🏆 **Portfolio Metrics** st.subheader("📊 Key Portfolio Metrics") col1, col2, col3 = st.columns(3) with col1: st.metric("📈 Total Market Value", f"₹{df['Market Value'].sum():,.2f}") with col2: st.metric("📊 Average Unrealized Gain/Loss (%)", f"{df['Unrealized Gain/Loss (%)'].mean():.2f}%") with col3: st.metric("⚠️ Risk Level", "Moderate" if df['Unrealized Gain/Loss (%)'].mean() > 0 else "High Risk")