aiqtech commited on
Commit
0d01ec2
ยท
verified ยท
1 Parent(s): 2cd8d3b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -46
app.py CHANGED
@@ -1,67 +1,50 @@
1
  import gradio as gr
2
  import yfinance as yf
3
- from pypfopt import EfficientFrontier, risk_models, expected_returns
4
- import pandas as pd
5
- import plotly.graph_objects as go
6
  from datetime import datetime
7
 
8
- def download_data(tickers, start_date, end_date):
 
9
  attempts = 0
10
  while attempts < 3:
11
  try:
12
- return yf.download(tickers, start=start_date, end=end_date)
 
 
 
13
  except Exception as e:
14
  print(f"Download failed on attempt {attempts + 1}: {e}")
15
  attempts += 1
16
  raise Exception("Failed to download data after multiple attempts")
17
 
18
- def plot_efficient_frontier_custom(mu, S):
19
- ef = EfficientFrontier(mu, S)
20
- fig = go.Figure()
 
21
 
22
- # ํšจ์œจ์  ํˆฌ์ž์„  ์ƒ์„ฑ
23
- weights = ef.max_sharpe()
24
- cleaned_weights = ef.clean_weights()
25
- ret_sharpe, std_sharpe, _ = ef.portfolio_performance(verbose=True)
26
-
27
- # ํˆฌ์ž์„  ๋ฐ ์ตœ๋Œ€ ์ƒคํ”„ ํฌ์ธํŠธ ๊ทธ๋ž˜ํ”ฝ ์ถ”๊ฐ€
28
- fig.add_scatter(x=[std_sharpe], y=[ret_sharpe], mode='markers', marker=dict(color='red', size=10), name='Max Sharpe Ratio')
29
- fig.update_layout(title='Efficient Frontier', xaxis_title='Volatility (Std. Deviation)', yaxis_title='Expected Returns', legend_title='Portfolio')
30
- return fig
31
-
32
-
33
-
34
- def output_results(start_date, end_date, tickers_string):
35
- tickers = [ticker.strip() for ticker in tickers_string.split(',')]
36
- stocks_df = yf.download(tickers, start=start_date, end=end_date)['Adj Close']
37
-
38
- mu = expected_returns.mean_historical_return(stocks_df)
39
- S = risk_models.sample_cov(stocks_df)
40
 
41
- # ๊ณต๋ถ„์‚ฐ ํ–‰๋ ฌ์ด ๋Œ€์นญ์ธ์ง€ ํ™•์ธ
42
- if not (S.T == S).all().all(): # ๋ชจ๋“  ๊ฐ’์ด ๋Œ€์นญ์ธ์ง€ ํ™•์ธ
43
- raise ValueError("๊ณต๋ถ„์‚ฐ ํ–‰๋ ฌ์ด ๋Œ€์นญ์ด ์•„๋‹™๋‹ˆ๋‹ค.")
44
-
45
- ef = EfficientFrontier(mu, S)
46
- weights = ef.max_sharpe()
47
- cleaned_weights = ef.clean_weights()
48
- fig_weights = plot_weights(cleaned_weights)
49
- expected_annual_return, annual_volatility, sharpe_ratio = ef.portfolio_performance()
50
-
51
- return fig_weights, expected_annual_return, annual_volatility, sharpe_ratio
52
 
53
- # Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ดˆ๊ธฐํ™” ๋ฐ ์‹คํ–‰
54
- # (์—ฌ๊ธฐ์— Gradio ์ธํ„ฐํŽ˜์ด์Šค ์„ค์ • ์ฝ”๋“œ ์ถ”๊ฐ€)
55
-
56
 
 
57
  with gr.Blocks() as app:
58
  with gr.Row():
59
- start_date = gr.Textbox("2013-01-01", label="Start Date")
60
- end_date = gr.Textbox(datetime.now().date(), label="End Date")
61
- tickers_string = gr.Textbox("AAPL,MSFT,AMZN", label="Enter tickers separated by comma")
62
- btn = gr.Button("Show Efficient Frontier")
 
63
 
64
- fig_efficient_frontier = gr.Plot(label="Efficient Frontier")
65
- btn.click(fn=output_results, inputs=[start_date, end_date, tickers_string], outputs=fig_efficient_frontier)
 
 
 
66
 
67
  app.launch()
 
1
  import gradio as gr
2
  import yfinance as yf
3
+ from prophet import Prophet
4
+ import plotly.express as px
 
5
  from datetime import datetime
6
 
7
+ def download_data(tickers, start_date='2010-01-01'):
8
+ """ ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค์šด๋กœ๋“œํ•˜๋Š” ํ•จ์ˆ˜, ์ตœ๋Œ€ 3๋ฒˆ ์‹œ๋„ """
9
  attempts = 0
10
  while attempts < 3:
11
  try:
12
+ data = yf.download(tickers, start=start_date)
13
+ if 'Adj Close' in data.columns:
14
+ return data['Adj Close'].reset_index()
15
+ return data.reset_index()
16
  except Exception as e:
17
  print(f"Download failed on attempt {attempts + 1}: {e}")
18
  attempts += 1
19
  raise Exception("Failed to download data after multiple attempts")
20
 
21
+ def predict_future_prices(ticker):
22
+ """ Prophet์„ ์‚ฌ์šฉํ•œ ์ฃผ์‹ ๊ฐ€๊ฒฉ ์˜ˆ์ธก """
23
+ data = download_data(ticker)
24
+ data.rename(columns={'Date': 'ds', ticker: 'y'}, inplace=True)
25
 
26
+ model = Prophet(daily_seasonality=False, yearly_seasonality=True)
27
+ model.fit(data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ future = model.make_future_dataframe(periods=5 * 365) # ํ–ฅํ›„ 5๋…„
30
+ forecast = model.predict(future)
 
 
 
 
 
 
 
 
 
31
 
32
+ fig = px.line(forecast, x='ds', y='yhat', title=f'5-Year Future Price Forecast for {ticker}')
33
+ return fig, forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]
 
34
 
35
+ # Gradio ์ธํ„ฐํŽ˜์ด์Šค ์„ค์ •
36
  with gr.Blocks() as app:
37
  with gr.Row():
38
+ ticker_input = gr.Textbox(value="AAPL", label="Enter Stock Ticker")
39
+ forecast_button = gr.Button("Generate 5-Year Forecast")
40
+
41
+ forecast_chart = gr.Plot(label="Future Price Forecast")
42
+ forecast_data = gr.Dataframe(label="Forecast Data Table")
43
 
44
+ forecast_button.click(
45
+ fn=predict_future_prices,
46
+ inputs=ticker_input,
47
+ outputs=[forecast_chart, forecast_data]
48
+ )
49
 
50
  app.launch()