Dmitry Beresnev commited on
Commit Β·
803210e
1
Parent(s): e458064
fix UI
Browse files8 unmodified lines9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566678 unmodified linesload_dotenv()token = os.getenv("TOKEN")st.title("TradingView + Tech Indicators Dashboard")symbol = st.text_input("Ticker", "AAPL")period = st.slider("SMA/EMA/RSI period", 5, 50, 20)if st.button("Load Dashboard"):# Load free stock data via OpenBBdf = sdk.equity.price.historical(symbol=symbol).to_dataframe()# ---- Technical Indicators ----df["SMA"] = df["close"].rolling(period).mean()df["EMA"] = df["close"].ewm(span=period, adjust=False).mean()delta = df["close"].diff()gain = delta.clip(lower=0)loss = -1 * delta.clip(upper=0)avg_gain = gain.rolling(period).mean()avg_loss = loss.rolling(period).mean()rs = avg_gain / avg_lossdf["RSI"] = 100 - (100 / (1 + rs))# ---- Tabs ----tab1, tab2, tab3 = st.tabs(["TradingView", "Price + SMA/EMA", "RSI"])# ---- Tab 1: Interactive TradingView ----with tab1:tradingview_html = f"""<div class="tradingview-widget-container"><div id="tradingview_{symbol}"></div><script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script><script type="text/javascript">new TradingView.widget({{"width": "100%","height": 600,"symbol": "{symbol}","interval": "D","timezone": "Etc/UTC","theme": "light","style": "1","locale": "en","toolbar_bg": "#f1f3f6","enable_publishing": false,"allow_symbol_change": true,"container_id": "tradingview_{symbol}"}});</script></div>"""st.components.v1.html(tradingview_html, height=650)# ---- Tab 2: Price + SMA/EMA ----with tab2:fig = go.Figure()fig.add_trace(go.Scatter(x=df.index, y=df["close"], name="Close"))fig.add_trace(go.Scatter(x=df.index, y=df["SMA"], name=f"SMA {period}"))8 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114128 unmodified linesload_dotenv()token = os.getenv("TOKEN")# ---- Page Configuration ----st.set_page_config(page_title="Financial Dashboard",page_icon="π",layout="wide",initial_sidebar_state="expanded",menu_items={"About": "A professional financial analysis dashboard with technical indicators"})# ---- Custom CSS for Dark Theme ----st.markdown("""<style>:root {--primary-color: #0066ff;--secondary-color: #1f77e2;--success-color: #00d084;--danger-color: #ff3838;--warning-color: #ffa500;--bg-dark: #0e1117;--bg-darker: #010409;--text-primary: #e6edf3;--text-secondary: #8b949e;--border-color: #30363d;}.metric-card {background: linear-gradient(135deg, #1f2937 0%, #111827 100%);padding: 1.5rem;border-radius: 10px;border: 1px solid var(--border-color);box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);}.metric-value {font-size: 2.5rem;font-weight: 700;color: var(--primary-color);margin: 0.5rem 0;}.metric-label {font-size: 0.875rem;color: var(--text-secondary);text-transform: uppercase;letter-spacing: 0.05em;}.section-title {color: var(--text-primary);border-bottom: 2px solid var(--primary-color);padding-bottom: 1rem;margin-top: 2rem;margin-bottom: 1.5rem;}</style>""", unsafe_allow_html=True)# ---- Header ----st.markdown("# π Financial Analysis Dashboard")st.markdown("Real-time technical analysis with multiple indicators")# ---- Sidebar Configuration ----with st.sidebar:st.markdown("## βοΈ Settings")symbol = st.text_input("Stock Ticker", "AAPL", help="Enter a valid stock ticker symbol").upper()period = st.slider("Indicator Period", 5, 50, 20, help="Period for SMA, EMA, and RSI calculations")st.markdown("---")st.markdown("### About")st.info("This dashboard provides real-time technical analysis using OpenBB data.")if st.button("π Load Dashboard", key="load_btn", use_container_width=True):try:# Load free stock data via OpenBBwith st.spinner("Loading data..."):df = sdk.equity.price.historical(symbol=symbol).to_dataframe()# Load company profileprofile_data = sdk.equity.profile(symbol=symbol)profile_info = profile_data[0] if profile_data else None# Load income statementincome_stmt = sdk.equity.fundamental.income(symbol=symbol).to_dataframe()# ---- Technical Indicators ----df["SMA"] = df["close"].rolling(period).mean()df["EMA"] = df["close"].ewm(span=period, adjust=False).mean()delta = df["close"].diff()gain = delta.clip(lower=0)loss = -1 * delta.clip(upper=0)avg_gain = gain.rolling(period).mean()avg_loss = loss.rolling(period).mean()rs = avg_gain / avg_lossdf["RSI"] = 100 - (100 / (1 + rs))# ---- Display Key Metrics ----st.markdown('<div class="section-title">π Price Metrics</div>', unsafe_allow_html=True)col1, col2, col3, col4 = st.columns(4)current_price = df["close"].iloc[-1]prev_close = df["close"].iloc[-2] if len(df) > 1 else df["close"].iloc[0]price_change = current_price - prev_closeprice_change_pct = (price_change / prev_close) * 100 if prev_close != 0 else 0with col1:st.metric("Current Price", f"${current_price:.2f}", f"{price_change:+.2f}", delta_color="normal")with col2:st.metric("Day Change %", f"{price_change_pct:+.2f}%", None, delta_color="normal")with col3:st.metric("52W High", f"${df['high'].max():.2f}")with col4:st.metric("52W Low", f"${df['low'].min():.2f}")# ---- Company Information & Financials ----st.markdown('<div class="section-title">π Company Information</div>', unsafe_allow_html=True)if profile_info:info_col1, info_col2 = st.columns(2)with info_col1:st.write(f"**Company Name:** {getattr(profile_info, 'name', 'N/A')}")st.write(f"**Sector:** {getattr(profile_info, 'sector', 'N/A')}")st.write(f"**Industry:** {getattr(profile_info, 'industry', 'N/A')}")with info_col2:st.write(f"**Country:** {getattr(profile_info, 'country', 'N/A')}")st.write(f"**Exchange:** {getattr(profile_info, 'exchange', 'N/A')}")st.write(f"**Website:** {getattr(profile_info, 'website', 'N/A')}")# ---- Financial Metrics ----if not income_stmt.empty:st.markdown('<div class="section-title">π° Financial Metrics</div>', unsafe_allow_html=True)# Get latest financial datalatest_income = income_stmt.iloc[0] if len(income_stmt) > 0 else Noneif latest_income is not None:fin_col1, fin_col2, fin_col3, fin_col4 = st.columns(4)with fin_col1:revenue = latest_income.get('total_revenue', 0)if pd.notna(revenue) and revenue > 0:st.metric("Total Revenue", f"${revenue/1e9:.2f}B" if revenue > 1e9 else f"${revenue/1e6:.2f}M")else:st.metric("Total Revenue", "N/A")with fin_col2:net_income = latest_income.get('net_income', 0)if pd.notna(net_income) and net_income > 0:st.metric("Net Income", f"${net_income/1e9:.2f}B" if net_income > 1e9 else f"${net_income/1e6:.2f}M")else:st.metric("Net Income", "N/A")with fin_col3:gross_profit = latest_income.get('gross_profit', 0)if pd.notna(gross_profit) and gross_profit > 0:st.metric("Gross Profit", f"${gross_profit/1e9:.2f}B" if gross_profit > 1e9 else f"${gross_profit/1e6:.2f}M")else:st.metric("Gross Profit", "N/A")with fin_col4:operating_income = latest_income.get('operating_income', 0)if pd.notna(operating_income) and operating_income > 0:st.metric("Operating Income", f"${operating_income/1e9:.2f}B" if operating_income > 1e9 else f"${operating_income/1e6:.2f}M")else:st.metric("Operating Income", "N/A")# Additional metricsfin_col5, fin_col6, fin_col7, fin_col8 = st.columns(4)with fin_col5:eps = latest_income.get('diluted_earnings_per_share', 0)if pd.notna(eps):st.metric("EPS (Diluted)", f"${eps:.2f}")else:st.metric("EPS (Diluted)", "N/A")with fin_col6:ebitda = latest_income.get('ebitda', 0)if pd.notna(ebitda) and ebitda > 0:st.metric("EBITDA", f"${ebitda/1e9:.2f}B" if ebitda > 1e9 else f"${ebitda/1e6:.2f}M")else:st.metric("EBITDA", "N/A")with fin_col7:cogs = latest_income.get('cost_of_revenue', 0)if pd.notna(cogs) and cogs > 0:st.metric("Cost of Revenue", f"${cogs/1e9:.2f}B" if cogs > 1e9 else f"${cogs/1e6:.2f}M")else:st.metric("Cost of Revenue", "N/A")with fin_col8:rd_expense = latest_income.get('research_and_development_expense', 0)if pd.notna(rd_expense) and rd_expense > 0:st.metric("R&D Expense", f"${rd_expense/1e9:.2f}B" if rd_expense > 1e9 else f"${rd_expense/1e6:.2f}M")else:st.metric("R&D Expense", "N/A")# Financial history chartst.markdown('<div class="section-title">π Revenue & Net Income Trend</div>', unsafe_allow_html=True)# Prepare data for chartif len(income_stmt) > 0:income_chart_data = income_stmt[['period_ending', 'total_revenue', 'net_income']].dropna()if len(income_chart_data) > 0:fig_financial = go.Figure()fig_financial.add_trace(go.Bar(x=income_chart_data['period_ending'],y=income_chart_data['total_revenue'],name="Total Revenue",marker=dict(color='#0066ff'),yaxis='y1'))fig_financial.add_trace(go.Bar(x=income_chart_data['period_ending'],y=income_chart_data['net_income'],name="Net Income",marker=dict(color='#00d084'),yaxis='y1'))fig_financial.update_layout(title="Revenue & Net Income (Annual)",xaxis_title="Period",yaxis_title="Amount ($)",hovermode="x unified",template="plotly_dark",height=400,barmode='group',margin=dict(l=0, r=0, t=40, b=0))st.plotly_chart(fig_financial, use_container_width=True)# ---- Tabs ----tab1, tab2, tab3, tab4 = st.tabs(["π Price & Moving Averages", "π RSI Indicator", "π TradingView", "π Financials"])# ---- Tab 1: Price + SMA/EMA ----with tab1:fig_price = go.Figure()fig_price.add_trace(go.Scatter(x=df.index, y=df["close"],name="Close Price",line=dict(color="#0066ff", width=2)))fig_price.add_trace(go.Scatter(x=df.index, y=df["SMA"],name=f"SMA {period}",line=dict(color="#00d084", width=2, dash="dash")))fig_price.add_trace(go.Scatter(x=df.index, y=df["EMA"],name=f"EMA {period}",line=dict(color="#ffa500", width=2, dash="dot")))fig_price.update_layout(title=f"{symbol} - Price with Moving Averages",xaxis_title="Date",yaxis_title="Price ($)",hovermode="x unified",template="plotly_dark",height=500,margin=dict(l=0, r=0, t=40, b=0))st.plotly_chart(fig_price, use_container_width=True)# ---- Tab 2: RSI ----with tab2:fig_rsi = go.Figure()fig_rsi.add_trace(go.Scatter(x=df.index, y=df["RSI"],name="RSI",line=dict(color="#ff3838", width=2),fill="tozeroy",fillcolor="rgba(255, 56, 56, 0.2)"))# Add overbought/oversold linesfig_rsi.add_hline(y=70, line_dash="dash", line_color="rgba(255, 165, 0, 0.5)", annotation_text="Overbought")fig_rsi.add_hline(y=30, line_dash="dash", line_color="rgba(0, 208, 132, 0.5)", annotation_text="Oversold")fig_rsi.update_layout(title=f"{symbol} - Relative Strength Index (RSI)",xaxis_title="Date",yaxis_title="RSI",hovermode="x unified",template="plotly_dark",height=500,yaxis=dict(range=[0, 100]),margin=dict(l=0, r=0, t=40, b=0))st.plotly_chart(fig_rsi, use_container_width=True)# ---- Tab 3: TradingView ----with tab3:tradingview_html = f"""<div class="tradingview-widget-container"><div id="tradingview_{symbol}"></div><script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script><script type="text/javascript">new TradingView.widget({{"width": "100%","height": 600,"symbol": "{symbol}","interval": "D","timezone": "Etc/UTC","theme": "dark","style": "1","locale": "en","enable_publishing": false,"allow_symbol_change": true,"container_id": "tradingview_{symbol}"}});</script></div>"""st.components.v1.html(tradingview_html, height=650)# ---- Tab 4: Detailed Financials ----with tab4:st.markdown("### Income Statement")if not income_stmt.empty:# Select key columns to displaydisplay_columns = ['period_ending','total_revenue','cost_of_revenue','gross_profit','operating_income','net_income','diluted_earnings_per_share','ebitda']# Filter to available columnsavailable_cols = [col for col in display_columns if col in income_stmt.columns]financial_display = income_stmt[available_cols].copy()# Format numeric columnsfor col in financial_display.columns:if col != 'period_ending':financial_display[col] = financial_display[col].apply(lambda x: f"${x/1e9:.2f}B" if pd.notna(x) and abs(x) >= 1e9 else (f"${x/1e6:.2f}M" if pd.notna(x) and abs(x) >= 1e6 else (f"${x:.2f}" if pd.notna(x) else "N/A")))st.dataframe(financial_display, use_container_width=True, hide_index=True)# Profitability metricsst.markdown("### Profitability Metrics")prof_col1, prof_col2 = st.columns(2)with prof_col1:# Calculate profit marginslatest_data = income_stmt.iloc[0]total_rev = latest_data.get('total_revenue', 0)gross_prof = latest_data.get('gross_profit', 0)net_inc = latest_data.get('net_income', 0)if total_rev and total_rev > 0:gross_margin = (gross_prof / total_rev) * 100 if pd.notna(gross_prof) else 0net_margin = (net_inc / total_rev) * 100 if pd.notna(net_inc) else 0st.metric("Gross Margin", f"{gross_margin:.2f}%")st.metric("Net Profit Margin", f"{net_margin:.2f}%")with prof_col2:operating_inc = latest_data.get('operating_income', 0)if total_rev and total_rev > 0 and operating_inc:operating_margin = (operating_inc / total_rev) * 100st.metric("Operating Margin", f"{operating_margin:.2f}%")# Growth comparisonif len(income_stmt) > 1:prev_revenue = income_stmt.iloc[1].get('total_revenue', 0)if prev_revenue and prev_revenue > 0:revenue_growth = ((total_rev - prev_revenue) / prev_revenue) * 100st.metric("Revenue Growth (YoY)", f"{revenue_growth:+.2f}%")except Exception as e:st.error(f"Error loading data for {symbol}: {str(e)}")st.info("Please check the ticker symbol and try again.")
app/main.py+400-55