Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
CHANGED
|
@@ -1,64 +1,102 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
system_message,
|
| 14 |
-
max_tokens,
|
| 15 |
-
temperature,
|
| 16 |
-
top_p,
|
| 17 |
-
):
|
| 18 |
-
messages = [{"role": "system", "content": system_message}]
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
messages.append({"role": "user", "content": message})
|
| 27 |
-
|
| 28 |
-
response = ""
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
):
|
| 37 |
-
token = message.choices[0].delta.content
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
]
|
| 60 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
|
|
|
| 63 |
if __name__ == "__main__":
|
| 64 |
demo.launch()
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
# This script creates an interactive dashboard for viewing an investment portfolio using Gradio.
|
| 3 |
+
# It fetches real-time stock prices via yfinance and displays portfolio metrics, including a table and pie chart.
|
| 4 |
+
# To deploy on Hugging Face Spaces:
|
| 5 |
+
# 1. Create a new Space on Hugging Face.
|
| 6 |
+
# 2. Upload this file as app.py.
|
| 7 |
+
# 3. Add a requirements.txt file with the following content:
|
| 8 |
+
# gradio
|
| 9 |
+
# yfinance
|
| 10 |
+
# pandas
|
| 11 |
+
# matplotlib
|
| 12 |
+
# 4. The Space will automatically install the dependencies and run the app.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
import gradio as gr
|
| 15 |
+
import yfinance as yf
|
| 16 |
+
import pandas as pd
|
| 17 |
+
import matplotlib.pyplot as plt
|
| 18 |
+
from io import BytesIO
|
| 19 |
+
import base64
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
# Define the portfolio data
|
| 22 |
+
portfolio = {
|
| 23 |
+
'Ticker': ['TSLA', 'PLTR', 'SOUN'],
|
| 24 |
+
'Shares': [200, 490, 652],
|
| 25 |
+
'Avg Cost': [245.0, 52.0, 7.5]
|
| 26 |
+
}
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
def get_current_prices(tickers):
|
| 29 |
+
"""
|
| 30 |
+
Fetch the latest closing prices for the given tickers.
|
| 31 |
+
"""
|
| 32 |
+
data = yf.download(tickers, period='1d')['Close']
|
| 33 |
+
return data.iloc[-1]
|
| 34 |
|
| 35 |
+
def generate_pie_chart(values, labels):
|
| 36 |
+
"""
|
| 37 |
+
Generate a pie chart as a base64-encoded image.
|
| 38 |
+
"""
|
| 39 |
+
fig, ax = plt.subplots()
|
| 40 |
+
ax.pie(values, labels=labels, autopct='%1.1f%%', startangle=90)
|
| 41 |
+
ax.set_title('Portfolio Allocation by Current Value')
|
| 42 |
+
ax.axis('equal') # Equal aspect ratio ensures the pie is circular.
|
| 43 |
+
|
| 44 |
+
buf = BytesIO()
|
| 45 |
+
plt.savefig(buf, format='png')
|
| 46 |
+
buf.seek(0)
|
| 47 |
+
img_base64 = base64.b64encode(buf.read()).decode('utf-8')
|
| 48 |
+
plt.close(fig)
|
| 49 |
+
return f"data:image/png;base64,{img_base64}"
|
| 50 |
|
| 51 |
+
def display_portfolio():
|
| 52 |
+
"""
|
| 53 |
+
Compute portfolio metrics and generate outputs.
|
| 54 |
+
"""
|
| 55 |
+
df = pd.DataFrame(portfolio)
|
| 56 |
+
try:
|
| 57 |
+
prices = get_current_prices(df['Ticker'].tolist())
|
| 58 |
+
df['Current Price'] = prices.values
|
| 59 |
+
except Exception as e:
|
| 60 |
+
return f"Error fetching prices: {str(e)}", "", "N/A", "N/A"
|
| 61 |
+
|
| 62 |
+
df['Cost Basis'] = df['Shares'] * df['Avg Cost']
|
| 63 |
+
df['Current Value'] = df['Shares'] * df['Current Price']
|
| 64 |
+
df['Gain/Loss'] = df['Current Value'] - df['Cost Basis']
|
| 65 |
+
df['Gain/Loss %'] = (df['Gain/Loss'] / df['Cost Basis']) * 100
|
| 66 |
+
|
| 67 |
+
total_cost = df['Cost Basis'].sum()
|
| 68 |
+
total_value = df['Current Value'].sum()
|
| 69 |
+
total_gain = total_value - total_cost
|
| 70 |
+
|
| 71 |
+
# Format the table as HTML
|
| 72 |
+
table_html = df.to_html(index=False, float_format=lambda x: f'{x:.2f}')
|
| 73 |
+
|
| 74 |
+
# Generate pie chart
|
| 75 |
+
pie_img = generate_pie_chart(df['Current Value'], df['Ticker'])
|
| 76 |
+
|
| 77 |
+
total_value_str = f"${total_value:.2f}"
|
| 78 |
+
total_gain_str = f"${total_gain:.2f} ({(total_gain / total_cost * 100):.2f}%)"
|
| 79 |
+
|
| 80 |
+
return table_html, pie_img, total_value_str, total_gain_str
|
| 81 |
|
| 82 |
+
# Create the Gradio interface
|
| 83 |
+
with gr.Blocks(title="Investment Portfolio Dashboard") as demo:
|
| 84 |
+
gr.Markdown("# Investment Portfolio Dashboard")
|
| 85 |
+
gr.Markdown("View your portfolio metrics with real-time stock prices.")
|
| 86 |
+
|
| 87 |
+
refresh_btn = gr.Button("Refresh Data")
|
| 88 |
+
|
| 89 |
+
table_output = gr.HTML(label="Portfolio Table")
|
| 90 |
+
pie_output = gr.Image(label="Portfolio Allocation", type="pil") # Will display base64 image
|
| 91 |
+
total_value_output = gr.Textbox(label="Total Portfolio Value")
|
| 92 |
+
total_gain_output = gr.Textbox(label="Total Gain/Loss")
|
| 93 |
+
|
| 94 |
+
refresh_btn.click(
|
| 95 |
+
fn=display_portfolio,
|
| 96 |
+
inputs=[],
|
| 97 |
+
outputs=[table_output, pie_output, total_value_output, total_gain_output]
|
| 98 |
+
)
|
| 99 |
|
| 100 |
+
# Launch the demo (automatically handled in Hugging Face Spaces)
|
| 101 |
if __name__ == "__main__":
|
| 102 |
demo.launch()
|