Benjamin Consolvo commited on
Commit
3cb68d0
·
1 Parent(s): 3fba644

ui updates

Browse files
Files changed (1) hide show
  1. app.py +242 -434
app.py CHANGED
@@ -1,7 +1,5 @@
1
  import streamlit as st
2
- st.set_page_config(layout="wide")
3
  import yfinance as yf
4
- # import alpaca as tradeapi
5
  import alpaca_trade_api as alpaca
6
  from newsapi import NewsApiClient
7
  from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
@@ -18,16 +16,18 @@ import plotly.graph_objs as go
18
  from sklearn.preprocessing import minmax_scale
19
  from plotly.subplots import make_subplots
20
 
21
- # Configure logging
22
- logging.basicConfig(level=logging.INFO)
 
 
 
 
23
  logger = logging.getLogger(__name__)
24
 
25
- AUTO_TRADE_LOG_PATH = "auto_trade_log.json" # Path to store auto trade log
26
-
27
- # The trading history events are saved in the file "auto_trade_log.json"
28
- # This file is created and updated in the current working directory where you run your Streamlit app.
29
-
30
  AUTO_TRADE_INTERVAL = 10800 # Interval in seconds (e.g., 10800 seconds = 3 hours)
 
31
 
32
  class AlpacaTrader:
33
  def __init__(self, API_KEY, API_SECRET, BASE_URL):
@@ -39,7 +39,7 @@ class AlpacaTrader:
39
  def get_market_status(self):
40
  return self.alpaca.get_clock().is_open
41
 
42
- def buy(self, symbol, qty):
43
  try:
44
  # Ensure at least $1000 in cash before buying
45
  account = self.alpaca.get_account()
@@ -48,13 +48,27 @@ class AlpacaTrader:
48
  logger.warning(f"Low cash: (${cash_balance}) to buy {symbol}. Minimum $1000 required.")
49
  return None
50
  order = self.alpaca.submit_order(symbol=symbol, qty=qty, side='buy', type='market', time_in_force='day')
51
- logger.info(f"Bought {qty} shares of {symbol}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  return order
53
  except Exception as e:
54
  logger.error(f"Error buying {symbol}: {e}")
55
  return None
56
 
57
- def sell(self, symbol, qty):
58
  # Check if position exists and has enough quantity before attempting to sell
59
  positions = {p.symbol: float(p.qty) for p in self.alpaca.list_positions()}
60
  if symbol not in positions:
@@ -65,7 +79,21 @@ class AlpacaTrader:
65
  return None
66
  try:
67
  order = self.alpaca.submit_order(symbol=symbol, qty=qty, side='sell', type='market', time_in_force='day')
68
- logger.info(f"Sold {qty} shares of {symbol}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  return order
70
  except Exception as e:
71
  logger.error(f"Error selling {symbol}: {e}")
@@ -74,7 +102,9 @@ class AlpacaTrader:
74
  def getHoldings(self):
75
  positions = self.alpaca.list_positions()
76
  for position in positions:
77
- self.holdings[position.symbol] = position.market_value
 
 
78
  return self.holdings
79
 
80
  def getCash(self):
@@ -105,7 +135,9 @@ class NewsSentiment:
105
 
106
  def get_news_sentiment(self, symbols):
107
  '''
 
108
  ERROR:__main__:Error getting news for APLD: {'status': 'error', 'code': 'rateLimited', 'message': 'You have made too many requests recently. Developer accounts are limited to 100 requests over a 24 hour period (50 requests available every 12 hours). Please upgrade to a paid plan if you need more requests.'}
 
109
  '''
110
  sentiment = {}
111
  for symbol in symbols:
@@ -170,7 +202,8 @@ class StockAnalyzer:
170
  }
171
  }
172
  else:
173
- logger.warning(f"No bar data for symbol: {symbol}")
 
174
  bars_data[symbol] = {'bar_data': None}
175
  except Exception as e:
176
  logger.warning(f"Error fetching bars in batch: {e}")
@@ -240,7 +273,7 @@ class StockAnalyzer:
240
  if info['bar_data'] is not None
241
  }
242
  top_volume_stocks = sorted(volume_data, key=volume_data.get, reverse=True)[:num_stocks]
243
- print(f'top_volume_stocks = {top_volume_stocks}')
244
 
245
  return top_volume_stocks
246
  except Exception as e:
