Dmitry Beresnev commited on
Commit
803210e
Β·
1 Parent(s): e458064
Files changed (1) hide show
  1. app/main.py +400 -55
app/main.py CHANGED
@@ -9,59 +9,404 @@ import os
9
  load_dotenv()
10
  token = os.getenv("TOKEN")
11
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- st.title("TradingView + Tech Indicators Dashboard")
14
-
15
- symbol = st.text_input("Ticker", "AAPL")
16
- period = st.slider("SMA/EMA/RSI period", 5, 50, 20)
17
-
18
- if st.button("Load Dashboard"):
19
-
20
- # Load free stock data via OpenBB
21
- df = sdk.equity.price.historical(symbol=symbol).to_dataframe()
22
-
23
- # ---- Technical Indicators ----
24
- df["SMA"] = df["close"].rolling(period).mean()
25
- df["EMA"] = df["close"].ewm(span=period, adjust=False).mean()
26
- delta = df["close"].diff()
27
- gain = delta.clip(lower=0)
28
- loss = -1 * delta.clip(upper=0)
29
- avg_gain = gain.rolling(period).mean()
30
- avg_loss = loss.rolling(period).mean()
31
- rs = avg_gain / avg_loss
32
- df["RSI"] = 100 - (100 / (1 + rs))
33
-
34
- # ---- Tabs ----
35
- tab1, tab2, tab3 = st.tabs(["TradingView", "Price + SMA/EMA", "RSI"])
36
-
37
- # ---- Tab 1: Interactive TradingView ----
38
- with tab1:
39
- tradingview_html = f"""
40
- <div class="tradingview-widget-container">
41
- <div id="tradingview_{symbol}"></div>
42
- <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
43
- <script type="text/javascript">
44
- new TradingView.widget({{
45
- "width": "100%",
46
- "height": 600,
47
- "symbol": "{symbol}",
48
- "interval": "D",
49
- "timezone": "Etc/UTC",
50
- "theme": "light",
51
- "style": "1",
52
- "locale": "en",
53
- "toolbar_bg": "#f1f3f6",
54
- "enable_publishing": false,
55
- "allow_symbol_change": true,
56
- "container_id": "tradingview_{symbol}"
57
- }});
58
- </script>
59
- </div>
60
- """
61
- st.components.v1.html(tradingview_html, height=650)
62
-
63
- # ---- Tab 2: Price + SMA/EMA ----
64
- with tab2:
65
- fig = go.Figure()
66
- fig.add_trace(go.Scatter(x=df.index, y=df["close"], name="Close"))
67
- fig.add_trace(go.Scatter(x=df.index, y=df["SMA"], name=f"SMA {period}"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  load_dotenv()
10
  token = os.getenv("TOKEN")
11
 
12
+ # ---- Page Configuration ----
13
+ st.set_page_config(
14
+ page_title="Financial Dashboard",
15
+ page_icon="πŸ“ˆ",
16
+ layout="wide",
17
+ initial_sidebar_state="expanded",
18
+ menu_items={
19
+ "About": "A professional financial analysis dashboard with technical indicators"
20
+ }
21
+ )
22
 
23
+ # ---- Custom CSS for Dark Theme ----
24
+ st.markdown("""
25
+ <style>
26
+ :root {
27
+ --primary-color: #0066ff;
28
+ --secondary-color: #1f77e2;
29
+ --success-color: #00d084;
30
+ --danger-color: #ff3838;
31
+ --warning-color: #ffa500;
32
+ --bg-dark: #0e1117;
33
+ --bg-darker: #010409;
34
+ --text-primary: #e6edf3;
35
+ --text-secondary: #8b949e;
36
+ --border-color: #30363d;
37
+ }
38
+
39
+ .metric-card {
40
+ background: linear-gradient(135deg, #1f2937 0%, #111827 100%);
41
+ padding: 1.5rem;
42
+ border-radius: 10px;
43
+ border: 1px solid var(--border-color);
44
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
45
+ }
46
+
47
+ .metric-value {
48
+ font-size: 2.5rem;
49
+ font-weight: 700;
50
+ color: var(--primary-color);
51
+ margin: 0.5rem 0;
52
+ }
53
+
54
+ .metric-label {
55
+ font-size: 0.875rem;
56
+ color: var(--text-secondary);
57
+ text-transform: uppercase;
58
+ letter-spacing: 0.05em;
59
+ }
60
+
61
+ .section-title {
62
+ color: var(--text-primary);
63
+ border-bottom: 2px solid var(--primary-color);
64
+ padding-bottom: 1rem;
65
+ margin-top: 2rem;
66
+ margin-bottom: 1.5rem;
67
+ }
68
+ </style>
69
+ """, unsafe_allow_html=True)
70
+
71
+ # ---- Header ----
72
+ st.markdown("# πŸ“ˆ Financial Analysis Dashboard")
73
+ st.markdown("Real-time technical analysis with multiple indicators")
74
+
75
+ # ---- Sidebar Configuration ----
76
+ with st.sidebar:
77
+ st.markdown("## βš™οΈ Settings")
78
+ symbol = st.text_input("Stock Ticker", "AAPL", help="Enter a valid stock ticker symbol").upper()
79
+ period = st.slider("Indicator Period", 5, 50, 20, help="Period for SMA, EMA, and RSI calculations")
80
+
81
+ st.markdown("---")
82
+ st.markdown("### About")
83
+ st.info("This dashboard provides real-time technical analysis using OpenBB data.")
84
+
85
+ if st.button("πŸ“Š Load Dashboard", key="load_btn", use_container_width=True):
86
+
87
+ try:
88
+ # Load free stock data via OpenBB
89
+ with st.spinner("Loading data..."):
90
+ df = sdk.equity.price.historical(symbol=symbol).to_dataframe()
91
+
92
+ # Load company profile
93
+ profile_data = sdk.equity.profile(symbol=symbol)
94
+ profile_info = profile_data[0] if profile_data else None
95
+
96
+ # Load income statement
97
+ income_stmt = sdk.equity.fundamental.income(symbol=symbol).to_dataframe()
98
+
99
+ # ---- Technical Indicators ----
100
+ df["SMA"] = df["close"].rolling(period).mean()
101
+ df["EMA"] = df["close"].ewm(span=period, adjust=False).mean()
102
+ delta = df["close"].diff()
103
+ gain = delta.clip(lower=0)
104
+ loss = -1 * delta.clip(upper=0)
105
+ avg_gain = gain.rolling(period).mean()
106
+ avg_loss = loss.rolling(period).mean()
107
+ rs = avg_gain / avg_loss
108
+ df["RSI"] = 100 - (100 / (1 + rs))
109
+
110
+ # ---- Display Key Metrics ----
111
+ st.markdown('<div class="section-title">πŸ“Š Price Metrics</div>', unsafe_allow_html=True)
112
+
113
+ col1, col2, col3, col4 = st.columns(4)
114
+
115
+ current_price = df["close"].iloc[-1]
116
+ prev_close = df["close"].iloc[-2] if len(df) > 1 else df["close"].iloc[0]
117
+ price_change = current_price - prev_close
118
+ price_change_pct = (price_change / prev_close) * 100 if prev_close != 0 else 0
119
+
120
+ with col1:
121
+ st.metric("Current Price", f"${current_price:.2f}", f"{price_change:+.2f}", delta_color="normal")
122
+
123
+ with col2:
124
+ st.metric("Day Change %", f"{price_change_pct:+.2f}%", None, delta_color="normal")
125
+
126
+ with col3:
127
+ st.metric("52W High", f"${df['high'].max():.2f}")
128
+
129
+ with col4:
130
+ st.metric("52W Low", f"${df['low'].min():.2f}")
131
+
132
+ # ---- Company Information & Financials ----
133
+ st.markdown('<div class="section-title">πŸ“‹ Company Information</div>', unsafe_allow_html=True)
134
+
135
+ if profile_info:
136
+ info_col1, info_col2 = st.columns(2)
137
+ with info_col1:
138
+ st.write(f"**Company Name:** {getattr(profile_info, 'name', 'N/A')}")
139
+ st.write(f"**Sector:** {getattr(profile_info, 'sector', 'N/A')}")
140
+ st.write(f"**Industry:** {getattr(profile_info, 'industry', 'N/A')}")
141
+
142
+ with info_col2:
143
+ st.write(f"**Country:** {getattr(profile_info, 'country', 'N/A')}")
144
+ st.write(f"**Exchange:** {getattr(profile_info, 'exchange', 'N/A')}")
145
+ st.write(f"**Website:** {getattr(profile_info, 'website', 'N/A')}")
146
+
147
+ # ---- Financial Metrics ----
148
+ if not income_stmt.empty:
149
+ st.markdown('<div class="section-title">πŸ’° Financial Metrics</div>', unsafe_allow_html=True)
150
+
151
+ # Get latest financial data
152
+ latest_income = income_stmt.iloc[0] if len(income_stmt) > 0 else None
153
+
154
+ if latest_income is not None:
155
+ fin_col1, fin_col2, fin_col3, fin_col4 = st.columns(4)
156
+
157
+ with fin_col1:
158
+ revenue = latest_income.get('total_revenue', 0)
159
+ if pd.notna(revenue) and revenue > 0:
160
+ st.metric("Total Revenue", f"${revenue/1e9:.2f}B" if revenue > 1e9 else f"${revenue/1e6:.2f}M")
161
+ else:
162
+ st.metric("Total Revenue", "N/A")
163
+
164
+ with fin_col2:
165
+ net_income = latest_income.get('net_income', 0)
166
+ if pd.notna(net_income) and net_income > 0:
167
+ st.metric("Net Income", f"${net_income/1e9:.2f}B" if net_income > 1e9 else f"${net_income/1e6:.2f}M")
168
+ else:
169
+ st.metric("Net Income", "N/A")
170
+
171
+ with fin_col3:
172
+ gross_profit = latest_income.get('gross_profit', 0)
173
+ if pd.notna(gross_profit) and gross_profit > 0:
174
+ st.metric("Gross Profit", f"${gross_profit/1e9:.2f}B" if gross_profit > 1e9 else f"${gross_profit/1e6:.2f}M")
175
+ else:
176
+ st.metric("Gross Profit", "N/A")
177
+
178
+ with fin_col4:
179
+ operating_income = latest_income.get('operating_income', 0)
180
+ if pd.notna(operating_income) and operating_income > 0:
181
+ st.metric("Operating Income", f"${operating_income/1e9:.2f}B" if operating_income > 1e9 else f"${operating_income/1e6:.2f}M")
182
+ else:
183
+ st.metric("Operating Income", "N/A")
184
+
185
+ # Additional metrics
186
+ fin_col5, fin_col6, fin_col7, fin_col8 = st.columns(4)
187
+
188
+ with fin_col5:
189
+ eps = latest_income.get('diluted_earnings_per_share', 0)
190
+ if pd.notna(eps):
191
+ st.metric("EPS (Diluted)", f"${eps:.2f}")
192
+ else:
193
+ st.metric("EPS (Diluted)", "N/A")
194
+
195
+ with fin_col6:
196
+ ebitda = latest_income.get('ebitda', 0)
197
+ if pd.notna(ebitda) and ebitda > 0:
198
+ st.metric("EBITDA", f"${ebitda/1e9:.2f}B" if ebitda > 1e9 else f"${ebitda/1e6:.2f}M")
199
+ else:
200
+ st.metric("EBITDA", "N/A")
201
+
202
+ with fin_col7:
203
+ cogs = latest_income.get('cost_of_revenue', 0)
204
+ if pd.notna(cogs) and cogs > 0:
205
+ st.metric("Cost of Revenue", f"${cogs/1e9:.2f}B" if cogs > 1e9 else f"${cogs/1e6:.2f}M")
206
+ else:
207
+ st.metric("Cost of Revenue", "N/A")
208
+
209
+ with fin_col8:
210
+ rd_expense = latest_income.get('research_and_development_expense', 0)
211
+ if pd.notna(rd_expense) and rd_expense > 0:
212
+ st.metric("R&D Expense", f"${rd_expense/1e9:.2f}B" if rd_expense > 1e9 else f"${rd_expense/1e6:.2f}M")
213
+ else:
214
+ st.metric("R&D Expense", "N/A")
215
+
216
+ # Financial history chart
217
+ st.markdown('<div class="section-title">πŸ“Š Revenue & Net Income Trend</div>', unsafe_allow_html=True)
218
+
219
+ # Prepare data for chart
220
+ if len(income_stmt) > 0:
221
+ income_chart_data = income_stmt[['period_ending', 'total_revenue', 'net_income']].dropna()
222
+
223
+ if len(income_chart_data) > 0:
224
+ fig_financial = go.Figure()
225
+
226
+ fig_financial.add_trace(go.Bar(
227
+ x=income_chart_data['period_ending'],
228
+ y=income_chart_data['total_revenue'],
229
+ name="Total Revenue",
230
+ marker=dict(color='#0066ff'),
231
+ yaxis='y1'
232
+ ))
233
+
234
+ fig_financial.add_trace(go.Bar(
235
+ x=income_chart_data['period_ending'],
236
+ y=income_chart_data['net_income'],
237
+ name="Net Income",
238
+ marker=dict(color='#00d084'),
239
+ yaxis='y1'
240
+ ))
241
+
242
+ fig_financial.update_layout(
243
+ title="Revenue & Net Income (Annual)",
244
+ xaxis_title="Period",
245
+ yaxis_title="Amount ($)",
246
+ hovermode="x unified",
247
+ template="plotly_dark",
248
+ height=400,
249
+ barmode='group',
250
+ margin=dict(l=0, r=0, t=40, b=0)
251
+ )
252
+
253
+ st.plotly_chart(fig_financial, use_container_width=True)
254
+
255
+ # ---- Tabs ----
256
+ tab1, tab2, tab3, tab4 = st.tabs(["πŸ“ˆ Price & Moving Averages", "πŸ“Š RSI Indicator", "πŸ“‰ TradingView", "πŸ“‹ Financials"])
257
+
258
+ # ---- Tab 1: Price + SMA/EMA ----
259
+ with tab1:
260
+ fig_price = go.Figure()
261
+
262
+ fig_price.add_trace(go.Scatter(
263
+ x=df.index, y=df["close"],
264
+ name="Close Price",
265
+ line=dict(color="#0066ff", width=2)
266
+ ))
267
+ fig_price.add_trace(go.Scatter(
268
+ x=df.index, y=df["SMA"],
269
+ name=f"SMA {period}",
270
+ line=dict(color="#00d084", width=2, dash="dash")
271
+ ))
272
+ fig_price.add_trace(go.Scatter(
273
+ x=df.index, y=df["EMA"],
274
+ name=f"EMA {period}",
275
+ line=dict(color="#ffa500", width=2, dash="dot")
276
+ ))
277
+
278
+ fig_price.update_layout(
279
+ title=f"{symbol} - Price with Moving Averages",
280
+ xaxis_title="Date",
281
+ yaxis_title="Price ($)",
282
+ hovermode="x unified",
283
+ template="plotly_dark",
284
+ height=500,
285
+ margin=dict(l=0, r=0, t=40, b=0)
286
+ )
287
+
288
+ st.plotly_chart(fig_price, use_container_width=True)
289
+
290
+ # ---- Tab 2: RSI ----
291
+ with tab2:
292
+ fig_rsi = go.Figure()
293
+
294
+ fig_rsi.add_trace(go.Scatter(
295
+ x=df.index, y=df["RSI"],
296
+ name="RSI",
297
+ line=dict(color="#ff3838", width=2),
298
+ fill="tozeroy",
299
+ fillcolor="rgba(255, 56, 56, 0.2)"
300
+ ))
301
+
302
+ # Add overbought/oversold lines
303
+ fig_rsi.add_hline(y=70, line_dash="dash", line_color="rgba(255, 165, 0, 0.5)", annotation_text="Overbought")
304
+ fig_rsi.add_hline(y=30, line_dash="dash", line_color="rgba(0, 208, 132, 0.5)", annotation_text="Oversold")
305
+
306
+ fig_rsi.update_layout(
307
+ title=f"{symbol} - Relative Strength Index (RSI)",
308
+ xaxis_title="Date",
309
+ yaxis_title="RSI",
310
+ hovermode="x unified",
311
+ template="plotly_dark",
312
+ height=500,
313
+ yaxis=dict(range=[0, 100]),
314
+ margin=dict(l=0, r=0, t=40, b=0)
315
+ )
316
+
317
+ st.plotly_chart(fig_rsi, use_container_width=True)
318
+
319
+ # ---- Tab 3: TradingView ----
320
+ with tab3:
321
+ tradingview_html = f"""
322
+ <div class="tradingview-widget-container">
323
+ <div id="tradingview_{symbol}"></div>
324
+ <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
325
+ <script type="text/javascript">
326
+ new TradingView.widget({{
327
+ "width": "100%",
328
+ "height": 600,
329
+ "symbol": "{symbol}",
330
+ "interval": "D",
331
+ "timezone": "Etc/UTC",
332
+ "theme": "dark",
333
+ "style": "1",
334
+ "locale": "en",
335
+ "enable_publishing": false,
336
+ "allow_symbol_change": true,
337
+ "container_id": "tradingview_{symbol}"
338
+ }});
339
+ </script>
340
+ </div>
341
+ """
342
+ st.components.v1.html(tradingview_html, height=650)
343
+
344
+ # ---- Tab 4: Detailed Financials ----
345
+ with tab4:
346
+ st.markdown("### Income Statement")
347
+
348
+ if not income_stmt.empty:
349
+ # Select key columns to display
350
+ display_columns = [
351
+ 'period_ending',
352
+ 'total_revenue',
353
+ 'cost_of_revenue',
354
+ 'gross_profit',
355
+ 'operating_income',
356
+ 'net_income',
357
+ 'diluted_earnings_per_share',
358
+ 'ebitda'
359
+ ]
360
+
361
+ # Filter to available columns
362
+ available_cols = [col for col in display_columns if col in income_stmt.columns]
363
+ financial_display = income_stmt[available_cols].copy()
364
+
365
+ # Format numeric columns
366
+ for col in financial_display.columns:
367
+ if col != 'period_ending':
368
+ financial_display[col] = financial_display[col].apply(
369
+ lambda x: f"${x/1e9:.2f}B" if pd.notna(x) and abs(x) >= 1e9 else (
370
+ f"${x/1e6:.2f}M" if pd.notna(x) and abs(x) >= 1e6 else (
371
+ f"${x:.2f}" if pd.notna(x) else "N/A"
372
+ )
373
+ )
374
+ )
375
+
376
+ st.dataframe(financial_display, use_container_width=True, hide_index=True)
377
+
378
+ # Profitability metrics
379
+ st.markdown("### Profitability Metrics")
380
+
381
+ prof_col1, prof_col2 = st.columns(2)
382
+
383
+ with prof_col1:
384
+ # Calculate profit margins
385
+ latest_data = income_stmt.iloc[0]
386
+ total_rev = latest_data.get('total_revenue', 0)
387
+ gross_prof = latest_data.get('gross_profit', 0)
388
+ net_inc = latest_data.get('net_income', 0)
389
+
390
+ if total_rev and total_rev > 0:
391
+ gross_margin = (gross_prof / total_rev) * 100 if pd.notna(gross_prof) else 0
392
+ net_margin = (net_inc / total_rev) * 100 if pd.notna(net_inc) else 0
393
+
394
+ st.metric("Gross Margin", f"{gross_margin:.2f}%")
395
+ st.metric("Net Profit Margin", f"{net_margin:.2f}%")
396
+
397
+ with prof_col2:
398
+ operating_inc = latest_data.get('operating_income', 0)
399
+ if total_rev and total_rev > 0 and operating_inc:
400
+ operating_margin = (operating_inc / total_rev) * 100
401
+ st.metric("Operating Margin", f"{operating_margin:.2f}%")
402
+
403
+ # Growth comparison
404
+ if len(income_stmt) > 1:
405
+ prev_revenue = income_stmt.iloc[1].get('total_revenue', 0)
406
+ if prev_revenue and prev_revenue > 0:
407
+ revenue_growth = ((total_rev - prev_revenue) / prev_revenue) * 100
408
+ st.metric("Revenue Growth (YoY)", f"{revenue_growth:+.2f}%")
409
+
410
+ except Exception as e:
411
+ st.error(f"Error loading data for {symbol}: {str(e)}")
412
+ st.info("Please check the ticker symbol and try again.")