DagonGod / portfolio.py
ratulsur's picture
Create portfolio.py
6774854 verified
Raw
History Blame Contribute Delete
4.26 kB
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")