@@ -272,19 +305,8 @@ class TradingApp:
272
  symbols = list(self.data.keys())
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
@@ -327,201 +349,112 @@ class TradingApp:
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
- class TradingApp:
424
- def __init__(self):
425
- self.alpaca = AlpacaTrader(st.secrets['ALPACA_API_KEY'], st.secrets['ALPACA_SECRET_KEY'], 'https://paper-api.alpaca.markets')
426
- self.sentiment = NewsSentiment(st.secrets['NEWS_API_KEY'])
427
- self.analyzer = StockAnalyzer(self.alpaca)
428
- self.data = self.analyzer.get_historical_data(self.analyzer.symbols)
429
- self.auto_trade_log = [] # Store automatic trade actions
430
-
431
- def display_charts(self):
432
- # Dynamically adjust columns based on number of stocks and available width
433
- symbols = list(self.data.keys())
434
- symbol_to_name = self.analyzer.symbol_to_name
435
- n = len(symbols)
436
-
437
- # Calculate columns based on n for best fit
438
- if n <= 3:
439
- cols = n
440
- elif n <= 6:
441
- cols = 3
442
- elif n <= 8:
443
- cols = 4
444
- elif n <= 12:
445
- cols = 4
446
- else:
447
- cols = 5
448
-
449
- rows = (n + cols - 1) // cols
450
- subplot_titles = [
451
- f"{symbol} - {symbol_to_name.get(symbol, '')}" for symbol in symbols
452
- ]
453
- fig = make_subplots(rows=rows, cols=cols, subplot_titles=subplot_titles)
454
- for idx, symbol in enumerate(symbols):
455
- df = self.data[symbol]
456
- if not df.empty:
457
- row = idx // cols + 1
458
- col = idx % cols + 1
459
- fig.add_trace(
460
- go.Scatter(
461
- x=df.index,
462
- y=df['Close'],
463
- mode='lines',
464
- name=symbol,
465
- hovertemplate=f"%{{x}}<br>{symbol}: %{{y:.2f}}<extra></extra>"
466
- ),
467
- row=row,
468
- col=col
469
- )
470
- fig.update_layout(
471
- title="Top Volume Stocks - Price Charts (Since 2023)",
472
- height=max(400 * rows, 600),
473
- showlegend=False,
474
- dragmode=False,
475
- )
476
- # Enable scroll-zoom for each subplot (individual zoom)
477
- fig.update_layout(
478
- xaxis=dict(fixedrange=False),
479
- yaxis=dict(fixedrange=False),
480
- )
481
- for i in range(1, rows * cols + 1):
482
- fig.layout[f'xaxis{i}'].update(fixedrange=False)
483
- fig.layout[f'yaxis{i}'].update(fixedrange=False)
484
- st.plotly_chart(fig, use_container_width=True, config={"scrollZoom": True})
485
 
486
- def manual_trade(self):
487
- # Move all user inputs to the sidebar
488
- with st.sidebar:
489
- st.header("Manual Trade")
490
- symbol = st.text_input('Enter stock symbol')
491
- qty = int(st.number_input('Enter quantity'))
492
  action = st.selectbox('Action', ['Buy', 'Sell'])
493
  if st.button('Execute'):
494
- if action == 'Buy':
495
- order = self.alpaca.buy(symbol, qty)
496
- else:
497
- order = self.alpaca.sell(symbol, qty)
498
- if order:
499
- st.success(f"Order executed: {action} {qty} shares of {symbol}")
 
 
 
 
 
 
 
 
 
 
500
  else:
501
- st.error("Order failed")
502
- st.header("Portfolio")
503
- st.write("Cash Balance:")
504
- st.write(self.alpaca.getCash())
505
- st.write("Holdings:")
506
- st.write(self.alpaca.getHoldings())
507
- st.write("Recent Trades:")
508
- st.write(pd.DataFrame(self.alpaca.trades))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509
 
510
  def auto_trade_based_on_sentiment(self, sentiment):
511
- # Add company name to each action
512
  actions = []
513
  symbol_to_name = self.analyzer.symbol_to_name
514
  for symbol, sentiment_value in sentiment.items():
515
  action = None
 
516
  if sentiment_value == 'Positive':
517
- order = self.alpaca.buy(symbol, 1)
518
  action = 'Buy'
519
  elif sentiment_value == 'Negative':
520
- order = self.alpaca.sell(symbol, 1)
521
  action = 'Sell'
522
  else:
523
  order = None
524
  action = 'Hold'
 
 
 
 
 
 
 
 
 
 
