SelmaNajih001 commited on
Commit
c47f1a1
·
verified ·
1 Parent(s): 13a3392

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -19
app.py CHANGED
@@ -45,7 +45,7 @@ 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]
@@ -54,7 +54,7 @@ for i, row in df_multi.iterrows():
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:
@@ -75,8 +75,10 @@ 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 ---
@@ -84,7 +86,7 @@ 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
@@ -92,15 +94,16 @@ for company in companies:
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 ---
@@ -114,16 +117,34 @@ fig_strategy_B = px.line(df_plot_B, x='Data', y='StrategyB_Cumulative', color='C
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()
 
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]
 
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:
 
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
+ # Flatten the columns to a single level
79
+ df_prices.columns = ['_'.join(col).strip() if isinstance(col, tuple) else col for col in df_prices.columns]
80
+ df_prices['date_merge'] = pd.to_datetime(df_prices['Date_']).dt.normalize()
81
+ df_prices['PctChangeDaily'] = df_prices[f'Close_{ticker}'].pct_change().shift(-1)
82
  prices[company] = df_prices
83
 
84
  # --- MERGE & CALCULATE STRATEGIES ---
 
86
  for company in companies:
87
  df_c = df_multi[df_multi['Company']==company].copy()
88
  df_c = pd.merge(df_c, prices[company], on='date_merge', how='inner')
89
+
90
  # Strategy A: Sentiment
91
  df_c['StrategyA_Daily'] = 0
92
  df_c['StrategyA_Cumulative'] = 0
 
94
  score = df_c.loc[i,'Confidence']
95
  pct = df_c.loc[i,'PctChangeDaily'] if pd.notnull(df_c.loc[i,'PctChangeDaily']) else 0
96
  if df_c.loc[i,'Sentiment']=="UP" and score>0.8:
97
+ df_c.loc[i,'StrategyA_Daily'] = df_c.loc[i,f'Close_{TICKERS[company]}']*pct
98
  elif df_c.loc[i,'Sentiment']=="DOWN" and score>0.8:
99
+ df_c.loc[i,'StrategyA_Daily'] = df_c.loc[i,f'Close_{TICKERS[company]}']*pct*-1
100
  df_c.loc[i,'StrategyA_Cumulative'] = df_c.loc[i-1,'StrategyA_Cumulative'] + df_c.loc[i,'StrategyA_Daily']
101
+
102
+
103
  # Strategy B: Regression (only Tesla & Microsoft)
104
+ df_c['StrategyB_Daily'] = df_c['Predicted']*df_c['PctChangeDaily']*df_c[f'Close_{TICKERS[company]}']
105
  df_c['StrategyB_Cumulative'] = df_c['StrategyB_Daily'].cumsum()
106
+
107
  dfs_final[company] = df_c
108
 
109
  # --- PLOT STRATEGIES ---
 
117
  title="Portfolio Evolution Following Strategy B (Regression)",
118
  labels={'StrategyB_Cumulative':'Cumulative Value','Data':'Date'})
119
 
120
+ # --- FUNCTION FOR GRADIO ---
121
+ def show_company_data(selected_companies):
122
+ if not selected_companies:
123
+ return "Select at least one company to visualize.", None, None
124
+
125
+ # DataFrames
126
+ tables = [dfs_final[c].head(10) for c in selected_companies if c in dfs_final]
127
+
128
+ # Strategy plots
129
+ df_plot_A = pd.concat([dfs_final[c][['Data','StrategyA_Cumulative']].assign(Company=c) for c in selected_companies if c in dfs_final], ignore_index=True)
130
+ df_plot_B = pd.concat([dfs_final[c][['Data','StrategyB_Cumulative']].assign(Company=c) for c in selected_companies if c in dfs_final], ignore_index=True)
131
+
132
+ fig_A = px.line(df_plot_A, x='Data', y='StrategyA_Cumulative', color='Company', title="Portfolio Evolution - Strategy A (Sentiment)")
133
+ fig_B = px.line(df_plot_B, x='Data', y='StrategyB_Cumulative', color='Company', title="Portfolio Evolution - Strategy B (Regression)")
134
+
135
+ return tables, fig_A, fig_B
136
 
137
+ # --- GRADIO INTERFACE ---
138
  demo = gr.Interface(
139
+ fn=show_company_data,
140
+ inputs=[gr.CheckboxGroup(choices=companies, label="Select Companies")],
141
+ outputs=[
142
+ gr.Dataframe(label="Top 10 Rows per Company", type="pandas"),
143
+ gr.Plot(label="Strategy A: Sentiment"),
144
+ gr.Plot(label="Strategy B: Regression")
145
+ ],
146
+ title="Interactive Portfolio Evolution",
147
+ description="Select one or more companies to visualize portfolio evolution based on Strategy A (Sentiment) and Strategy B (Regression). Regression applies only to Tesla and Microsoft."
148
  )
149
 
150
+ demo.launch()