Spaces:
Running
Running
Benjamin Consolvo
commited on
Commit
·
18cfdec
1
Parent(s):
6893212
rm auto trades from ui
Browse files
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 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
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
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
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 |
-
|
660 |
|
661 |
-
# Only start the background thread once
|
662 |
-
if "auto_trade_thread_started" not in st.session_state:
|
663 |
-
|
664 |
-
|
665 |
-
|
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 |
-
#
|
675 |
-
|
676 |
-
|
677 |
-
|
678 |
-
|
679 |
-
|
680 |
-
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
|
685 |
-
|
686 |
-
st.write(
|
687 |
-
|
688 |
-
#
|
689 |
-
|
690 |
-
|
691 |
-
if
|
692 |
-
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
704 |
-
|
705 |
-
|
706 |
-
|
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()
|