525
  actions.append({
526
  'symbol': symbol,
527
  'company_name': symbol_to_name.get(symbol, ''),
@@ -532,216 +465,81 @@ class TradingApp:
532
  return actions
533
 
534
  def background_auto_trade(app):
535
- # This function runs in a background thread and does not require a TTY.
536
- # The warning "tcgetpgrp failed: Not a tty" is harmless and can be ignored.
537
- # It is likely caused by the environment in which the script is running (e.g., Streamlit, Docker, or a notebook).
538
- # No code changes are needed for this warning.
539
  while True:
540
  sentiment = app.sentiment.get_news_sentiment(app.analyzer.symbols)
 
541
  actions = []
542
  for symbol, sentiment_value in sentiment.items():
543
  action = None
 
544
  if sentiment_value == 'Positive':
545
- order = app.alpaca.buy(symbol, 1)
546
  action = 'Buy'
547
  elif sentiment_value == 'Negative':
548
- order = app.alpaca.sell(symbol, 1)
549
  action = 'Sell'
550
  else:
551
  order = None
552
  action = 'Hold'
553
- actions.append({
554
- 'symbol': symbol,
555
- 'sentiment': sentiment_value,
556
- 'action': action
557
- })
558
- # Append to log file instead of overwriting
559
- log_entry = {
560
- "timestamp": datetime.now().isoformat(),
561
- "actions": actions,
562
- "sentiment": sentiment
563
- }
564
- try:
565
- if os.path.exists(AUTO_TRADE_LOG_PATH):
566
- with open(AUTO_TRADE_LOG_PATH, "r") as f:
567
- log_data = json.load(f)
568
- else:
569
- log_data = []
570
- except Exception:
571
- log_data = []
572
- log_data.append(log_entry)
573
- with open(AUTO_TRADE_LOG_PATH, "w") as f:
574
- json.dump(log_data, f)
575
- time.sleep(AUTO_TRADE_INTERVAL)
576
-
577
- def load_auto_trade_log():
578
- try:
579
- with open(AUTO_TRADE_LOG_PATH, "r") as f:
580
- return json.load(f)
581
- except Exception:
582
- return None
583
-
584
- class TradingApp:
585
- def __init__(self):
586
- self.alpaca = AlpacaTrader(st.secrets['ALPACA_API_KEY'], st.secrets['ALPACA_SECRET_KEY'], 'https://paper-api.alpaca.markets')
587
- self.sentiment = NewsSentiment(st.secrets['NEWS_API_KEY'])
588
- self.analyzer = StockAnalyzer(self.alpaca)
589
- self.data = self.analyzer.get_historical_data(self.analyzer.symbols)
590
- self.auto_trade_log = [] # Store automatic trade actions
591
-
592
- def display_charts(self):
593
- # Dynamically adjust columns based on number of stocks and available width
594
- symbols = list(self.data.keys())
595
- symbol_to_name = self.analyzer.symbol_to_name
596
- n = len(symbols)
597
-
598
- # Calculate columns based on n for best fit
599
- if n <= 3:
600
- cols = n
601
- elif n <= 6:
602
- cols = 3
603
- elif n <= 8:
604
- cols = 4
605
- elif n <= 12:
606
- cols = 4
607
- else:
608
- cols = 5
609
 
610
- rows = (n + cols - 1) // cols
611
- subplot_titles = [
612
- f"{symbol} - {symbol_to_name.get(symbol, '')}" for symbol in symbols
613
- ]
614
- fig = make_subplots(rows=rows, cols=cols, subplot_titles=subplot_titles)
615
- for idx, symbol in enumerate(symbols):
616
- df = self.data[symbol]
617
- if not df.empty:
618
- row = idx // cols + 1
619
- col = idx % cols + 1
620
- fig.add_trace(
621
- go.Scatter(
622
- x=df.index,
623
- y=df['Close'],
624
- mode='lines',
625
- name=symbol,
626
- hovertemplate=f"%{{x}}<br>{symbol}: %{{y:.2f}}<extra></extra>"
627
- ),
628
- row=row,
629
- col=col
630
- )
631
- fig.update_layout(
632
- title="Top Volume Stocks - Price Charts (Since 2023)",
633
- height=max(400 * rows, 600),
634
- showlegend=False,
635
- dragmode=False,
636
- )
637
- # Enable scroll-zoom for each subplot (individual zoom)
638
- fig.update_layout(
639
- xaxis=dict(fixedrange=False),
640
- yaxis=dict(fixedrange=False),
641
- )
642
- for i in range(1, rows * cols + 1):
643
- fig.layout[f'xaxis{i}'].update(fixedrange=False)
644
- fig.layout[f'yaxis{i}'].update(fixedrange=False)
645
- st.plotly_chart(fig, use_container_width=True, config={"scrollZoom": True})
646
-
647
- def manual_trade(self):
648
- # Move all user inputs to the sidebar
649
- with st.sidebar:
650
- st.header("Manual Trade")
651
- symbol = st.text_input('Enter stock symbol')
652
- qty = int(st.number_input('Enter quantity'))
653
- action = st.selectbox('Action', ['Buy', 'Sell'])
654
- if st.button('Execute'):
655
- if action == 'Buy':
656
- order = self.alpaca.buy(symbol, qty)
657
  else:
658
- order = self.alpaca.sell(symbol, qty)
659
- if order:
660
- st.success(f"Order executed: {action} {qty} shares of {symbol}")
661
- else:
662
- st.error("Order failed")
663
- st.header("Portfolio")
664
- st.write("Cash Balance:")
665
- st.write(self.alpaca.getCash())
666
- st.write("Holdings:")
667
- st.write(self.alpaca.getHoldings())
668
- st.write("Recent Trades:")
669
- st.write(pd.DataFrame(self.alpaca.trades))
670
 
671
- def auto_trade_based_on_sentiment(self, sentiment):
672
- # Add company name to each action
673
- actions = []
674
- symbol_to_name = self.analyzer.symbol_to_name
675
- for symbol, sentiment_value in sentiment.items():
676
- action = None
677
- if sentiment_value == 'Positive':
678
- order = self.alpaca.buy(symbol, 1)
679
- action = 'Buy'
680
- elif sentiment_value == 'Negative':
681
- order = self.alpaca.sell(symbol, 1)
682
- action = 'Sell'
683
- else:
684
- order = None
685
- action = 'Hold'
686
  actions.append({
687
  'symbol': symbol,
688
  'company_name': symbol_to_name.get(symbol, ''),
689
  'sentiment': sentiment_value,
690
  'action': action
691
  })
692
- self.auto_trade_log = actions
693
- return actions
694
-
695
- def background_auto_trade(app):
696
- # This function runs in a background thread and does not require a TTY.
697
- # The warning "tcgetpgrp failed: Not a tty" is harmless and can be ignored.
698
- # It is likely caused by the environment in which the script is running (e.g., Streamlit, Docker, or a notebook).
699
- # No code changes are needed for this warning.
700
- while True:
701
- sentiment = app.sentiment.get_news_sentiment(app.analyzer.symbols)
702
- actions = []
703
- for symbol, sentiment_value in sentiment.items():
704
- action = None
705
- if sentiment_value == 'Positive':
706
- order = app.alpaca.buy(symbol, 1)
707
- action = 'Buy'
708
- elif sentiment_value == 'Negative':
709
- order = app.alpaca.sell(symbol, 1)
710
- action = 'Sell'
711
- else:
712
- order = None
713
- action = 'Hold'
714
- actions.append({
715
- 'symbol': symbol,
716
- 'sentiment': sentiment_value,
717
- 'action': action
718
- })
719
- # Append to log file instead of overwriting
720
  log_entry = {
721
  "timestamp": datetime.now().isoformat(),
722
  "actions": actions,
723
  "sentiment": sentiment
724
  }
725
- try:
726
- if os.path.exists(AUTO_TRADE_LOG_PATH):
727
- with open(AUTO_TRADE_LOG_PATH, "r") as f:
728
- log_data = json.load(f)
729
- else:
730
- log_data = []
731
- except Exception:
732
- log_data = []
733
- log_data.append(log_entry)
734
- with open(AUTO_TRADE_LOG_PATH, "w") as f:
735
- json.dump(log_data, f)
736
  time.sleep(AUTO_TRADE_INTERVAL)
737
 
738
- def load_auto_trade_log():
739
- try:
740
- with open(AUTO_TRADE_LOG_PATH, "r") as f:
741
- return json.load(f)
742
- except Exception:
743
- return None
744
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
745
 
746
  def get_market_times(alpaca_api):
747
  try:
@@ -768,51 +566,85 @@ def main():
768
  st.session_state["app_instance"] = TradingApp()
769
  app = st.session_state["app_instance"]
770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
771
  # Only start the background thread once
772
  if "auto_trade_thread_started" not in st.session_state:
773
  thread = threading.Thread(target=background_auto_trade, args=(app,), daemon=True)
774
  thread.start()
775
  st.session_state["auto_trade_thread_started"] = True
776
 
777
- # Static market clock (no auto-refresh)
778
- is_open, now, next_open, next_close = get_market_times(app.alpaca.alpaca)
779
- market_status = "🟢 Market is OPEN" if is_open else "🔴 Market is CLOSED"
780
- st.markdown(f"### {market_status}")
781
- if now is not None:
782
- st.markdown(f"**Current time (ET):** {now.strftime('%Y-%m-%d %H:%M:%S')}")
783
- if is_open and next_close is not None:
784
- st.markdown(f"**Market closes at:** {next_close.strftime('%Y-%m-%d %H:%M:%S')} ET")
785
- # Show countdown to close
786
- seconds_left = int((next_close - now).total_seconds())
787
- st.markdown(f"**Time until close:** {pd.to_timedelta(seconds_left, unit='s')}")
788
- elif not is_open and next_open is not None:
789
- st.markdown(f"**Market opens at:** {next_open.strftime('%Y-%m-%d %H:%M:%S')} ET")
790
- # Show countdown to open
791
- seconds_left = int((next_open - now).total_seconds())
792
- st.markdown(f"**Time until open:** {pd.to_timedelta(seconds_left, unit='s')}")
793
-
794
- # User inputs and portfolio are now in the sidebar
795
- app.manual_trade()
796
-
797
  # Main area: plots and data
 
798
  app.display_charts()
799
 
800
  # Read and display latest auto-trade actions
801
  st.write("Automatic Trading Actions Based on Sentiment (background):")
802
- auto_trade_log = load_auto_trade_log()
803
  if auto_trade_log:
804
  # Show the most recent entry
805
  last_entry = auto_trade_log[-1]
806
  st.write(f"Last checked: {last_entry['timestamp']}")
807
  df = pd.DataFrame(last_entry["actions"])
808
- # Reorder columns for clarity
809
  if "company_name" in df.columns:
810
  df = df[["symbol", "company_name", "sentiment", "action"]]
811
  st.dataframe(df)
812
  st.write("Sentiment Analysis (latest):")
813
  st.write(last_entry["sentiment"])
814
 
815
- # Plot buy/sell actions over time (aggregate for all symbols)
816
  st.write("Auto-Trading History (Buy/Sell Actions Over Time):")
817
  history = []
818
  for entry in auto_trade_log:
@@ -828,36 +660,12 @@ def main():
828
  hist_df = pd.DataFrame(history)
829
  if not hist_df.empty:
830
  hist_df["timestamp"] = pd.to_datetime(hist_df["timestamp"])
831
- # Pivot to get Buy/Sell counts per symbol over time
832
- # Avoid FutureWarning by explicitly converting to float after replace
833
- hist_df["action_value"] = hist_df["action"].replace({"Buy": 1, "Sell": -1})
834
- hist_df["action_value"] = hist_df["action_value"].astype(float)
835
  pivot = hist_df.pivot_table(index="timestamp", columns="symbol", values="action_value", aggfunc="sum")
836
  st.line_chart(pivot.fillna(0))
837
  else:
838
  st.info("Waiting for first background auto-trade run...")
839
 
840
- # Explanation:
841
- # In Alpaca:
842
- # - 'cash' is the actual cash available in your account (uninvested funds).
843
- # - 'buying_power' is the total amount you can use to buy securities, which may be higher than cash if you have margin enabled.
844
- # For a cash account, buying_power == cash.
845
- # For a margin account, buying_power can be up to 2x (or 4x for day trading) your cash, depending on regulations and your account status.
846
-
847
- # Example usage:
848
- # account = alpaca.get_account()
849
- # cash_balance = account.cash
850
- # buying_power = account.buying_power
851
-
852
- # Note:
853
- # To disable margin on your Alpaca paper account, you must set your account type to "cash" instead of "margin".
854
- # This cannot be changed via the API or code. You must:
855
- # 1. Log in to your Alpaca dashboard at https://app.alpaca.markets/
856
- # 2. Go to "Paper Trading" > "Settings"
857
- # 3. Set the account type to "Cash" (not "Margin")
858
- # 4. If you do not see this option, you may need to reset your paper account or contact Alpaca support.
859
-
860
- # There is no programmatic/API way to change the margin setting for a paper account.
861
 
862
  if __name__ == "__main__":
863
  main()
 
1
  import streamlit as st
 
2
  import yfinance as yf
 
3
  import alpaca_trade_api as alpaca
4
  from newsapi import NewsApiClient
5
  from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
 
16
  from sklearn.preprocessing import minmax_scale
17
  from plotly.subplots import make_subplots
18
 
19
+ # Configure logging with timestamps
20
+ logging.basicConfig(
21
+ level=logging.INFO,
22
+ format="%(asctime)s - %(levelname)s - %(message)s",
23
+ datefmt="%Y-%m-%d %H:%M:%S"
24
+ )
25
  logger = logging.getLogger(__name__)
26
 
27
+ # Use session state keys instead of file paths
28
+ AUTO_TRADE_LOG_KEY = "auto_trade_log" # Session state key for trade log
 
 
 
29
  AUTO_TRADE_INTERVAL = 10800 # Interval in seconds (e.g., 10800 seconds = 3 hours)
30
+ st.set_page_config(layout="wide")
31
 
32
  class AlpacaTrader:
33
  def __init__(self, API_KEY, API_SECRET, BASE_URL):
 
39
  def get_market_status(self):
40
  return self.alpaca.get_clock().is_open
41
 
42
+ def buy(self, symbol, qty, reason=None):
43
  try:
44
  # Ensure at least $1000 in cash before buying
45
  account = self.alpaca.get_account()
 
48
  logger.warning(f"Low cash: (${cash_balance}) to buy {symbol}. Minimum $1000 required.")
49
  return None
50
  order = self.alpaca.submit_order(symbol=symbol, qty=qty, side='buy', type='market', time_in_force='day')
51
+ if reason:
52
+ logger.info(f"Bought {qty} shares of {symbol} [Reason: {reason}]")
53
+ else:
54
+ logger.info(f"Bought {qty} shares of {symbol}")
55
+
56
+ # Record the trade
57
+ if order:
58
+ self.trades.append({
59
+ 'symbol': symbol,
60
+ 'qty': qty,
61
+ 'action': 'Buy',
62
+ 'time': datetime.now(),
63
+ 'reason': reason
64
+ })
65
+
66
  return order
67
  except Exception as e:
68
  logger.error(f"Error buying {symbol}: {e}")
69
  return None
70
 
71
+ def sell(self, symbol, qty, reason=None):
72
  # Check if position exists and has enough quantity before attempting to sell
73
  positions = {p.symbol: float(p.qty) for p in self.alpaca.list_positions()}
74
  if symbol not in positions:
 
79
  return None
80
  try:
81
  order = self.alpaca.submit_order(symbol=symbol, qty=qty, side='sell', type='market', time_in_force='day')
82
+ if reason:
83
+ logger.info(f"Sold {qty} shares of {symbol} [Reason: {reason}]")
84
+ else:
85
+ logger.info(f"Sold {qty} shares of {symbol}")
86
+
87
+ # Record the trade
88
+ if order:
89
+ self.trades.append({
90
+ 'symbol': symbol,
91
+ 'qty': qty,
92
+ 'action': 'Sell',
93
+ 'time': datetime.now(),
94
+ 'reason': reason
95
+ })
96
+
97
  return order
98
  except Exception as e:
99
  logger.error(f"Error selling {symbol}: {e}")
 
102
  def getHoldings(self):
103
  positions = self.alpaca.list_positions()
104
  for position in positions:
105
+ self.holdings[position.symbol] = float(position.market_value)
106
+
107
+ # Return holdings as a dictionary for internal use
108
  return self.holdings
109
 
110
  def getCash(self):
 
135
 
136
  def get_news_sentiment(self, symbols):
137
  '''
138
+ The News API has a rate limit of 100 requests per day for free accounts. If you exceed this limit, you'll get a rateLimited error. Example error message:
139
  ERROR:__main__:Error getting news for APLD: {'status': 'error', 'code': 'rateLimited', 'message': 'You have made too many requests recently. Developer accounts are limited to 100 requests over a 24 hour period (50 requests available every 12 hours). Please upgrade to a paid plan if you need more requests.'}
140
+
141
  '''
142
  sentiment = {}
143
  for symbol in symbols:
 
202
  }
203
  }
