Spaces:
Running
Running
Benjamin Consolvo
commited on
Commit
·
dee760c
1
Parent(s):
3824258
clocks update
Browse files
app.py
CHANGED
@@ -273,14 +273,170 @@ class TradingApp:
|
|
273 |
symbol_to_name = self.analyzer.symbol_to_name
|
274 |
n = len(symbols)
|
275 |
|
276 |
-
#
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
284 |
# Calculate columns based on n for best fit
|
285 |
if n <= 3:
|
286 |
cols = n
|
@@ -431,6 +587,18 @@ def load_auto_trade_log():
|
|
431 |
# Add this at the top after imports to suppress Streamlit reruns on widget interaction
|
432 |
st.experimental_set_query_params() # This is a no-op but ensures Streamlit doesn't rerun due to query params
|
433 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
434 |
def main():
|
435 |
st.title("Stock Trading Application")
|
436 |
|
@@ -450,10 +618,26 @@ def main():
|
|
450 |
thread.start()
|
451 |
st.session_state["auto_trade_thread_started"] = True
|
452 |
|
453 |
-
|
454 |
-
|
455 |
-
else
|
456 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
457 |
|
458 |
# User inputs and portfolio are now in the sidebar
|
459 |
app.manual_trade()
|
|
|
273 |
symbol_to_name = self.analyzer.symbol_to_name
|
274 |
n = len(symbols)
|
275 |
|
276 |
+
# Calculate columns based on n for best fit
|
277 |
+
if n <= 3:
|
278 |
+
cols = n
|
279 |
+
elif n <= 6:
|
280 |
+
cols = 3
|
281 |
+
elif n <= 8:
|
282 |
+
cols = 4
|
283 |
+
elif n <= 12:
|
284 |
+
cols = 4
|
285 |
+
else:
|
286 |
+
cols = 5
|
287 |
+
|
288 |
+
rows = (n + cols - 1) // cols
|
289 |
+
subplot_titles = [
|
290 |
+
f"{symbol} - {symbol_to_name.get(symbol, '')}" for symbol in symbols
|
291 |
+
]
|
292 |
+
fig = make_subplots(rows=rows, cols=cols, subplot_titles=subplot_titles)
|
293 |
+
for idx, symbol in enumerate(symbols):
|
294 |
+
df = self.data[symbol]
|
295 |
+
if not df.empty:
|
296 |
+
row = idx // cols + 1
|
297 |
+
col = idx % cols + 1
|
298 |
+
fig.add_trace(
|
299 |
+
go.Scatter(
|
300 |
+
x=df.index,
|
301 |
+
y=df['Close'],
|
302 |
+
mode='lines',
|
303 |
+
name=symbol,
|
304 |
+
hovertemplate=f"%{{x}}<br>{symbol}: %{{y:.2f}}<extra></extra>"
|
305 |
+
),
|
306 |
+
row=row,
|
307 |
+
col=col
|
308 |
+
)
|
309 |
+
fig.update_layout(
|
310 |
+
title="Top Volume Stocks - Price Charts (Since 2023)",
|
311 |
+
height=max(400 * rows, 600),
|
312 |
+
showlegend=False,
|
313 |
+
dragmode=False,
|
314 |
+
)
|
315 |
+
# Enable scroll-zoom for each subplot (individual zoom)
|
316 |
+
fig.update_layout(
|
317 |
+
xaxis=dict(fixedrange=False),
|
318 |
+
yaxis=dict(fixedrange=False),
|
319 |
+
)
|
320 |
+
for i in range(1, rows * cols + 1):
|
321 |
+
fig.layout[f'xaxis{i}'].update(fixedrange=False)
|
322 |
+
fig.layout[f'yaxis{i}'].update(fixedrange=False)
|
323 |
+
st.plotly_chart(fig, use_container_width=True, config={"scrollZoom": True})
|
324 |
+
|
325 |
+
def manual_trade(self):
|
326 |
+
# Move all user inputs to the sidebar
|
327 |
+
with st.sidebar:
|
328 |
+
st.header("Manual Trade")
|
329 |
+
symbol = st.text_input('Enter stock symbol')
|
330 |
+
qty = int(st.number_input('Enter quantity'))
|
331 |
+
action = st.selectbox('Action', ['Buy', 'Sell'])
|
332 |
+
if st.button('Execute'):
|
333 |
+
if action == 'Buy':
|
334 |
+
order = self.alpaca.buy(symbol, qty)
|
335 |
+
else:
|
336 |
+
order = self.alpaca.sell(symbol, qty)
|
337 |
+
if order:
|
338 |
+
st.success(f"Order executed: {action} {qty} shares of {symbol}")
|
339 |
+
else:
|
340 |
+
st.error("Order failed")
|
341 |
+
st.header("Portfolio")
|
342 |
+
st.write("Cash Balance:")
|
343 |
+
st.write(self.alpaca.getCash())
|
344 |
+
st.write("Holdings:")
|
345 |
+
st.write(self.alpaca.getHoldings())
|
346 |
+
st.write("Recent Trades:")
|
347 |
+
st.write(pd.DataFrame(self.alpaca.trades))
|
348 |
+
|
349 |
+
def auto_trade_based_on_sentiment(self, sentiment):
|
350 |
+
# Add company name to each action
|
351 |
+
actions = []
|
352 |
+
symbol_to_name = self.analyzer.symbol_to_name
|
353 |
+
for symbol, sentiment_value in sentiment.items():
|
354 |
+
action = None
|
355 |
+
if sentiment_value == 'Positive':
|
356 |
+
order = self.alpaca.buy(symbol, 1)
|
357 |
+
action = 'Buy'
|
358 |
+
elif sentiment_value == 'Negative':
|
359 |
+
order = self.alpaca.sell(symbol, 1)
|
360 |
+
action = 'Sell'
|
361 |
+
else:
|
362 |
+
order = None
|
363 |
+
action = 'Hold'
|
364 |
+
actions.append({
|
365 |
+
'symbol': symbol,
|
366 |
+
'company_name': symbol_to_name.get(symbol, ''),
|
367 |
+
'sentiment': sentiment_value,
|
368 |
+
'action': action
|
369 |
+
})
|
370 |
+
self.auto_trade_log = actions
|
371 |
+
return actions
|
372 |
+
|
373 |
+
def background_auto_trade(app):
|
374 |
+
# This function runs in a background thread and does not require a TTY.
|
375 |
+
# The warning "tcgetpgrp failed: Not a tty" is harmless and can be ignored.
|
376 |
+
# It is likely caused by the environment in which the script is running (e.g., Streamlit, Docker, or a notebook).
|
377 |
+
# No code changes are needed for this warning.
|
378 |
+
while True:
|
379 |
+
sentiment = app.sentiment.get_news_sentiment(app.analyzer.symbols)
|
380 |
+
actions = []
|
381 |
+
for symbol, sentiment_value in sentiment.items():
|
382 |
+
action = None
|
383 |
+
if sentiment_value == 'Positive':
|
384 |
+
order = app.alpaca.buy(symbol, 1)
|
385 |
+
action = 'Buy'
|
386 |
+
elif sentiment_value == 'Negative':
|
387 |
+
order = app.alpaca.sell(symbol, 1)
|
388 |
+
action = 'Sell'
|
389 |
+
else:
|
390 |
+
order = None
|
391 |
+
action = 'Hold'
|
392 |
+
actions.append({
|
393 |
+
'symbol': symbol,
|
394 |
+
'sentiment': sentiment_value,
|
395 |
+
'action': action
|
396 |
+
})
|
397 |
+
# Append to log file instead of overwriting
|
398 |
+
log_entry = {
|
399 |
+
"timestamp": datetime.now().isoformat(),
|
400 |
+
"actions": actions,
|
401 |
+
"sentiment": sentiment
|
402 |
+
}
|
403 |
+
try:
|
404 |
+
if os.path.exists(AUTO_TRADE_LOG_PATH):
|
405 |
+
with open(AUTO_TRADE_LOG_PATH, "r") as f:
|
406 |
+
log_data = json.load(f)
|
407 |
+
else:
|
408 |
+
log_data = []
|
409 |
+
except Exception:
|
410 |
+
log_data = []
|
411 |
+
log_data.append(log_entry)
|
412 |
+
with open(AUTO_TRADE_LOG_PATH, "w") as f:
|
413 |
+
json.dump(log_data, f)
|
414 |
+
time.sleep(AUTO_TRADE_INTERVAL)
|
415 |
+
|
416 |
+
def load_auto_trade_log():
|
417 |
+
try:
|
418 |
+
with open(AUTO_TRADE_LOG_PATH, "r") as f:
|
419 |
+
return json.load(f)
|
420 |
+
except Exception:
|
421 |
+
return None
|
422 |
+
|
423 |
+
# Replace deprecated st.experimental_set_query_params with st.query_params
|
424 |
+
st.query_params() # This is a no-op but ensures Streamlit doesn't rerun due to query params
|
425 |
+
|
426 |
+
class TradingApp:
|
427 |
+
def __init__(self):
|
428 |
+
self.alpaca = AlpacaTrader(st.secrets['ALPACA_API_KEY'], st.secrets['ALPACA_SECRET_KEY'], 'https://paper-api.alpaca.markets')
|
429 |
+
self.sentiment = NewsSentiment(st.secrets['NEWS_API_KEY'])
|
430 |
+
self.analyzer = StockAnalyzer(self.alpaca)
|
431 |
+
self.data = self.analyzer.get_historical_data(self.analyzer.symbols)
|
432 |
+
self.auto_trade_log = [] # Store automatic trade actions
|
433 |
+
|
434 |
+
def display_charts(self):
|
435 |
+
# Dynamically adjust columns based on number of stocks and available width
|
436 |
+
symbols = list(self.data.keys())
|
437 |
+
symbol_to_name = self.analyzer.symbol_to_name
|
438 |
+
n = len(symbols)
|
439 |
+
|
440 |
# Calculate columns based on n for best fit
|
441 |
if n <= 3:
|
442 |
cols = n
|
|
|
587 |
# Add this at the top after imports to suppress Streamlit reruns on widget interaction
|
588 |
st.experimental_set_query_params() # This is a no-op but ensures Streamlit doesn't rerun due to query params
|
589 |
|
590 |
+
def get_market_times(alpaca_api):
|
591 |
+
try:
|
592 |
+
clock = alpaca_api.get_clock()
|
593 |
+
is_open = clock.is_open
|
594 |
+
now = pd.Timestamp(clock.timestamp).tz_convert('America/New_York')
|
595 |
+
next_close = pd.Timestamp(clock.next_close).tz_convert('America/New_York')
|
596 |
+
next_open = pd.Timestamp(clock.next_open).tz_convert('America/New_York')
|
597 |
+
return is_open, now, next_open, next_close
|
598 |
+
except Exception as e:
|
599 |
+
logger.error(f"Error fetching market times: {e}")
|
600 |
+
return None, None, None, None
|
601 |
+
|
602 |
def main():
|
603 |
st.title("Stock Trading Application")
|
604 |
|
|
|
618 |
thread.start()
|
619 |
st.session_state["auto_trade_thread_started"] = True
|
620 |
|
621 |
+
# Dynamic market clock
|
622 |
+
is_open, now, next_open, next_close = get_market_times(app.alpaca.alpaca)
|
623 |
+
market_status = "🟢 Market is OPEN" if is_open else "🔴 Market is CLOSED"
|
624 |
+
st.markdown(f"### {market_status}")
|
625 |
+
if now is not None:
|
626 |
+
st.markdown(f"**Current time (ET):** {now.strftime('%Y-%m-%d %H:%M:%S')}")
|
627 |
+
if is_open and next_close is not None:
|
628 |
+
st.markdown(f"**Market closes at:** {next_close.strftime('%Y-%m-%d %H:%M:%S')} ET")
|
629 |
+
# Show countdown to close
|
630 |
+
seconds_left = int((next_close - now).total_seconds())
|
631 |
+
st.markdown(f"**Time until close:** {pd.to_timedelta(seconds_left, unit='s')}")
|
632 |
+
elif not is_open and next_open is not None:
|
633 |
+
st.markdown(f"**Market opens at:** {next_open.strftime('%Y-%m-%d %H:%M:%S')} ET")
|
634 |
+
# Show countdown to open
|
635 |
+
seconds_left = int((next_open - now).total_seconds())
|
636 |
+
st.markdown(f"**Time until open:** {pd.to_timedelta(seconds_left, unit='s')}")
|
637 |
+
|
638 |
+
# Add auto-refresh for the clock every 5 seconds
|
639 |
+
st.experimental_rerun()
|
640 |
+
time.sleep(5)
|
641 |
|
642 |
# User inputs and portfolio are now in the sidebar
|
643 |
app.manual_trade()
|