Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,11 +5,9 @@ import plotly.express as px
|
|
| 5 |
import yfinance as yf
|
| 6 |
import gradio as gr
|
| 7 |
|
| 8 |
-
# ---
|
| 9 |
-
companies = [
|
| 10 |
-
|
| 11 |
-
"Tesla", "IBM", "Intel", "Netflix", "Adobe"
|
| 12 |
-
]
|
| 13 |
|
| 14 |
TICKERS = {
|
| 15 |
"Microsoft": "MSFT",
|
|
@@ -26,102 +24,106 @@ TICKERS = {
|
|
| 26 |
|
| 27 |
HF_DATASET = "SelmaNajih001/FT_MultiCompany"
|
| 28 |
MODEL_SENTIMENT = "SelmaNajih001/SentimentBasedOnPriceVariation"
|
| 29 |
-
|
|
|
|
| 30 |
|
| 31 |
# --- PIPELINES ---
|
| 32 |
sentiment_pipeline = pipeline("sentiment-analysis", model=MODEL_SENTIMENT)
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
except Exception:
|
| 52 |
-
df.at[i, 'Sentiment'] = 'ERROR'
|
| 53 |
-
df.at[i, 'Confidence'] = 0.0
|
| 54 |
-
|
| 55 |
-
# --- CALCOLO PREVISIONI PREZZI ---
|
| 56 |
-
df['Predicted'] = 0.0
|
| 57 |
-
for i, row in df.iterrows():
|
| 58 |
try:
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
for company, ticker in TICKERS.items():
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
df_prices =
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
# ---
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
)
|
| 111 |
-
|
| 112 |
-
# ---
|
| 113 |
-
|
| 114 |
-
|
| 115 |
|
| 116 |
demo = gr.Interface(
|
| 117 |
-
fn=
|
| 118 |
inputs=[],
|
| 119 |
-
outputs=
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
],
|
| 123 |
-
title="Analisi Sentiment e Previsioni Prezzi Azionari",
|
| 124 |
-
description="Visualizza le strategie basate su sentiment e modelli di previsione dei prezzi per diverse aziende."
|
| 125 |
)
|
| 126 |
|
| 127 |
demo.launch()
|
|
|
|
| 5 |
import yfinance as yf
|
| 6 |
import gradio as gr
|
| 7 |
|
| 8 |
+
# --- CONFIG ---
|
| 9 |
+
companies = ["Microsoft", "Apple", "Google", "Amazon", "Facebook",
|
| 10 |
+
"Tesla", "IBM", "Intel", "Netflix", "Adobe"]
|
|
|
|
|
|
|
| 11 |
|
| 12 |
TICKERS = {
|
| 13 |
"Microsoft": "MSFT",
|
|
|
|
| 24 |
|
| 25 |
HF_DATASET = "SelmaNajih001/FT_MultiCompany"
|
| 26 |
MODEL_SENTIMENT = "SelmaNajih001/SentimentBasedOnPriceVariation"
|
| 27 |
+
MODEL_PRICE_TESLA = "SelmaNajih001/PricePredictionForTesla"
|
| 28 |
+
MODEL_PRICE_MICROSOFT = "SelmaNajih001/PricePredictionForMicrosoft"
|
| 29 |
|
| 30 |
# --- PIPELINES ---
|
| 31 |
sentiment_pipeline = pipeline("sentiment-analysis", model=MODEL_SENTIMENT)
|
| 32 |
+
price_pipeline_tesla = pipeline("text-classification", model=MODEL_PRICE_TESLA)
|
| 33 |
+
price_pipeline_msft = pipeline("text-classification", model=MODEL_PRICE_MICROSOFT)
|
| 34 |
+
|
| 35 |
+
# --- LOAD DATASET ---
|
| 36 |
+
df_multi = pd.DataFrame(load_dataset(HF_DATASET)["train"])
|
| 37 |
+
df_multi['date'] = pd.to_datetime(df_multi['Data'], errors='coerce')
|
| 38 |
+
df_multi['date_merge'] = df_multi['date'].dt.normalize()
|
| 39 |
+
df_multi.sort_values('date', inplace=True)
|
| 40 |
+
|
| 41 |
+
# --- SENTIMENT & PREDICTION ---
|
| 42 |
+
df_multi['Sentiment'] = ""
|
| 43 |
+
df_multi['Confidence'] = 0.0
|
| 44 |
+
df_multi['Predicted'] = 0.0
|
| 45 |
+
|
| 46 |
+
for i, row in df_multi.iterrows():
|
| 47 |
+
company = row['Company']
|
| 48 |
+
|
| 49 |
+
# Sentiment for all companies
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
try:
|
| 51 |
+
res = sentiment_pipeline(row['Riassunto'])[0]
|
| 52 |
+
df_multi.at[i,'Sentiment'] = res['label'].upper().strip()
|
| 53 |
+
df_multi.at[i,'Confidence'] = res['score']
|
| 54 |
+
except:
|
| 55 |
+
df_multi.at[i,'Sentiment'] = 'ERROR'
|
| 56 |
+
df_multi.at[i,'Confidence'] = 0.0
|
| 57 |
+
|
| 58 |
+
# Regression only for Tesla & Microsoft
|
| 59 |
+
if company == "Tesla":
|
| 60 |
+
try:
|
| 61 |
+
val = price_pipeline_tesla(row['Riassunto'])[0]['score']
|
| 62 |
+
df_multi.at[i,'Predicted'] = min(val, 1.0)
|
| 63 |
+
except:
|
| 64 |
+
df_multi.at[i,'Predicted'] = 0.0
|
| 65 |
+
elif company == "Microsoft":
|
| 66 |
+
try:
|
| 67 |
+
val = price_pipeline_msft(row['Riassunto'])[0]['score']
|
| 68 |
+
df_multi.at[i,'Predicted'] = min(val, 1.0)
|
| 69 |
+
except:
|
| 70 |
+
df_multi.at[i,'Predicted'] = 0.0
|
| 71 |
+
|
| 72 |
+
# --- FETCH STOCK PRICES ---
|
| 73 |
+
prices = {}
|
| 74 |
for company, ticker in TICKERS.items():
|
| 75 |
+
start_date = df_multi[df_multi['Company']==company]['date'].min()
|
| 76 |
+
end_date = pd.Timestamp.today()
|
| 77 |
+
df_prices = yf.download(ticker, start=start_date, end=end_date)[['Close']].reset_index()
|
| 78 |
+
df_prices['date_merge'] = pd.to_datetime(df_prices['Date']).dt.normalize()
|
| 79 |
+
df_prices['PctChangeDaily'] = df_prices['Close'].pct_change().shift(-1)
|
| 80 |
+
prices[company] = df_prices
|
| 81 |
+
|
| 82 |
+
# --- MERGE & CALCULATE STRATEGIES ---
|
| 83 |
+
dfs_final = {}
|
| 84 |
+
for company in companies:
|
| 85 |
+
df_c = df_multi[df_multi['Company']==company].copy()
|
| 86 |
+
df_c = pd.merge(df_c, prices[company], on='date_merge', how='inner')
|
| 87 |
+
|
| 88 |
+
# Strategy A: Sentiment
|
| 89 |
+
df_c['StrategyA_Daily'] = 0
|
| 90 |
+
df_c['StrategyA_Cumulative'] = 0
|
| 91 |
+
for i in range(1, len(df_c)):
|
| 92 |
+
score = df_c.loc[i,'Confidence']
|
| 93 |
+
pct = df_c.loc[i,'PctChangeDaily'] if pd.notnull(df_c.loc[i,'PctChangeDaily']) else 0
|
| 94 |
+
if df_c.loc[i,'Sentiment']=="UP" and score>0.8:
|
| 95 |
+
df_c.loc[i,'StrategyA_Daily'] = df_c.loc[i,'Close']*pct
|
| 96 |
+
elif df_c.loc[i,'Sentiment']=="DOWN" and score>0.8:
|
| 97 |
+
df_c.loc[i,'StrategyA_Daily'] = df_c.loc[i,'Close']*pct*-1
|
| 98 |
+
df_c.loc[i,'StrategyA_Cumulative'] = df_c.loc[i-1,'StrategyA_Cumulative'] + df_c.loc[i,'StrategyA_Daily']
|
| 99 |
+
|
| 100 |
+
# Strategy B: Regression (only Tesla & Microsoft)
|
| 101 |
+
df_c['StrategyB_Daily'] = df_c['Predicted']*df_c['PctChangeDaily']*df_c['Close']
|
| 102 |
+
df_c['StrategyB_Cumulative'] = df_c['StrategyB_Daily'].cumsum()
|
| 103 |
+
|
| 104 |
+
dfs_final[company] = df_c
|
| 105 |
+
|
| 106 |
+
# --- PLOT STRATEGIES ---
|
| 107 |
+
df_plot_A = pd.concat([df[['Data','StrategyA_Cumulative']].assign(Company=company) for company, df in dfs_final.items()], ignore_index=True)
|
| 108 |
+
df_plot_B = pd.concat([df[['Data','StrategyB_Cumulative']].assign(Company=company) for company, df in dfs_final.items()], ignore_index=True)
|
| 109 |
+
|
| 110 |
+
fig_strategy_A = px.line(df_plot_A, x='Data', y='StrategyA_Cumulative', color='Company',
|
| 111 |
+
title="Portfolio Evolution Following Strategy A (Sentiment)",
|
| 112 |
+
labels={'StrategyA_Cumulative':'Cumulative Value','Data':'Date'})
|
| 113 |
+
fig_strategy_B = px.line(df_plot_B, x='Data', y='StrategyB_Cumulative', color='Company',
|
| 114 |
+
title="Portfolio Evolution Following Strategy B (Regression)",
|
| 115 |
+
labels={'StrategyB_Cumulative':'Cumulative Value','Data':'Date'})
|
| 116 |
+
|
| 117 |
+
# --- GRADIO INTERFACE ---
|
| 118 |
+
outputs = [gr.Dataframe(label=company) for company in dfs_final.keys()]
|
| 119 |
+
outputs += [gr.Plot(label="Strategy A: Sentiment"), gr.Plot(label="Strategy B: Regression")]
|
| 120 |
|
| 121 |
demo = gr.Interface(
|
| 122 |
+
fn=lambda: [df.head(10) for df in dfs_final.values()] + [fig_strategy_A, fig_strategy_B],
|
| 123 |
inputs=[],
|
| 124 |
+
outputs=outputs,
|
| 125 |
+
title="Portfolio Evolution: Strategy A vs Strategy B",
|
| 126 |
+
description="Visualizes portfolio evolution based on sentiment (Strategy A) and regression predictions (Strategy B). Regression applies only to Tesla and Microsoft."
|
|
|
|
|
|
|
|
|
|
| 127 |
)
|
| 128 |
|
| 129 |
demo.launch()
|