204
  else:
205
+ # Only log at debug level to avoid spamming warnings for missing bar data
206
+ logger.debug(f"No bar data for symbol: {symbol}")
207
  bars_data[symbol] = {'bar_data': None}
208
  except Exception as e:
209
  logger.warning(f"Error fetching bars in batch: {e}")
 
273
  if info['bar_data'] is not None
274
  }
275
  top_volume_stocks = sorted(volume_data, key=volume_data.get, reverse=True)[:num_stocks]
276
+ logger.info(f'top_volume_stocks = {top_volume_stocks}')
277
 
278
  return top_volume_stocks
279
  except Exception as e:
 
305
  symbols = list(self.data.keys())
306
  symbol_to_name = self.analyzer.symbol_to_name
307
  n = len(symbols)
 
308
  # Calculate columns based on n for best fit
309
+ cols = 3
 
 
 
 
 
 
 
 
 
 
310
  rows = (n + cols - 1) // cols
311
  subplot_titles = [
312
  f"{symbol} - {symbol_to_name.get(symbol, '')}" for symbol in symbols
 
349
  with st.sidebar:
350
  st.header("Manual Trade")
351
  symbol = st.text_input('Enter stock symbol')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352
 
353
+ # Fetch the current stock price dynamically using Alpaca's API
354
+ def get_stock_price(symbol):
355
+ try:
356
+ if not symbol:
357
+ return None
358
+ last_trade = self.alpaca.alpaca.get_latest_trade(symbol)
359
+ return last_trade.price
360
+ except Exception as e:
361
+ logger.error(f"Error fetching stock price for {symbol}: {e}")
362
+ return None
363
+
364
+ # Update stock price when a new symbol is entered
365
+ if symbol:
366
+ if "stock_price" not in st.session_state or st.session_state.get("last_symbol") != symbol:
367
+ st.session_state["stock_price"] = get_stock_price(symbol)
368
+ st.session_state["last_symbol"] = symbol
369
+
370
+ stock_price = st.session_state.get("stock_price")
371
+ # Explicitly display the stock price below the input field
372
+ if stock_price is not None:
373
+ st.write(f"Current stock price for {symbol.upper()}: ${stock_price:,.2f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  else:
375
+ st.write("Enter a valid stock symbol to see the price.")
376
+
377
+ # Allow user to enter either quantity or amount
378
+ trade_option = st.radio("Trade Option", ["Enter Quantity", "Enter Amount"])
379
+ qty = st.number_input('Enter quantity', min_value=0.0, step=0.01, value=0.0) if trade_option == "Enter Quantity" else None
380
+ amount = st.number_input('Enter amount ($)', min_value=0.0, step=0.01, value=0.0) if trade_option == "Enter Amount" else None
381
+
382
+ # Dynamically calculate the other field
383
+ if stock_price:
384
+ if trade_option == "Enter Quantity" and qty:
385
+ amount = qty * stock_price
386
+ st.write(f"Calculated Amount: ${amount:,.2f}")
387
+ elif trade_option == "Enter Amount" and amount:
388
+ qty = float(amount / stock_price)
389
+ st.write(f"Calculated Quantity: {qty:,.2f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
 
 
 
 
 
 
 
391
  action = st.selectbox('Action', ['Buy', 'Sell'])
392
  if st.button('Execute'):
393
+ if stock_price and qty:
394
+ is_market_open = self.alpaca.get_market_status()
395
+ if action == 'Buy':
396
+ order = self.alpaca.buy(symbol, qty, reason="Manual Trade")
397
+ else:
398
+ order = self.alpaca.sell(symbol, qty, reason="Manual Trade")
399
+
400
+ if order:
401
+ if not is_market_open:
402
+ _, _, next_open, _ = get_market_times(self.alpaca.alpaca)
403
+ next_open_time = next_open.strftime('%Y-%m-%d %H:%M:%S') if next_open else "unknown"
404
+ st.warning(f"Market is currently closed. The {action.lower()} order for {qty} shares of {symbol} has been submitted and will execute when the market opens at {next_open_time}.")
405
+ else:
406
+ st.success(f"Order executed: {action} {qty} shares of {symbol}")
407
+ else:
408
+ st.error("Order failed")
409
  else:
410
+ st.error("Please enter a valid stock symbol and trade details.")
411
+
412
+ # Display portfolio information in the sidebar
413
+ st.header("Alpaca Cash Portfolio")
414
+
415
+ def refresh_portfolio():
416
+ account = self.alpaca.alpaca.get_account()
417
+ portfolio_data = {
418
+ "Metric": ["Cash Balance", "Buying Power", "Equity", "Portfolio Value"],
419
+ "Value": [
420
+ f"${int(float(account.cash)):,.0f}",
421
+ f"${int(float(account.buying_power)):,.0f}",
422
+ f"${int(float(account.equity)):,.0f}",
423
+ f"${int(float(account.portfolio_value)):,.0f}"
424
+ ]
425
+ }
426
+ df = pd.DataFrame(portfolio_data)
427
+ st.table(df.to_dict(orient="records")) # Convert DataFrame to a list of dictionaries
428
+
429
+ refresh_portfolio()
430
+ st.button("Refresh Portfolio", on_click=refresh_portfolio)
431
+ # ...existing code...
432
 
433
  def auto_trade_based_on_sentiment(self, sentiment):
 
434
  actions = []
435
  symbol_to_name = self.analyzer.symbol_to_name
436
  for symbol, sentiment_value in sentiment.items():
437
  action = None
438
+ is_market_open = self.alpaca.get_market_status()
439
  if sentiment_value == 'Positive':
440
+ order = self.alpaca.buy(symbol, 1, reason="Sentiment: Positive")
441
  action = 'Buy'
442
  elif sentiment_value == 'Negative':
443
+ order = self.alpaca.sell(symbol, 1, reason="Sentiment: Negative")
444
  action = 'Sell'
445
  else:
446
  order = None
447
  action = 'Hold'
448
+ logger.info(f"Held {symbol}")
449
+
450
+ if order:
451
+ if not is_market_open:
452
+ _, _, next_open, _ = get_market_times(self.alpaca.alpaca)
453
+ next_open_time = next_open.strftime('%Y-%m-%d %H:%M:%S') if next_open else "unknown"
454
+ logger.warning(f"Market is currently closed. The {action.lower()} order for 1 share of {symbol} has been submitted and will execute when the market opens at {next_open_time}.")
455
+ else:
456
+ logger.info(f"Order executed: {action} 1 share of {symbol}")
457
+
458
  actions.append({
459
  'symbol': symbol,
460
  'company_name': symbol_to_name.get(symbol, ''),
 
465
  return actions
466
 
467
  def background_auto_trade(app):
468
+ # This function runs in a background thread and updates session state
 
 
 
469
  while True:
470
  sentiment = app.sentiment.get_news_sentiment(app.analyzer.symbols)
471
+ symbol_to_name = app.analyzer.symbol_to_name
472
  actions = []
473
  for symbol, sentiment_value in sentiment.items():
474
  action = None
475
+ is_market_open = app.alpaca.get_market_status()
476
  if sentiment_value == 'Positive':
477
+ order = app.alpaca.buy(symbol, 1, reason="Sentiment: Positive")
478
  action = 'Buy'
479
  elif sentiment_value == 'Negative':
480
+ order = app.alpaca.sell(symbol, 1, reason="Sentiment: Negative")
481
  action = 'Sell'
482
  else:
483
  order = None
484
  action = 'Hold'
485
+ logger.info(f"Held {symbol}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486
 
487
+ if order:
488
+ if not is_market_open:
489
+ _, _, next_open, _ = get_market_times(app.alpaca.alpaca)
490
+ next_open_time = next_open.strftime('%Y-%m-%d %H:%M:%S') if next_open else "unknown"
491
+ logger.warning(f"Market is currently closed. The {action.lower()} order for 1 share of {symbol} has been submitted and will execute when the market opens at {next_open_time}.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
492
  else:
493
+ logger.info(f"Order executed: {action} 1 share of {symbol}")
 
 
 
 
 
 
 
 
 
 
 
494
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495
  actions.append({
496
  'symbol': symbol,
497
  'company_name': symbol_to_name.get(symbol, ''),
498
  'sentiment': sentiment_value,
499
  'action': action
500
  })
501
+
502
+ # Create log entry
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503
  log_entry = {
504
  "timestamp": datetime.now().isoformat(),
505
  "actions": actions,
506
  "sentiment": sentiment
507
  }
508
+
509
+ # Update session state - need to use a thread lock to safely update
510
+ if hasattr(threading, "main_thread") and threading.current_thread() is threading.main_thread():
511
+ # Direct update if in main thread
512
+ update_auto_trade_log(log_entry)
513
+ else:
514
+ # Safer to just store the latest entry, which the main thread will pick up
515
+ st.session_state["latest_auto_trade_entry"] = log_entry
516
+
 
 
517
  time.sleep(AUTO_TRADE_INTERVAL)
518
 
519
+ def update_auto_trade_log(log_entry):
520
+ """Update auto trade log in session state"""
521
+ if AUTO_TRADE_LOG_KEY not in st.session_state:
522
+ st.session_state[AUTO_TRADE_LOG_KEY] = []
523
+
524
+ # Append the new entry
525
+ st.session_state[AUTO_TRADE_LOG_KEY].append(log_entry)
526
+
527
+ # Limit size to avoid memory issues (keep last 50 entries)
528
+ if len(st.session_state[AUTO_TRADE_LOG_KEY]) > 50:
529
+ st.session_state[AUTO_TRADE_LOG_KEY] = st.session_state[AUTO_TRADE_LOG_KEY][-50:]
530
+
531
+ def get_auto_trade_log():
532
+ """Get the auto trade log from session state"""
533
+ if AUTO_TRADE_LOG_KEY not in st.session_state:
534
+ st.session_state[AUTO_TRADE_LOG_KEY] = []
535
+
536
+ # Check if we have a new entry from background thread
537
+ if "latest_auto_trade_entry" in st.session_state:
538
+ update_auto_trade_log(st.session_state["latest_auto_trade_entry"])
539
+ # Clear the latest entry after adding it
540
+ del st.session_state["latest_auto_trade_entry"]
541
+
542
+ return st.session_state[AUTO_TRADE_LOG_KEY]
543
 
544
  def get_market_times(alpaca_api):
545
  try:
 
566
  st.session_state["app_instance"] = TradingApp()
567
  app = st.session_state["app_instance"]
568
 
569
+ # Create two columns for market status and portfolio holdings
570
+ col1, col2 = st.columns([1, 1])
571
+
572
+ # Column 1: Market status
573
+ with col1:
574
+ is_open, now, next_open, next_close = get_market_times(app.alpaca.alpaca)
575
+ market_status = "🟢 Market is OPEN" if is_open else "🔴 Market is CLOSED"
576
+ st.markdown(f"### {market_status}")
577
+ if now is not None:
578
+ st.markdown(f"**Current time (ET):** {now.strftime('%Y-%m-%d %H:%M:%S')}")
579
+ if is_open and next_close is not None:
580
+ st.markdown(f"**Market closes at:** {next_close.strftime('%Y-%m-%d %H:%M:%S')} ET")
581
+ seconds_left = int((next_close - now).total_seconds())
582
+ st.markdown(f"**Time until close:** {pd.to_timedelta(seconds_left, unit='s')}")
583
+ elif not is_open and next_open is not None:
584
+ st.markdown(f"**Market opens at:** {next_open.strftime('%Y-%m-%d %H:%M:%S')} ET")
585
+ seconds_left = int((next_open - now).total_seconds())
586
+ st.markdown(f"**Time until open:** {pd.to_timedelta(seconds_left, unit='s')}")
587
+
588
+ # Column 2: Portfolio holdings bar chart
589
+ with col2:
590
+ st.subheader("Portfolio Holdings")
591
+ holdings_container = st.empty() # Create a container for dynamic updates
592
+ def update_holdings():
593
+ holdings = app.alpaca.getHoldings()
594
+ if holdings:
595
+ df = pd.DataFrame(list(holdings.items()), columns=['Ticker', 'Market Value'])
596
+ fig = go.Figure(
597
+ data=[
598
+ go.Bar(
599
+ x=df['Ticker'],
600
+ y=df['Market Value'],
601
+ marker=dict(color=df['Market Value'], colorscale='Viridis'),
602
+ )
603
+ ]
604
+ )
605
+ fig.update_layout(
606
+ xaxis_title="Ticker",
607
+ yaxis_title="$ USD",
608
+ height=400,
609
+ )
610
+ # Use a unique key by appending the current timestamp
611
+ holdings_container.plotly_chart(fig, use_container_width=True, key=f"portfolio_holdings_chart_{time.time()}")
612
+ else:
613
+ holdings_container.info("No holdings to display.")
614
+
615
+ # Periodically refresh the holdings plot
616
+ update_holdings()
617
+ st.button("Refresh Holdings", on_click=update_holdings)
618
+
619
+ # Initialize auto trade log in session state if needed
620
+ if AUTO_TRADE_LOG_KEY not in st.session_state:
621
+ st.session_state[AUTO_TRADE_LOG_KEY] = []
622
+
623
  # Only start the background thread once
624
  if "auto_trade_thread_started" not in st.session_state:
625
  thread = threading.Thread(target=background_auto_trade, args=(app,), daemon=True)
626
  thread.start()
627
  st.session_state["auto_trade_thread_started"] = True
628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
629
  # Main area: plots and data
630
+ app.manual_trade()
631
  app.display_charts()
632
 
633
  # Read and display latest auto-trade actions
634
  st.write("Automatic Trading Actions Based on Sentiment (background):")
635
+ auto_trade_log = get_auto_trade_log()
636
  if auto_trade_log:
637
  # Show the most recent entry
638
  last_entry = auto_trade_log[-1]
639
  st.write(f"Last checked: {last_entry['timestamp']}")
640
  df = pd.DataFrame(last_entry["actions"])
 
641
  if "company_name" in df.columns:
642
  df = df[["symbol", "company_name", "sentiment", "action"]]
643
  st.dataframe(df)
644
  st.write("Sentiment Analysis (latest):")
645
  st.write(last_entry["sentiment"])
646
 
647
+ # Plot buy/sell actions over time
648
  st.write("Auto-Trading History (Buy/Sell Actions Over Time):")
649
  history = []
650
  for entry in auto_trade_log:
 
660
  hist_df = pd.DataFrame(history)
661
  if not hist_df.empty:
662
  hist_df["timestamp"] = pd.to_datetime(hist_df["timestamp"])
663
+ hist_df["action_value"] = hist_df["action"].replace({"Buy": 1, "Sell": -1}).astype(float)
 
 
 
664
  pivot = hist_df.pivot_table(index="timestamp", columns="symbol", values="action_value", aggfunc="sum")
665
  st.line_chart(pivot.fillna(0))
666
  else:
667
  st.info("Waiting for first background auto-trade run...")
668
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
669
 
670
  if __name__ == "__main__":
671
  main()