Benjamin Consolvo commited on
Commit
18cfdec
·
1 Parent(s): 6893212

rm auto trades from ui

Browse files
Files changed (1) hide show
  1. app.py +78 -139
app.py CHANGED
@@ -482,32 +482,30 @@ def background_auto_trade(app):
482
  while True:
483
  start_time = time.time() # Record the start time of the iteration
484
 
485
- try:
486
- sentiment = app.sentiment.get_news_sentiment(app.analyzer.symbols)
487
-
488
- # Use the shared method to execute trades
489
- actions = app._execute_sentiment_trades(sentiment)
490
-
491
- # Create log entry
492
- log_entry = {
493
- "timestamp": datetime.now().isoformat(),
494
- "actions": actions,
495
- "sentiment": sentiment
496
- }
497
-
498
- # Create a temporary file to store the log entry as a workaround for Streamlit session state issues in threads
499
- logger.info(f"Auto-trade completed with {len(actions)} actions")
500
-
501
- # Update the session state directly - this is safer than trying to directly modify st.session_state
502
- # from a background thread
503
- if "pending_auto_trade" not in st.session_state:
504
- st.session_state["pending_auto_trade"] = []
505
-
506
- st.session_state["pending_auto_trade"].append(log_entry)
507
- logger.info(f"Added trade log to pending queue. Queue size: {len(st.session_state.get('pending_auto_trade', []))}")
508
-
509
- except Exception as e:
510
- logger.error(f"Error in background auto-trade: {e}")
511
 
512
  # Calculate the time taken for this iteration
513
  elapsed_time = time.time() - start_time
@@ -520,62 +518,19 @@ def get_auto_trade_log():
520
  """Get the auto trade log from session state."""
521
  if AUTO_TRADE_LOG_KEY not in st.session_state:
522
  st.session_state[AUTO_TRADE_LOG_KEY] = []
523
-
524
- # Process any pending trades
525
- pending_trades = st.session_state.get("pending_auto_trade", [])
526
- if pending_trades:
527
- logger.info(f"Processing {len(pending_trades)} pending trades")
528
-
529
- # Add pending trades to the main log
530
- st.session_state[AUTO_TRADE_LOG_KEY].extend(pending_trades)
531
-
532
- # Clear the pending trades
533
- st.session_state["pending_auto_trade"] = []
534
-
535
- # Limit size to avoid memory issues (keep last 50 entries)
536
- if len(st.session_state[AUTO_TRADE_LOG_KEY]) > 50:
537
- st.session_state[AUTO_TRADE_LOG_KEY] = st.session_state[AUTO_TRADE_LOG_KEY][-50:]
538
-
539
  return st.session_state[AUTO_TRADE_LOG_KEY]
540
 
541
- def add_test_trade_entry():
542
- """Helper function to add a test trade entry to the log."""
543
- # Create a sample log entry
544
- test_entry = {
545
- "timestamp": datetime.now().isoformat(),
546
- "actions": [
547
- {
548
- "symbol": "AAPL",
549
- "company_name": "Apple Inc.",
550
- "sentiment": "Positive",
551
- "action": "Buy"
552
- },
553
- {
554
- "symbol": "MSFT",
555
- "company_name": "Microsoft Corporation",
556
- "sentiment": "Neutral",
557
- "action": "Hold"
558
- },
559
- {
560
- "symbol": "GOOGL",
561
- "company_name": "Alphabet Inc.",
562
- "sentiment": "Negative",
563
- "action": "Sell"
564
- }
565
- ],
566
- "sentiment": {
567
- "AAPL": "Positive",
568
- "MSFT": "Neutral",
569
- "GOOGL": "Negative"
570
- }
571
- }
572
-
573
- # Add to session state
574
- if AUTO_TRADE_LOG_KEY not in st.session_state:
575
- st.session_state[AUTO_TRADE_LOG_KEY] = []
576
-
577
- st.session_state[AUTO_TRADE_LOG_KEY].append(test_entry)
578
- return "Test trade entry added successfully!"
579
 
580
  def main():
581
  st.title("Ben's Stock Trading Application")
