Spaces:
Sleeping
Sleeping
| ''' | |
| graphical line diagram of stock cumulative returns | |
| Note: Raw Data is from Yahoo Finance using python yfinance | |
| Author: Gang Luo | |
| Revision history: | |
| 2024-01-28.1: | |
| Creation of the file | |
| 2025-02.23.0027: fixing an issue (https://github.com/ranaroussi/yfinance/issues/2283) | |
| which is introduced by yfinance version 0.2.54 (released on Feb 18, 2025 ). | |
| The "Adj Close" column is missing from yf.download since yf.download default changed | |
| from auto_adjust=False to auto_adjust=True. When auto_adjust=True, column Close is actually Adj Close and | |
| Adj Close column does not exist any more. In order to fix the issue, auto_adjust=False is used explicitly in download function, | |
| to get back the Adj Close column. | |
| The "Adj Close" column is also missing from using ticker = yf.Ticker("AAPL") data = ticker.history(period="1y") | |
| ''' | |
| script_version = '(2025-0223-1156)' | |
| # Import the libraries | |
| import gradio as gr | |
| import yfinance as yf | |
| import pandas as pd | |
| import matplotlib | |
| def stock_return_df(tickers, start, end): | |
| # Download the historical data | |
| data = yf.download(tickers, start=start, end=end, auto_adjust=False) # yf.download default changed to auto_adjust=True at yfinance version 0.2.54, | |
| # when auto_adjust=True, Close = Adj Close and Adj Close does not exist | |
| # Calculate the daily and cumulative percentage change | |
| data_adj_close = data['Adj Close'] | |
| data_adj_close_pct = data_adj_close.pct_change() | |
| data_adj_close_pct_cum = (data_adj_close_pct + 1).cumprod(axis=0) - 1 | |
| return data_adj_close_pct_cum | |
| def plot_graph(tickers, start, end): | |
| data_adj_close_pct_cum=stock_return_df(tickers, start, end) | |
| # Plot a line chart of the salary by name | |
| #ax = data_adj_close_pct_cum.plot.line(x="Name", y="Salary", rot=0, legend=False, style="-o", markersize=10, color="green") | |
| ax = data_adj_close_pct_cum.plot() | |
| ax.set_ylabel("Percentage") | |
| ax.set_title("Cumulative Returns") | |
| # Return the plot as a matplotlib figure | |
| return ax.get_figure() | |
| # Create a gradio.Interface object with the DataFrame component as input and the Matplotlib component as output | |
| interface = gr.Interface( | |
| fn=plot_graph, # The function to call | |
| inputs=[gr.Textbox(label="Tickers", value="qqq,spy,vfv.to,xiu.to,xfn.to,ry.to"), | |
| gr.Textbox(label="Start Date", value="2014-01-01"), | |
| gr.Textbox(label="End Date", value="2023-12-30")], | |
| outputs=gr.Plot(label="Output Plot"), # The Matplotlib component as output | |
| title="Stock cumulative returns - DataFrame Line Plot by Gradio" # The title of the interface | |
| ) | |
| # Launch the interface | |
| interface.launch(debug=False) |