Nazhar commited on
Commit
bc370a0
·
verified ·
1 Parent(s): 9069248

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +427 -116
app.py CHANGED
@@ -3,146 +3,173 @@ import pandas as pd
3
  import plotly.express as px
4
  import plotly.graph_objects as go
5
  from plotly.subplots import make_subplots
 
 
 
6
 
7
- default_start_date = pd.to_datetime('2020-11-02')
8
- date_limit = pd.to_datetime('2021-08-12')
9
 
10
- st.title("Stock Analysis Dashboard")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
 
 
 
 
 
 
 
 
 
 
 
12
  # Load data
13
  data_file_path = r"technicalRecommendation.csv" # Update this with your file path
14
  data = pd.read_csv(data_file_path)
 
15
  # Convert 'Date' column to datetime format
16
  data['Date'] = pd.to_datetime(data['Date'])
17
- print(data.shape, data.columns)
18
- market_analysis, news_analysis, trade_recs = st.tabs(["Market Analysis", "News Analysis", "Trading Recommendations"])
 
 
 
 
 
 
19
 
20
  with market_analysis:
21
  st.header("Market Analysis")
22
- start_date = st.sidebar.date_input('Start Date', value=default_start_date, min_value=data['Date'].min(), max_value=date_limit)
23
- end_date = st.sidebar.date_input("End Date", value=date_limit, min_value=data['Date'].min(), max_value=date_limit)
 
 
 
 
24
  start_date = pd.to_datetime(start_date)
25
  end_date = pd.to_datetime(end_date)
26
  data2 = data[data['Date'].between(start_date, end_date)]
27
 
28
  # Dropdown for selecting the indicator
29
- selected_indicator = st.sidebar.selectbox("Select an Indicator", ['EMA 9', 'EMA 55', 'MACD', 'RSI'])
30
  # Dropdown for selecting the Number of Signal Days
31
- num_signals = st.sidebar.selectbox("Signals to Show", ['None', 'All', 'Last 5 Days', 'Last 15 Days', 'Last 20 Days'])
32
 
33
  if selected_indicator == 'EMA 9':
34
  # Plot close price and EMA 9
35
  fig = px.line(data2, x='Date', y=['Close_price', 'EMA_9'], title='Close Price vs EMA 9',
36
  labels={'Date': 'Date', 'value': 'Price', 'variable': 'Type'})
37
  fig.update_traces(selector=dict(type='scatter'))
38
- ema9_signal = 'EMA9_Signal'
39
  # Plot ‘strong buy’ signals
40
  if num_signals != 'None':