@@ -654,72 +609,56 @@ def main():
654
  st.markdown(f"**Time until open:** {pd.to_timedelta(seconds_left, unit='s')}")
655
 
656
 
657
- # Initialize auto trade log in session state if needed
658
- if AUTO_TRADE_LOG_KEY not in st.session_state:
659
- st.session_state[AUTO_TRADE_LOG_KEY] = []
660
 
661
- # Only start the background thread once
662
- if "auto_trade_thread_started" not in st.session_state:
663
- thread = threading.Thread(target=background_auto_trade, args=(app,), daemon=True)
664
- thread.start()
665
- st.session_state["auto_trade_thread_started"] = True
666
 
667
  # Main area: plots and data
668
  app.manual_trade()
669
  app.display_charts()
670
 
671
  # Read and display latest auto-trade actions
672
- st.write("Automatic Trading Actions Based on Sentiment (background):")
673
-
674
- # Add refresh and test buttons side by side
675
- col1, col2 = st.columns(2)
676
- with col1:
677
- if st.button("Refresh Auto-Trade Log"):
678
- st.experimental_rerun() # Force Streamlit to rerun and update the display
679
- with col2:
680
- if st.button("Add Test Trade (Debug)"):
681
- result = add_test_trade_entry()
682
- st.success(result)
683
-
684
- # Get and display auto trade log
685
- auto_trade_log = get_auto_trade_log()
686
- st.write(f"Log entries: {len(auto_trade_log)}")
687
-
688
- # For debugging: Display the size of the log to verify it's being updated
689
- st.write(f"Log entries: {len(auto_trade_log)}")
690
-
691
- if auto_trade_log:
692
- # Show the most recent entry
693
- last_entry = auto_trade_log[-1]
694
- st.write(f"Last checked: {last_entry['timestamp']}")
695
- df = pd.DataFrame(last_entry["actions"])
696
- if "company_name" in df.columns:
697
- df = df[["symbol", "company_name", "sentiment", "action"]]
698
- st.dataframe(df)
699
- st.write("Sentiment Analysis (latest):")
700
- st.write(last_entry["sentiment"])
701
-
702
- # Plot buy/sell actions over time
703
- st.write("Auto-Trading History (Buy/Sell Actions Over Time):")
704
- history = []
705
- for entry in auto_trade_log:
706
- ts = entry["timestamp"]
707
- for act in entry["actions"]:
708
- if act["action"] in ("Buy", "Sell"):
709
- history.append({
710
- "timestamp": ts,
711
- "symbol": act["symbol"],
712
- "action": act["action"]
713
- })
714
- if history:
715
- hist_df = pd.DataFrame(history)
716
- if not hist_df.empty:
717
- hist_df["timestamp"] = pd.to_datetime(hist_df["timestamp"])
718
- hist_df["action_value"] = hist_df["action"].replace({"Buy": 1, "Sell": -1}).astype(float)
719
- pivot = hist_df.pivot_table(index="timestamp", columns="symbol", values="action_value", aggfunc="sum")
720
- st.line_chart(pivot.fillna(0))
721
- else:
722
- st.info("Waiting for first background auto-trade run... Please use the 'Refresh Auto-Trade Log' button if trades have been made.")
723
 
724
  if __name__ == "__main__":
725
  main()
 
482
  while True:
483
  start_time = time.time() # Record the start time of the iteration
484
 
485
+ sentiment = app.sentiment.get_news_sentiment(app.analyzer.symbols)
486
+
487
+ # Use the shared method to execute trades
488
+ actions = app._execute_sentiment_trades(sentiment)
489
+
490
+ # Create log entry
491
+ log_entry = {
492
+ "timestamp": datetime.now().isoformat(),
493
+ "actions": actions,
494
+ "sentiment": sentiment
495
+ }
496
+
497
+ # Update session state - ensure the UI reflects the latest data
498
+ if AUTO_TRADE_LOG_KEY not in st.session_state:
499
+ st.session_state[AUTO_TRADE_LOG_KEY] = []
500
+
501
+ st.session_state[AUTO_TRADE_LOG_KEY].append(log_entry)
502
+
503
+ # Limit size to avoid memory issues (keep last 50 entries)
504
+ if len(st.session_state[AUTO_TRADE_LOG_KEY]) > 50:
505
+ st.session_state[AUTO_TRADE_LOG_KEY] = st.session_state[AUTO_TRADE_LOG_KEY][-50:]
506
+
507
+ # Log the update
508
+ logger.info(f"Auto-trade completed. Actions: {actions}")
 
 
509
 
