-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTraderDashboard3Github.py
More file actions
279 lines (211 loc) · 9.19 KB
/
TraderDashboard3Github.py
File metadata and controls
279 lines (211 loc) · 9.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import streamlit as st
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import re
import os
import time
# --- KONFIGURATION ---
ST_PAGE_TITLE = "Trader Dashboard - Top 20 Momentum"
# ÄNDRING: Relativ sökväg för molnet (filen måste ligga i samma mapp på GitHub)
FILE_PATH = "UNIVERSES.txt"
DEFAULT_LOOKBACK = "2y"
st.set_page_config(page_title=ST_PAGE_TITLE, layout="wide", page_icon="🏆")
# Dark mode CSS
st.markdown("""
<style>
.reportview-container { background: #0e1117; }
.main { background: #0e1117; color: white; }
h1, h2, h3 { color: #f0f2f6; }
</style>
""", unsafe_allow_html=True)
# --- FUNKTIONER ---
def parse_universes(filepath):
universes = {}
if not os.path.exists(filepath):
# Visar tydligt felmeddelande om filen saknas i repot
st.error(f"Kunde inte hitta filen: {filepath}. Se till att 'UNIVERSES.txt' ligger i GitHub-repot.")
return universes
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
# Regex-fix för backslashes enligt minnesregel [2025-12-19]
content = re.sub(r'\\', '', content)
pattern = re.compile(r'(\w+)\s*=\s*\[(.*?)\]', re.DOTALL)
matches = pattern.findall(content)
for name, list_content in matches:
lines = list_content.split('\n')
cleaned_lines = []
for line in lines:
line = line.split('#')[0]
cleaned_lines.append(line)
full_string = "".join(cleaned_lines)
clean_content = re.sub(r'["\'\s]', '', full_string)
clean_content = re.sub(r'\\', '', clean_content)
tickers = [t.strip() for t in clean_content.split(',') if t.strip()]
if tickers:
universes[name] = tickers
return universes
@st.cache_data(ttl=300)
def fetch_data(tickers, period="2y"):
if not tickers:
return pd.DataFrame()
try:
data = yf.download(tickers, period=period, group_by='ticker', progress=False, auto_adjust=True, threads=True)
return data
except Exception as e:
st.error(f"Fel vid hämtning av data: {e}")
return pd.DataFrame()
def calculate_rsi(series, period=5):
delta = series.diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.ewm(alpha=1/period, min_periods=period, adjust=False).mean()
avg_loss = loss.ewm(alpha=1/period, min_periods=period, adjust=False).mean()
rs = avg_gain / avg_loss
return 100 - (100 / (1 + rs))
def analyze_ticker(ticker, df):
t_data = None
if isinstance(df.columns, pd.MultiIndex):
if ticker in df.columns:
t_data = df[ticker].copy()
elif ticker.upper() in df.columns:
t_data = df[ticker.upper()].copy()
else:
t_data = df.copy()
if t_data is not None and not t_data.empty:
t_data = t_data.dropna(subset=['Close'])
if t_data is None or t_data.empty or len(t_data) < 200:
return None
close = t_data['Close']
t_data['MA50'] = close.rolling(window=50).mean()
t_data['MA200'] = close.rolling(window=200).mean()
t_data['RSI5'] = calculate_rsi(close, period=5)
current = t_data.iloc[-1]
if pd.isna(current['MA200']) or pd.isna(current['MA50']) or pd.isna(current['Close']):
return None
is_uptrend = (current['Close'] > current['MA50']) and (current['MA50'] > current['MA200'])
if not is_uptrend:
return None
try:
price_now = current['Close']
if len(t_data) > 130:
price_3m = t_data['Close'].iloc[-63]
price_6m = t_data['Close'].iloc[-126]
ret_3m = (price_now / price_3m) - 1
ret_6m = (price_now / price_6m) - 1
momentum_score = (ret_3m * 100) + (ret_6m * 100)
else:
momentum_score = 0
except (IndexError, ZeroDivisionError):
return None
rsi_val = current['RSI5']
if pd.isna(rsi_val): rsi_val = 50.0
return {
'ticker': ticker,
'data': t_data,
'momentum_val': momentum_score,
'price': current['Close'],
'rsi': rsi_val,
'ma50': current['MA50'],
'ma200': current['MA200']
}
def get_full_name(ticker):
try:
t = yf.Ticker(ticker)
info = t.info
name = info.get('longName') or info.get('shortName') or ticker
return name
except Exception:
return ticker
def plot_chart(metrics):
df = metrics['data']
display_name = metrics.get('full_name', metrics['ticker'])
rsi = metrics['rsi']
display_df = df.tail(126)
rsi_color = "green" if rsi < 60 else "red"
rsi_text = "DIP" if rsi < 60 else "HÖG"
title_html = (f"<b>{display_name}</b><br>"
f"<span style='font-size: 14px;'>Pris: {metrics['price']:.2f} | "
f"Mom: {metrics['momentum_val']:.2f} | "
f"<span style='color:{rsi_color}'>RSI: {rsi:.2f} ({rsi_text})</span></span>")
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
vertical_spacing=0.1, row_heights=[0.7, 0.3])
fig.add_trace(go.Scatter(x=display_df.index, y=display_df['Close'], name='Pris',
line=dict(color='#00F0FF', width=2)), row=1, col=1)
fig.add_trace(go.Scatter(x=display_df.index, y=display_df['MA50'], name='MA50',
line=dict(color='#FFA500', width=1)), row=1, col=1)
fig.add_trace(go.Scatter(x=display_df.index, y=display_df['MA200'], name='MA200',
line=dict(color='#FF0000', width=1)), row=1, col=1)
fig.add_trace(go.Scatter(x=display_df.index, y=display_df['RSI5'], name='RSI(5)',
line=dict(color='#ADFF2F', width=1.5)), row=2, col=1)
fig.add_hline(y=90, line_dash="dot", line_color="red", row=2, col=1)
fig.add_hline(y=50, line_dash="solid", line_color="white", row=2, col=1)
fig.add_hline(y=10, line_dash="dot", line_color="green", row=2, col=1)
fig.update_layout(
title=dict(text=title_html, x=0, font=dict(size=16)),
template="plotly_dark",
margin=dict(l=10, r=10, t=50, b=10),
height=450,
showlegend=False,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)'
)
fig.update_xaxes(rangeslider_visible=False)
return fig
# --- MAIN ---
def main():
st.sidebar.title("⚙️ Inställningar")
universes = parse_universes(FILE_PATH)
if not universes:
# Om filen finns men är tom eller felaktig
st.warning("Hittade filen men inga listor kunde läsas in.")
return
selected_universe_name = st.sidebar.selectbox("Välj Instrument-lista", list(universes.keys()))
selected_tickers = universes[selected_universe_name]
st.sidebar.markdown(f"**Antal instrument:** {len(selected_tickers)}")
auto_refresh = st.sidebar.checkbox("Aktivera Auto-Refresh (60s)", value=True)
if st.sidebar.button("🔄 Uppdatera Nu"):
st.cache_data.clear()
st.rerun()
st.markdown(f"<h1 style='font-size: 25px;'>🚀 Top 20 Momentum: {selected_universe_name}</h1>", unsafe_allow_html=True)
st.markdown("Visar **Golden Trend** instrument rankade efter **3m + 6m avkastning**.")
with st.spinner('Hämtar prisdata...'):
data = fetch_data(selected_tickers, period=DEFAULT_LOOKBACK)
if data.empty:
st.error("Ingen data kunde hämtas.")
return
analyzed_stocks = []
progress_bar = st.progress(0)
loop_tickers = selected_tickers if len(selected_tickers) > 1 else [selected_tickers[0]]
for i, ticker in enumerate(loop_tickers):
try:
metrics = analyze_ticker(ticker, data)
if metrics:
analyzed_stocks.append(metrics)
except Exception:
pass
if len(loop_tickers) > 0:
progress_bar.progress((i + 1) / len(loop_tickers))
progress_bar.empty()
analyzed_stocks.sort(key=lambda x: x['momentum_val'], reverse=True)
top_stocks = analyzed_stocks[:20]
if not top_stocks:
st.warning(f"Inga instrument uppfyller kriterierna (Pris > MA50 > MA200) för {selected_universe_name}.")
return
with st.spinner(f'Hämtar beskrivande namn för de {len(top_stocks)} bästa kandidaterna...'):
for stock in top_stocks:
stock['full_name'] = get_full_name(stock['ticker'])
col1, col2 = st.columns(2)
for i, stock in enumerate(top_stocks):
fig = plot_chart(stock)
# ÄNDRING: width="stretch" fungerar ej. use_container_width=True är korrekt.
if i % 2 == 0:
with col1: st.plotly_chart(fig, use_container_width=True)
else:
with col2: st.plotly_chart(fig, use_container_width=True)
if auto_refresh:
time.sleep(60)
st.rerun()
if __name__ == "__main__":
main()