Spaces:
Sleeping
Sleeping
Update space_stock_plot.py
Browse files- space_stock_plot.py +43 -6
space_stock_plot.py
CHANGED
|
@@ -1,7 +1,44 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
graphical line diagram of stock cumulative returns
|
| 3 |
+
|
| 4 |
+
Note: Raw Data is from Yahoo Finance using python yfinance
|
| 5 |
+
'''
|
| 6 |
+
script_version = '(2024-01-28.1)'
|
| 7 |
+
# Import the libraries
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import yfinance as yf
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
def stock_return_df(tickers, start, end):
|
| 13 |
+
# Download the historical data
|
| 14 |
+
data = yf.download(tickers, start=start, end=end)
|
| 15 |
+
# Calculate the daily and cumulative percentage change
|
| 16 |
+
data_adj_close = data['Adj Close']
|
| 17 |
+
data_adj_close_pct = data_adj_close.pct_change()
|
| 18 |
+
data_adj_close_pct_cum = (data_adj_close_pct + 1).cumprod(axis=0) - 1
|
| 19 |
+
return data_adj_close_pct_cum
|
| 20 |
+
|
| 21 |
+
def plot_graph(tickers, start, end):
|
| 22 |
+
data_adj_close_pct_cum=stock_return_df(tickers, start, end)
|
| 23 |
+
# Plot a line chart of the salary by name
|
| 24 |
+
#ax = data_adj_close_pct_cum.plot.line(x="Name", y="Salary", rot=0, legend=False, style="-o", markersize=10, color="green")
|
| 25 |
+
ax = data_adj_close_pct_cum.plot()
|
| 26 |
+
ax.set_ylabel("Percentage")
|
| 27 |
+
ax.set_title("Cumulative Returns")
|
| 28 |
+
# Return the plot as a matplotlib figure
|
| 29 |
+
return ax.get_figure()
|
| 30 |
+
|
| 31 |
+
# Create a gradio.Interface object with the DataFrame component as input and the Matplotlib component as output
|
| 32 |
+
interface = gr.Interface(
|
| 33 |
+
fn=plot_graph, # The function to call
|
| 34 |
+
inputs=[gr.Textbox(label="Tickers", value="qqq,spy,vfv.to,xiu.to,xfn.to,ry.to"),
|
| 35 |
+
gr.Textbox(label="Start Date", value="2014-01-01"),
|
| 36 |
+
gr.Textbox(label="End Date", value="2023-12-30")],
|
| 37 |
+
outputs=gr.Plot(label="Output Plot"), # The Matplotlib component as output
|
| 38 |
+
title="Stock cumulative returns - DataFrame Line Plot by Gradio" # The title of the interface
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# Launch the interface
|
| 42 |
+
interface.launch(debug=False)
|
| 43 |
+
|
| 44 |
|