41
- if num_signals == 'All':
42
- strong_buy_dates = data2[data2[ema9_signal] == 3.0]
43
- elif num_signals == 'Last 5 Days':
44
- last5 = data2.tail(5)
45
- strong_buy_dates = last5[last5[ema9_signal] == 3.0]
46
- elif num_signals == 'Last 15 Days':
47
- last15 = data2.tail(15)
48
- strong_buy_dates = last15[last15[ema9_signal] == 3.0]
49
- elif num_signals == 'Last 20 Days':
50
- last20 = data2.tail(20)
51
- strong_buy_dates = last20[last20[ema9_signal] == 3.0]
52
-
53
- fig.add_scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['EMA_9'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong buy')
54
-
55
- # Plot ‘strong sell’ signals
56
- if num_signals != 'None':
57
- if num_signals == 'All':
58
- strong_sell_dates = data2[data2[ema9_signal] == -3.0]
59
- elif num_signals == 'Last 5 Days':
60
- last5 = data2.tail(5)
61
- strong_sell_dates = last5[last5[ema9_signal] == -3.0]
62
- elif num_signals == 'Last 15 Days':
63
- last15 = data2.tail(15)
64
- strong_sell_dates = last15[last15[ema9_signal] == -3.0]
65
- elif num_signals == 'Last 20 Days':
66
- last20 = data2.tail(20)
67
- strong_sell_dates = last20[last20[ema9_signal] == -3.0]
68
 
 
69
  fig.add_scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['EMA_9'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong sell')
70
-
 
 
 
 
 
 
 
 
 
 
 
71
  st.plotly_chart(fig)
72
 
73
  elif selected_indicator == 'EMA 55':
74
  # Plot close price and EMA 9
75
- fig = px.line(data2, x='Date', y=['Close_price', 'EMA_55'], title='Close Price vs EMA 9',
76
  labels={'Date': 'Date', 'value': 'Price', 'variable': 'Type'})
77
  fig.update_traces(selector=dict(type='scatter'))
78
- ema55_signal = 'EMA55_Signal'
79
  # Plot ‘strong buy’ signals
80
  if num_signals != 'None':
81
- if num_signals == 'All':
82
- strong_buy_dates = data2[data2[ema55_signal] == 3.0]
83
- elif num_signals == 'Last 5 Days':
84
- last5 = data2.tail(5)
85
- strong_buy_dates = last5[last5[ema55_signal] == 3.0]
86
- elif num_signals == 'Last 15 Days':
87
- last15 = data2.tail(15)
88
- strong_buy_dates = last15[last15[ema55_signal] == 3.0]
89
- elif num_signals == 'Last 20 Days':
90
- last20 = data2.tail(20)
91
- strong_buy_dates = last20[last20[ema55_signal] == 3.0]
92
 
93
  fig.add_scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['EMA_55'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong buy')
94
-
95
- # Plot ‘strong sell’ signals
96
- if num_signals != 'None':
97
- if num_signals == 'All':
98
- strong_sell_dates = data2[data2[ema55_signal] == -3.0]
99
- elif num_signals == 'Last 5 Days':
100
- last5 = data2.tail(5)
101
- strong_sell_dates = last5[last5[ema55_signal] == -3.0]
102
- elif num_signals == 'Last 15 Days':
103
- last15 = data2.tail(15)
104
- strong_sell_dates = last15[last15[ema55_signal] == -3.0]
105
- elif num_signals == 'Last 20 Days':
106
- last20 = data2.tail(20)
107
- strong_sell_dates = last20[last20[ema55_signal] == -3.0]
108
-
109
  fig.add_scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['EMA_55'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong sell')
110
-
 
 
 
 
 
 
 
 
 
 
 
111
  st.plotly_chart(fig)
112
 
113
  elif selected_indicator == 'MACD':
114
  # Set up the figure and subplots
115
- macd_signal = 'MACD_Signals'
116
-
117
  fig = make_subplots(rows=2, cols=1)
118
  # fig = go.Figure()
119
  # Add subplot for Close Price and Signals
120
  fig.add_trace(go.Scatter(x=data2['Date'], y=data2['Close_price'], mode='lines', name='Close Price'),
121
  row=1, col=1)
122
  if num_signals != 'None':
123
- if num_signals == 'All':
124
- strong_buy_dates = data2[data2[macd_signal] == 3.0]
125
- strong_sell_dates = data2[data2[macd_signal] == -3.0]
126
- strong_hold_dates = data2[data2[macd_signal] == 0]
127
- elif num_signals == 'Last 5 Days':
128
- last5 = data2.tail(5)
129
- strong_buy_dates = last5[last5[macd_signal] == 3.0]
130
- strong_sell_dates = last5[last5[macd_signal] == -3.0]
131
- strong_hold_dates = last5[last5[macd_signal] == 0]
132
- elif num_signals == 'Last 15 Days':
133
- last15 = data2.tail(15)
134
- strong_buy_dates = last15[last15[macd_signal] == 3.0]
135
- strong_sell_dates = last15[last15[macd_signal] == -3.0]
136
- strong_hold_dates = last15[last15[macd_signal] == 0]
137
- elif num_signals == 'Last 20 Days':
138
- last20 = data2.tail(20)
139
- strong_buy_dates = last20[last20[macd_signal] == 3.0]
140
- strong_sell_dates = last20[last20[macd_signal] == -3.0]
141
- strong_hold_dates = last20[last20[macd_signal] == 0]
142
-
143
  fig.add_trace(go.Scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['Close_price'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong Buy'), row=1, col=1)
144
  fig.add_trace(go.Scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['Close_price'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong Sell'), row=1, col=1)
145
- fig.add_trace(go.Scatter(x=strong_hold_dates['Date'], y=strong_hold_dates['Close_price'], mode='markers', marker=dict(symbol='circle', size=10, color='orange'), name='Strong Sell'), row=1, col=1)
146
 
147
  # Add subplot for MACD
148
  # fig2 = go.Figure()
@@ -156,6 +183,18 @@ with market_analysis:
156
  # yaxis=dict(title='Close Price', side='left', showgrid=False),
157
  # yaxis2=dict(title='MACD', side='right', overlaying='y', showgrid=False))
158
  fig.update_layout(title='MACD Analysis')
 
 
 
 
 
 
 
 
 
 
 
 
159
  st.plotly_chart(fig, use_container_width=True)
160
  # st.plotly_chart(fig2, use_container_width=True)
161
 
@@ -167,45 +206,317 @@ with market_analysis:
167
  fig.add_trace(go.Scatter(x=data2['Date'], y=data2['RSI'], mode='lines', name='RSI'))
168
 
169
  # Add overbought and oversold lines
170
- overbought_strong = 70
171
- oversold_strong = 30
172
  fig.add_shape(type="line", x0=data2['Date'].min(), y0=overbought_strong, x1=data2['Date'].max(), y1=overbought_strong, line=dict(color="red", width=1, dash="dash"), name="Overbought")
173
  fig.add_shape(type="line", x0=data2['Date'].min(), y0=oversold_strong, x1=data2['Date'].max(), y1=oversold_strong, line=dict(color="green", width=1, dash="dash"), name="Oversold")
174
 
175
- rsi_signal = 'RSI_Signals'
176
  if num_signals != 'None':
177
- if num_signals == 'All':
178
- strong_buy_dates = data2[data2[rsi_signal] >= 1.0]
179
- strong_sell_dates = data2[data2[rsi_signal] <= -1.0]
180
- strong_hold_dates = data2[data2[rsi_signal] == 0]
181
- elif num_signals == 'Last 5 Days':
182
- last5 = data2.tail(5)
183
- strong_buy_dates = last5[last5[rsi_signal] >= 1.0]
184
- strong_sell_dates = last5[last5[rsi_signal] <= -1.0]
185
- strong_hold_dates = last5[last5[rsi_signal] == 0]
186
- elif num_signals == 'Last 15 Days':
187
- last15 = data2.tail(15)
188
- strong_buy_dates = last15[last15[rsi_signal] >= 1.0]
189
- strong_sell_dates = last15[last15[rsi_signal] <= -1.0]
190
- strong_hold_dates = last15[last15[rsi_signal] == 0]
191
- elif num_signals == 'Last 20 Days':
192
- last20 = data2.tail(20)
193
- strong_buy_dates = last20[last20[rsi_signal] >= 1.0]
194
- strong_sell_dates = last20[last20[rsi_signal] <= -1.0]
195
- strong_hold_dates = last20[last20[rsi_signal] == 0]
196
-
197
  fig.add_trace(go.Scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['RSI'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong Buy'))
198
  fig.add_trace(go.Scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['RSI'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong Sell'))
199
- fig.add_trace(go.Scatter(x=strong_hold_dates['Date'], y=strong_hold_dates['RSI'], mode='markers', marker=dict(symbol='circle', size=10, color='orange'), name='Strong Sell'))
200
 
201
  fig.update_layout(title='RSI Analysis')
 
 
 
 
 
 
 
 
 
 
 
 
202
  st.plotly_chart(fig)
203
  # st.write(data2)
204
 
205
  with news_analysis:
206
  st.header("News Analysis")
207
- st.write('data to be added.')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  with trade_recs:
210
  st.header("Trading Recommendations")
211
- st.write('recommendations to be added.')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import plotly.express as px
4
  import plotly.graph_objects as go
5
  from plotly.subplots import make_subplots
6
+ import numpy as np
7
+ import ast
8
+ from pagination import paginator
9
 
 
 
10
 
11
+ # Utils Functions
12
+ def signals_to_plot(selected_indicator, num_signals, signal_column, data):
13
+ if selected_indicator != 'RSI':
14
+ if num_signals == 'All':
15
+ buy_dates = data[data[signal_column] == 3.0]
16
+ sell_dates = data[data[signal_column] == -3.0]
17
+ hold_dates = data[data[signal_column] == 0]
18
+ elif num_signals == 'Last 5 Days':
19
+ last5 = data.tail(5)
20
+ buy_dates = last5[last5[signal_column] == 3.0]
21
+ sell_dates = last5[last5[signal_column] == -3.0]
22
+ hold_dates = last5[last5[signal_column] == 0]
23
+ elif num_signals == 'Last 15 Days':
24
+ last15 = data.tail(15)
25
+ buy_dates = last15[last15[signal_column] == 3.0]
26
+ sell_dates = last15[last15[signal_column] == -3.0]
27
+ hold_dates = last15[last15[signal_column] == 0]
28
+ elif num_signals == 'Last 20 Days':
29
+ last20 = data.tail(20)
30
+ buy_dates = last20[last20[signal_column] == 3.0]
31
+ sell_dates = last20[last20[signal_column] == -3.0]
32
+ hold_dates = last20[last20[signal_column] == 0]
33
+
34
+ elif selected_indicator == 'RSI':
35
+ if num_signals == 'All':
36
+ buy_dates = data[data[signal_column] >= 1.0]
37
+ sell_dates = data[data[signal_column] <= -1.0]
38
+ hold_dates = data[data[signal_column] == 0]
39
+ elif num_signals == 'Last 5 Days':
40
+ last5 = data.tail(5)
41
+ buy_dates = last5[last5[signal_column] >= 1.0]
42
+ sell_dates = last5[last5[signal_column] <= -1.0]
43
+ hold_dates = last5[last5[signal_column] == 0]
44
+ elif num_signals == 'Last 15 Days':
45
+ last15 = data.tail(15)
46
+ buy_dates = last15[last15[signal_column] >= 1.0]
47
+ sell_dates = last15[last15[signal_column] <= -1.0]
48
+ hold_dates = last15[last15[signal_column] == 0]
49
+ elif num_signals == 'Last 20 Days':
50
+ last20 = data.tail(20)
51
+ buy_dates = last20[last20[signal_column] >= 1.0]
52
+ sell_dates = last20[last20[signal_column] <= -1.0]
53
+ hold_dates = last20[last20[signal_column] == 0]
54
+ return buy_dates, sell_dates, hold_dates
55
 
56
+ def convert_str_to_list(string):
57
+ try:
58
+ # Use ast.literal_eval to safely evaluate the string as a list
59
+ return ast.literal_eval(string)
60
+ except (ValueError, SyntaxError):
61
+ # If the string cannot be converted to a list, return it as is
62
+ return string
63
+
64
+
65
+
66
+ st.title("Stock Analysis Dashboard")
67
  # Load data
68
  data_file_path = r"technicalRecommendation.csv" # Update this with your file path
69
  data = pd.read_csv(data_file_path)
70
+
71
  # Convert 'Date' column to datetime format
72
  data['Date'] = pd.to_datetime(data['Date'])
73
+ # print(data.shape, data.columns)
74
+
75
+ default_start_date = data['Date'].min() # Set default start date for the start date picker
76
+ date_limit = pd.to_datetime('2021-08-12') # Set date limit for end date picker
77
+
78
+
79
+ # Create Tabs
80
+ market_analysis, news_analysis, trade_recs, chat = st.tabs(["Market Analysis", "News Analysis", "Trading Recommendations", "Gup Shup"])
81
 
82
  with market_analysis:
83
  st.header("Market Analysis")
84
+ date_container = st.container(height = 90, border=False)
85
+ # main_container.write(f"Date: {date}")
86
+
87
+ col1, col2 = date_container.columns([0.5, 0.5], gap='medium')
88
+ start_date = col1.date_input('Start Date', value=default_start_date, min_value=data['Date'].min(), max_value=date_limit)
89
+ end_date = col2.date_input("End Date", value=date_limit, min_value=data['Date'].min(), max_value=date_limit)
90
  start_date = pd.to_datetime(start_date)
91
  end_date = pd.to_datetime(end_date)
92
  data2 = data[data['Date'].between(start_date, end_date)]
93
 
94
  # Dropdown for selecting the indicator
95
+ selected_indicator = st.selectbox("Select an Indicator", ['EMA 9', 'EMA 55', 'MACD', 'RSI'])
96
  # Dropdown for selecting the Number of Signal Days
97
+ num_signals = st.selectbox("Signals to Show", ['None', 'All', 'Last 5 Days', 'Last 15 Days', 'Last 20 Days'])
98
 
99
  if selected_indicator == 'EMA 9':
100
  # Plot close price and EMA 9
101
  fig = px.line(data2, x='Date', y=['Close_price', 'EMA_9'], title='Close Price vs EMA 9',
102
  labels={'Date': 'Date', 'value': 'Price', 'variable': 'Type'})
103
  fig.update_traces(selector=dict(type='scatter'))
 
104
  # Plot ‘strong buy’ signals
105
  if num_signals != 'None':
106
+ strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
107
+ selected_indicator=selected_indicator,
108
+ num_signals=num_signals,
109
+ signal_column='EMA9_Signal',
110
+ data=data2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
+ fig.add_scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['EMA_9'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong buy')
113
  fig.add_scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['EMA_9'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong sell')
114
+ fig.update_xaxes(
115
+ rangeslider_visible=True,
116
+ rangeselector=dict(
117
+ buttons=list([
118
+ dict(count=1, label="1m", step="month", stepmode="backward"),
119
+ dict(count=6, label="6m", step="month", stepmode="backward"),
120
+ dict(count=1, label="YTD", step="year", stepmode="todate"),
121
+ dict(count=1, label="1y", step="year", stepmode="backward"),
122
+ dict(step="all")
123
+ ])
124
+ )
125
+ )
126
  st.plotly_chart(fig)
127
 
128
  elif selected_indicator == 'EMA 55':
129
  # Plot close price and EMA 9
130
+ fig = px.line(data2, x='Date', y=['Close_price', 'EMA_55'], title='Close Price vs EMA 55',
131
  labels={'Date': 'Date', 'value': 'Price', 'variable': 'Type'})
132
  fig.update_traces(selector=dict(type='scatter'))
 
133
  # Plot ‘strong buy’ signals
134
  if num_signals != 'None':
135
+ strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
136
+ selected_indicator=selected_indicator,
137
+ num_signals=num_signals,
138
+ signal_column='EMA55_Signal',
139
+ data=data2)
 
 
 
 
 
 
140
 
141
  fig.add_scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['EMA_55'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong buy')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  fig.add_scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['EMA_55'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong sell')
143
+ fig.update_xaxes(
144
+ rangeslider_visible=True,
145
+ rangeselector=dict(
146
+ buttons=list([
147
+ dict(count=1, label="1m", step="month", stepmode="backward"),
148
+ dict(count=6, label="6m", step="month", stepmode="backward"),
149
+ dict(count=1, label="YTD", step="year", stepmode="todate"),
150
+ dict(count=1, label="1y", step="year", stepmode="backward"),
151
+ dict(step="all")
152
+ ])
153
+ )
154
+ )
155
  st.plotly_chart(fig)
156
 
157
  elif selected_indicator == 'MACD':
158
  # Set up the figure and subplots
 
 
159
  fig = make_subplots(rows=2, cols=1)
160
  # fig = go.Figure()
161
  # Add subplot for Close Price and Signals
162
  fig.add_trace(go.Scatter(x=data2['Date'], y=data2['Close_price'], mode='lines', name='Close Price'),
163
  row=1, col=1)
164
  if num_signals != 'None':
165
+ strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
166
+ selected_indicator=selected_indicator,
167
+ num_signals=num_signals,
168
+ signal_column='MACD_Signals',
169
+ data=data2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  fig.add_trace(go.Scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['Close_price'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong Buy'), row=1, col=1)
171
  fig.add_trace(go.Scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['Close_price'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong Sell'), row=1, col=1)
172
+ fig.add_trace(go.Scatter(x=strong_hold_dates['Date'], y=strong_hold_dates['Close_price'], mode='markers', marker=dict(symbol='circle', size=10, color='orange'), name='Hold'), row=1, col=1)
173
 
174
  # Add subplot for MACD
175
  # fig2 = go.Figure()
 
183
  # yaxis=dict(title='Close Price', side='left', showgrid=False),
184
  # yaxis2=dict(title='MACD', side='right', overlaying='y', showgrid=False))
185
  fig.update_layout(title='MACD Analysis')
186
+ fig.update_xaxes(
187
+ rangeslider_visible=False,
188
+ rangeselector=dict(
189
+ buttons=list([
190
+ dict(count=1, label="1m", step="month", stepmode="backward"),
191
+ dict(count=6, label="6m", step="month", stepmode="backward"),
192
+ dict(count=1, label="YTD", step="year", stepmode="todate"),
193
+ dict(count=1, label="1y", step="year", stepmode="backward"),
194
+ dict(step="all")
195
+ ])
196
+ )
197
+ )
198
  st.plotly_chart(fig, use_container_width=True)
199
  # st.plotly_chart(fig2, use_container_width=True)
200
 
 
206
  fig.add_trace(go.Scatter(x=data2['Date'], y=data2['RSI'], mode='lines', name='RSI'))
207
 
208
  # Add overbought and oversold lines
209
+ overbought_strong = 79
210
+ oversold_strong = 22
211
  fig.add_shape(type="line", x0=data2['Date'].min(), y0=overbought_strong, x1=data2['Date'].max(), y1=overbought_strong, line=dict(color="red", width=1, dash="dash"), name="Overbought")
212
  fig.add_shape(type="line", x0=data2['Date'].min(), y0=oversold_strong, x1=data2['Date'].max(), y1=oversold_strong, line=dict(color="green", width=1, dash="dash"), name="Oversold")
213
 
 
214
  if num_signals != 'None':
215
+ strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
216
+ selected_indicator=selected_indicator,
217
+ num_signals=num_signals,
218
+ signal_column='RSI_Signals',
219
+ data=data2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  fig.add_trace(go.Scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['RSI'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong Buy'))
221
  fig.add_trace(go.Scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['RSI'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong Sell'))
222
+ # fig.add_trace(go.Scatter(x=strong_hold_dates['Date'], y=strong_hold_dates['RSI'], mode='markers', marker=dict(symbol='circle', size=10, color='orange'), name='Hold'))
223
 
224
  fig.update_layout(title='RSI Analysis')
225
+ fig.update_xaxes(
226
+ rangeslider_visible=True,
227
+ rangeselector=dict(
228
+ buttons=list([
229
+ dict(count=1, label="1m", step="month", stepmode="backward"),
230
+ dict(count=6, label="6m", step="month", stepmode="backward"),
231
+ dict(count=1, label="YTD", step="year", stepmode="todate"),
232
+ dict(count=1, label="1y", step="year", stepmode="backward"),
233
+ dict(step="all")
234
+ ])
235
+ )
236
+ )
237
  st.plotly_chart(fig)
238
  # st.write(data2)
239
 
240
  with news_analysis:
241
  st.header("News Analysis")
242
+ st.write('Date, event impact, close price, headline or Bold_KW.')
243
+ # Load data
244
+ data_file_path = r"Events_SameDay.csv" # Update this with your file path
245
+ events = pd.read_csv(data_file_path)
246
+
247
+ # Convert 'Date' column to datetime format
248
+ events['Date'] = pd.to_datetime(events['Date'])
249
+ print(events.shape, events.columns)
250
+
251
+ default_start_date = events['Date'].min() # Set default start date for the start date picker
252
+ date_limit = pd.to_datetime('2021-08-12') # Set date limit for end date picker
253
+
254
+ # Add a new column for positive values of column A
255
+ events['Positive_Impacts'] = events[events['Events_Impact'] > 0]['Events_Impact']
256
+
257
+ # Add a new column for negative values of column A
258
+ events['Negative_Impacts'] = events[events['Events_Impact'] < 0]['Events_Impact']
259
 
260
+ # Fill NaN values in the new columns with 0
261
+ events['Positive_Impacts'].fillna("", inplace=True)
262
+ events['Negative_Impacts'].fillna("", inplace=True)
263
+ # Create the line trace for stock prices
264
+ line_stock = go.Scatter(x=events['Date'], y=events['Price'], mode='lines', name='OGDCL Close Price',
265
+ line=dict(dash='solid', color='royalblue', width=2),
266
+ # text=events['Cleaned_Headline'],
267
+ # hovertext=events['FeatureSentiment'],
268
+ customdata=events['Feature'],
269
+ hovertemplate='%{x}<br>Close: %{y}<br>Feature: %{customdata}<br>',
270
+ # hoverlabel=dict(font=dict(color=events
271
+ # ['FeatureSentiment'].apply(lambda x: 'red' if x == 'Negative' else 'blue' if x == 'Neutral' else 'green'))), # Customize the line style, color, and width
272
+ )
273
+ # Create dummy traces for the legend
274
+ dummy_positive = go.Scatter(x=[None], y=[None], mode='lines', name='Positive Impacts',
275
+ marker=dict(color='black', size=15), showlegend=True,
276
+ # visible='legendonly'
277
+ )
278
+ dummy_negative = go.Scatter(x=[None], y=[None], mode='lines', name='Negative Impacts',
279
+ marker=dict(color='red', size=15), showlegend=True,
280
+ # visible='legendonly'
281
+ )
282
+
283
+ fontsize = 12
284
+ annotations = []
285
+ # Create annotations for the Positive points
286
+ for index, row in events.iterrows():
287
+ annotation1 = dict(x=row['Date'], y=row['Price'], text = row['Positive_Impacts'],
288
+ showarrow=True, arrowhead=0, # arrowcolor='black',
289
+ ax=10, ay=-20, # Dynamic offset
290
+ font=dict(size=fontsize, color='green'),
291
+ )
292
+ annotations.append(annotation1)
293
+
294
+ # Create annotations for the Negative points
295
+ for index, row in events.iterrows():
296
+ annotation2 = dict(x=row['Date'], y=row['Price'], text = row['Negative_Impacts'],
297
+ showarrow=True, arrowhead=0, arrowcolor='blue',
298
+ ax=10, ay=-20, # Dynamic offset
299
+ font=dict(size=fontsize, color='red'),
300
+ )
301
+ annotations.append(annotation2)
302
+
303
+ # Create the layout
304
+ title = 'OGDCL Close Price w.r.t. News Impacts'
305
+ layout = go.Layout(
306
+ title=title,
307
+ xaxis=dict(
308
+ title='Date',
309
+ tickformat='%b %d, %Y',
310
+ # gridcolor='lightgray',
311
+ range=[start_date, end_date],
312
+ # tickvals=list(range(dateA, dateB, 3)),
313
+ ),
314
+ yaxis=dict(
315
+ title='OGDCL Close Price',
316
+ # gridcolor='lightgray',
317
+ range=[90, 120],
318
+ tickvals=list(range(90, 120, 5)),
319
+ ),
320
+ # plot_bgcolor='rgba(245, 245, 245, 0.8)',
321
+ # paper_bgcolor='white',
322
+ # hoverlabel=dict(
323
+ # bgcolor='white',
324
+ # font=dict(color='black'),
325
+ # ),
326
+ annotations=annotations,
327
+ )
328
+
329
+ # Add all traces to the figure
330
+ figure = go.Figure(data=[line_stock, dummy_negative, dummy_positive], layout=layout)
331
+
332
+ figure.update_layout(
333
+ title={
334
+ 'text': title,
335
+ 'x': 0.5,
336
+ 'y': 0.95,
337
+ 'xanchor': 'center',
338
+ 'yanchor': 'top',
339
+ 'font': dict(size=12),
340
+ },
341
+ hovermode='closest',
342
+ margin=dict(l=40, r=40, t=80, b=40),
343
+ )
344
+ figure.update_xaxes(
345
+ rangeslider_visible=True,
346
+ rangeselector=dict(
347
+ buttons=list([
348
+ dict(count=1, label="1m", step="month", stepmode="backward"),
349
+ dict(count=6, label="6m", step="month", stepmode="backward"),
350
+ dict(count=1, label="YTD", step="year", stepmode="todate"),
351
+ dict(count=1, label="1y", step="year", stepmode="backward"),
352
+ dict(step="all")
353
+ ])
354
+ )
355
+ )
356
+ st.plotly_chart(figure)
357
+
358
+ # news = events[events['Date'].between(start_date, end_date, inclusive='both')]
359
+ news = events[(events['Date'] >= start_date) & (events['Date'] <= end_date)]
360
+ print(news[news['Date']==start_date])
361
+ news = news[['Date', 'Raw_Headline', 'Bold_KW', 'Feature', 'Raw_News', 'Sources', 'Urls']]
362
+ cols = ['Raw_Headline', 'Bold_KW', 'Feature', 'Raw_News', 'Sources', 'Urls']
363
+ for col in cols:
364
+ news[col] = news[col].apply(convert_str_to_list)
365
+ # Extract only the date part
366
+ news['Date'] = news['Date'].dt.date
367
+ st.subheader("News Events")
368
+ # st.dataframe(news, hide_index=True)
369
+ # st.table(news)
370
+ dates = list(news['Date'].unique())
371
+ dates = np.sort(dates)
372
+ print(dates, len(dates))
373
+ num_dates = len(dates)
374
+ items_per_page = min(num_dates, 5)
375
+ for i, date in paginator("Select Page Number", dates, items_per_page=items_per_page, on_sidebar=False):
376
+ st.write(f'<span style="font-size: large;"><b>Date:</b> <u>{date}</u></span>', unsafe_allow_html=True)
377
+
378
+
379
+ filtered_news = news[news['Date'] == date]
380
+ print(filtered_news.shape)
381
+ features = filtered_news['Feature'].sum()
382
+ headlines = filtered_news['Raw_Headline'].sum()
383
+ news_list = filtered_news['Raw_News'].sum()
384
+ sources = filtered_news['Sources'].sum()
385
+ urls = filtered_news['Urls'].sum()
386
+
387
+ main_container = st.container(height = 250, border=True)
388
+ # main_container.write(f"Date: {date}")
389
+
390
+ col1, col2 = main_container.columns([0.7, 0.3], gap='medium')
391
+
392
+ # Merge lists of headlines into a single list
393
+ for index, headline in enumerate(headlines):
394
+ col1.page_link(urls[index], label=f"**:blue[{headline}]**")
395
+ # col1.write(f"<span style='font-size: large;'><b><u>{headline}</u></b></span>", unsafe_allow_html=True)
396
+ col1.write(f"<span style='font-size: small;'>By {sources[index]}</span><br>", unsafe_allow_html=True)
397
+ with col1:
398
+ with st.expander("Show Full Article"):
399
+ st.write(news_list[index])
400
+
401
+ with col2:
402
+ # st.divider()
403
+ with st.expander("Oil Sector Features"):
404
+ st.write(set(features))
405
+
406
+
407
+
408
  with trade_recs:
409
  st.header("Trading Recommendations")
410
+ line_color = 'blue'
411
+ # Create the line trace for stock prices
412
+ # Dropdown for selecting the indicator
413
+ selected_indicator = st.selectbox("Indicator to Show", ['EMA 9', 'EMA 55', 'MACD', 'RSI'])
414
+ if selected_indicator == 'EMA 9':
415
+ column = 'EMA9_Signal'
416
+ hover_text = '%{x}<br>Close: %{y}<br> EMA9_Signal: %{customdata}<br>'
417
+ elif selected_indicator == 'EMA 55':
418
+ column = 'EMA55_Signal'
419
+ hover_text = '%{x}<br>Close: %{y}<br> EMA55_Signal: %{customdata}<br>'
420
+ elif selected_indicator == 'MACD':
421
+ column = 'MACD_Signals'
422
+ hover_text = '%{x}<br>Close: %{y}<br> MACD_Signal: %{customdata}<br>'
423
+ elif selected_indicator == 'RSI':
424
+ column = 'RSI_Signals'
425
+ hover_text = '%{x}<br>Close: %{y}<br> RSI_Signal: %{customdata}<br>'
426
+ line_stock = go.Scatter(x=events['Date'], y=events['Price'], mode='lines', name='OGDCL Close Price',
427
+ line=dict(dash='solid',color=line_color, width=2), # color='royalblue'
428
+ text=[column],
429
+ # hovertext=events['FeatureSentiment'],
430
+ customdata=events[column],
431
+ hovertemplate=hover_text,
432
+ # hoverlabel=dict(font=dict(color=events
433
+ # ['FeatureSentiment'].apply(lambda x: 'red' if x == 'Negative' else 'blue' if x == 'Neutral' else 'green'))), # Customize the line style, color, and width
434
+ )
435
+ # Create dummy traces for the legend
436
+ dummy_positive = go.Scatter(x=[None], y=[None], mode='lines', name='Positive Impacts',
437
+ marker=dict(color='black', size=15), showlegend=True,
438
+ # visible='legendonly'
439
+ )
440
+ dummy_negative = go.Scatter(x=[None], y=[None], mode='lines', name='Negative Impacts',
441
+ marker=dict(color='red', size=15), showlegend=True,
442
+ # visible='legendonly'
443
+ )
444
+
445
+ fontsize = 12
446
+ annotations = []
447
+ # Create annotations for the Positive points
448
+ for index, row in events.iterrows():
449
+ annotation1 = dict(x=row['Date'], y=row['Price'], text = row['Positive_Impacts'],
450
+ showarrow=True, arrowhead=0, # arrowcolor='black',
451
+ ax=10, ay=-20, # Dynamic offset
452
+ font=dict(size=fontsize, color='green'),
453
+ )
454
+ annotations.append(annotation1)
455
+
456
+ # Create annotations for the Negative points
457
+ for index, row in events.iterrows():
458
+ annotation2 = dict(x=row['Date'], y=row['Price'], text = row['Negative_Impacts'],
459
+ showarrow=True, arrowhead=0, arrowcolor=line_color,
460
+ ax=10, ay=-20, # Dynamic offset
461
+ font=dict(size=fontsize, color='red'),
462
+ )
463
+ annotations.append(annotation2)
464
+
465
+ # Create the layout
466
+ title = 'OGDCL Close Price w.r.t. News Impacts'
467
+ layout = go.Layout(
468
+ title=title,
469
+ xaxis=dict(
470
+ title='Date',
471
+ tickformat='%b %d, %Y',
472
+ # gridcolor='lightgray',
473
+ range=[start_date, end_date],
474
+ # tickvals=list(range(dateA, dateB, 3)),
475
+ ),
476
+ yaxis=dict(
477
+ title='OGDCL Close Price',
478
+ # gridcolor='lightgray',
479
+ range=[90, 120],
480
+ tickvals=list(range(90, 120, 5)),
481
+ ),
482
+ # plot_bgcolor='rgba(245, 245, 245, 0.8)',
483
+ # paper_bgcolor='white',
484
+ # hoverlabel=dict(
485
+ # bgcolor='white',
486
+ # font=dict(color='black'),
487
+ # ),
488
+ annotations=annotations,
489
+ )
490
+
491
+ # Add all traces to the figure
492
+ figure = go.Figure(data=[line_stock, dummy_negative, dummy_positive], layout=layout)
493
+ # figure.update_traces(mode="markers+lines")
494
+ figure.update_layout(
495
+ title={
496
+ 'text': title,
497
+ 'x': 0.5,
498
+ 'y': 0.95,
499
+ 'xanchor': 'center',
500
+ 'yanchor': 'top',
501
+ 'font': dict(size=12),
502
+ },
503
+ hovermode='closest',
504
+ margin=dict(l=40, r=40, t=80, b=40),
505
+ )
506
+ figure.update_xaxes(
507
+ rangeslider_visible=True,
508
+ rangeselector=dict(
509
+ buttons=list([
510
+ dict(count=1, label="1m", step="month", stepmode="backward"),
511
+ dict(count=6, label="6m", step="month", stepmode="backward"),
512
+ dict(count=1, label="YTD", step="year", stepmode="todate"),
513
+ dict(count=1, label="1y", step="year", stepmode="backward"),
514
+ dict(step="all")
515
+ ])
516
+ )
517
+ )
518
+ st.plotly_chart(figure)
519
+
520
+
521
+ with chat:
522
+ st.balloons()