Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import yfinance as yf | |
| import numpy as np | |
| from datetime import datetime | |
| def calculate_sharpe_ratios(end_date, sharpe_threshold, top_ten_tickers): | |
| sharpe_ratios = [] | |
| for ticker_symbol in top_ten_tickers.split('\n'): | |
| try: | |
| ticker_info = yf.Ticker(ticker_symbol) | |
| ticker_history = ticker_info.history(period="max") | |
| if not ticker_history.empty: | |
| start_date = ticker_history.index[0].strftime('%Y-%m-%d') | |
| stock_data = yf.download(ticker_symbol, start=start_date, end=end_date) | |
| if not stock_data['Close'].empty: | |
| stock_data['Daily_Return'] = stock_data['Close'].pct_change() | |
| risk_free_rate = 0.03 | |
| daily_risk_free_rate = (1 + risk_free_rate) ** (1/252) - 1 | |
| daily_returns = stock_data['Daily_Return'] | |
| sharpe_ratio = np.mean(daily_returns - daily_risk_free_rate) / np.std(daily_returns) | |
| sharpe_ratios.append((ticker_symbol, sharpe_ratio)) | |
| except Exception as e: | |
| print(f"Error processing {ticker_symbol}: {e}") | |
| # Sort the list of tuples based on Sharpe ratios | |
| sorted_sharpe_ratios = sorted(sharpe_ratios, key=lambda x: x[1], reverse=True) | |
| # Get the top ten tickers with the highest Sharpe ratios | |
| top_ten = [] | |
| for rank, (ticker, ratio) in enumerate(sorted_sharpe_ratios[:10], 1): | |
| result = f"Rank: {rank}\nTicker: {ticker}\nSharpe Ratio: {ratio}\n---------------------" | |
| top_ten.append(result) | |
| return "\n".join(top_ten) | |
| iface = gr.Interface( | |
| fn=calculate_sharpe_ratios, | |
| inputs=[ | |
| gr.inputs.Date(label="End Date", default=datetime.now().strftime('%Y-%m-%d')), | |
| "text", # Sharpe Threshold input | |
| "text" # Top Ten Tickers input | |
| ], | |
| outputs=gr.outputs.Textbox(label="Top Ten Tickers with Highest Sharpe Ratios"), | |
| title="Sharpe Ratio Calculator", | |
| description="Calculate top ten tickers with highest Sharpe ratios based on provided parameters" | |
| ) | |
| iface.launch() | |