AnilNiraula commited on
Commit
c3d0e6b
·
verified ·
1 Parent(s): 09b9f96

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -55
app.py CHANGED
@@ -1,64 +1,102 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
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()