Benjamin Consolvo commited on
Commit
873b67f
·
1 Parent(s): 3fd0696

updating auto trade log

Browse files
Files changed (2) hide show
  1. README.md +1 -2
  2. app.py +98 -37
README.md CHANGED
@@ -8,7 +8,7 @@ sdk_version: 1.42.2
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
- short_description: 'Sample stock trading application'
12
  ---
13
 
14
  ## Installation Steps
@@ -18,4 +18,3 @@ short_description: 'Sample stock trading application'
18
  3. source .venv/bin/activate
19
  4. streamlit run deeepseek_stocktrader.py
20
  5. need to add streamlit secrets: .streamlit/secrets.toml
21
- 6. add .streamlit/ to .gitignore
 
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
+ short_description: 'Stock trading application with Intel AI for Enterprise Inference'
12
  ---
13
 
14
  ## Installation Steps
 
18
  3. source .venv/bin/activate
19
  4. streamlit run deeepseek_stocktrader.py
20
  5. need to add streamlit secrets: .streamlit/secrets.toml
 
app.py CHANGED
@@ -482,30 +482,32 @@ def background_auto_trade(app):
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,19 +520,62 @@ def get_auto_trade_log():
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")
@@ -625,7 +670,24 @@ def main():
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]
@@ -657,8 +719,7 @@ def main():
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()
 
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
  """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")
 
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]
 
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()