510
  # Calculate the time taken for this iteration
511
  elapsed_time = time.time() - start_time
 
518
  """Get the auto trade log from session state."""
519
  if AUTO_TRADE_LOG_KEY not in st.session_state:
520
  st.session_state[AUTO_TRADE_LOG_KEY] = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521
  return st.session_state[AUTO_TRADE_LOG_KEY]
522
 
523
+ def get_market_times(alpaca_api):
524
+ try:
525
+ clock = alpaca_api.get_clock()
526
+ is_open = clock.is_open
527
+ now = pd.Timestamp(clock.timestamp).tz_convert('America/New_York')
528
+ next_close = pd.Timestamp(clock.next_close).tz_convert('America/New_York')
529
+ next_open = pd.Timestamp(clock.next_open).tz_convert('America/New_York')
530
+ return is_open, now, next_open, next_close
531
+ except Exception as e:
532
+ logger.error(f"Error fetching market times: {e}")
533
+ return None, None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
 
535
  def main():
536
  st.title("Ben's Stock Trading Application")
 
609
  st.markdown(f"**Time until open:** {pd.to_timedelta(seconds_left, unit='s')}")
610
 
611
 
612
+ # # Initialize auto trade log in session state if needed
613
+ # if AUTO_TRADE_LOG_KEY not in st.session_state:
614
+ # st.session_state[AUTO_TRADE_LOG_KEY] = []
615
 
616
+ # # Only start the background thread once
617
+ # if "auto_trade_thread_started" not in st.session_state:
618
+ # thread = threading.Thread(target=background_auto_trade, args=(app,), daemon=True)
619
+ # thread.start()
620
+ # st.session_state["auto_trade_thread_started"] = True
621
 
622
  # Main area: plots and data
623
  app.manual_trade()
624
  app.display_charts()
625
 
626
  # Read and display latest auto-trade actions
627
+ # st.write("Automatic Trading Actions Based on Sentiment (background):")
628
+ # auto_trade_log = get_auto_trade_log()
629
+ # if auto_trade_log:
630
+ # # Show the most recent entry
631
+ # last_entry = auto_trade_log[-1]
632
+ # st.write(f"Last checked: {last_entry['timestamp']}")
633
+ # df = pd.DataFrame(last_entry["actions"])
634
+ # if "company_name" in df.columns:
635
+ # df = df[["symbol", "company_name", "sentiment", "action"]]
636
+ # st.dataframe(df)
637
+ # st.write("Sentiment Analysis (latest):")
638
+ # st.write(last_entry["sentiment"])
639
+
640
+ # # Plot buy/sell actions over time
641
+ # st.write("Auto-Trading History (Buy/Sell Actions Over Time):")
642
+ # history = []
643
+ # for entry in auto_trade_log:
644
+ # ts = entry["timestamp"]
645
+ # for act in entry["actions"]:
646
+ # if act["action"] in ("Buy", "Sell"):
647
+ # history.append({
648
+ # "timestamp": ts,
649
+ # "symbol": act["symbol"],
650
+ # "action": act["action"]
651
+ # })
652
+ # if history:
653
+ # hist_df = pd.DataFrame(history)
654
+ # if not hist_df.empty:
655
+ # hist_df["timestamp"] = pd.to_datetime(hist_df["timestamp"])
656
+ # hist_df["action_value"] = hist_df["action"].replace({"Buy": 1, "Sell": -1}).astype(float)
657
+ # pivot = hist_df.pivot_table(index="timestamp", columns="symbol", values="action_value", aggfunc="sum")
658
+ # st.line_chart(pivot.fillna(0))
659
+ # else:
660
+ # st.info("Waiting for first background auto-trade run...")
661
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662
 
663
  if __name__ == "__main__":
664
  main()