import streamlit as st # Import your existing code here from datetime import datetime, timedelta import yfinance as yf import numpy as np import pandas as pd from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler, LabelEncoder from sklearn.ensemble import RandomForestClassifier import shap import matplotlib.pyplot as plt # Copy your existing classes here (DataFetcher, FinancialDataProcessor, etc.) # Then add this Streamlit interface: st.set_page_config(page_title="Crypto Trading Bot", layout="wide") st.title("Crypto Trading Analysis Bot") # Sidebar controls ticker = st.sidebar.text_input("Ticker Symbol", value="BTC-USD") days = st.sidebar.number_input("Number of Days", value=200, min_value=1, max_value=365) if st.sidebar.button("Run Analysis"): try: with st.spinner("Fetching and analyzing data..."): fetcher = DataFetcher(ticker=ticker, nb_days=days) fetcher.fetch_data() processor = FinancialDataProcessor(fetcher.data) processed_data = processor.calculate_returns().calculate_probabilities() pca_transformer = PCATransformer(n_components=1) pca_result = pca_transformer.fit_transform(processed_data) processed_data = processor.apply_pca_calculations(pca_result) strategy_builder = StrategyBuilder(processed_data) model, X, y_encoded = strategy_builder.train_model(target_column='PCA_Scenario') shap_values = strategy_builder.compute_shapley_values(model, X) feature_importance = strategy_builder.analyze_feature_importance(shap_values, X.columns) buy_threshold, sell_threshold = strategy_builder.refine_thresholds(feature_importance) backtester = Backtester(processed_data) portfolio_values, final_position, entry_price = backtester.backtest(buy_threshold, sell_threshold) last_row = processed_data.iloc[-1] # Display results col1, col2 = st.columns(2) with col1: st.subheader("Current Position") st.metric("Portfolio Value", f"${portfolio_values[-1]:.2f}") st.metric("Position", final_position or "No position") if final_position: st.metric("Entry Price", f"${entry_price:.2f}") st.metric("Latest Close", f"${last_row['Close']:.2f}") with col2: st.subheader("Decision Metrics") st.metric("Buy%", f"{last_row['Buy%']:.4f}") st.metric("Sell%", f"{last_row['Sell%']:.4f}") st.metric("PCA Buy%", f"{last_row['PCA_Buy%']:.4f}") st.metric("PCA Sell%", f"{last_row['PCA_Sell%']:.4f}") # Plot portfolio value st.subheader("Portfolio Value Over Time") fig, ax = plt.subplots(figsize=(12, 6)) ax.plot(processed_data.index[1:], portfolio_values, label='Portfolio Value', color='blue') ax.set_title('Portfolio Value Over Time (Backtest)') ax.set_xlabel('Date') ax.set_ylabel('Portfolio Value ($)') ax.grid(True) ax.legend() st.pyplot(fig) # Feature importance st.subheader("Feature Importance") st.dataframe(feature_importance) except Exception as e: st.error(f"An error occurred: {str(e)}")