Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
# Import your existing code here
|
3 |
+
from datetime import datetime, timedelta
|
4 |
+
import yfinance as yf
|
5 |
+
import numpy as np
|
6 |
+
import pandas as pd
|
7 |
+
from sklearn.decomposition import PCA
|
8 |
+
from sklearn.preprocessing import StandardScaler, LabelEncoder
|
9 |
+
from sklearn.ensemble import RandomForestClassifier
|
10 |
+
import shap
|
11 |
+
import matplotlib.pyplot as plt
|
12 |
+
|
13 |
+
# Copy your existing classes here (DataFetcher, FinancialDataProcessor, etc.)
|
14 |
+
# Then add this Streamlit interface:
|
15 |
+
|
16 |
+
st.set_page_config(page_title="Crypto Trading Bot", layout="wide")
|
17 |
+
st.title("Crypto Trading Analysis Bot")
|
18 |
+
|
19 |
+
# Sidebar controls
|
20 |
+
ticker = st.sidebar.text_input("Ticker Symbol", value="BTC-USD")
|
21 |
+
days = st.sidebar.number_input("Number of Days", value=200, min_value=1, max_value=365)
|
22 |
+
|
23 |
+
if st.sidebar.button("Run Analysis"):
|
24 |
+
try:
|
25 |
+
with st.spinner("Fetching and analyzing data..."):
|
26 |
+
fetcher = DataFetcher(ticker=ticker, nb_days=days)
|
27 |
+
fetcher.fetch_data()
|
28 |
+
|
29 |
+
processor = FinancialDataProcessor(fetcher.data)
|
30 |
+
processed_data = processor.calculate_returns().calculate_probabilities()
|
31 |
+
|
32 |
+
pca_transformer = PCATransformer(n_components=1)
|
33 |
+
pca_result = pca_transformer.fit_transform(processed_data)
|
34 |
+
processed_data = processor.apply_pca_calculations(pca_result)
|
35 |
+
|
36 |
+
strategy_builder = StrategyBuilder(processed_data)
|
37 |
+
model, X, y_encoded = strategy_builder.train_model(target_column='PCA_Scenario')
|
38 |
+
shap_values = strategy_builder.compute_shapley_values(model, X)
|
39 |
+
|
40 |
+
feature_importance = strategy_builder.analyze_feature_importance(shap_values, X.columns)
|
41 |
+
buy_threshold, sell_threshold = strategy_builder.refine_thresholds(feature_importance)
|
42 |
+
|
43 |
+
backtester = Backtester(processed_data)
|
44 |
+
portfolio_values, final_position, entry_price = backtester.backtest(buy_threshold, sell_threshold)
|
45 |
+
|
46 |
+
last_row = processed_data.iloc[-1]
|
47 |
+
|
48 |
+
# Display results
|
49 |
+
col1, col2 = st.columns(2)
|
50 |
+
|
51 |
+
with col1:
|
52 |
+
st.subheader("Current Position")
|
53 |
+
st.metric("Portfolio Value", f"${portfolio_values[-1]:.2f}")
|
54 |
+
st.metric("Position", final_position or "No position")
|
55 |
+
if final_position:
|
56 |
+
st.metric("Entry Price", f"${entry_price:.2f}")
|
57 |
+
st.metric("Latest Close", f"${last_row['Close']:.2f}")
|
58 |
+
|
59 |
+
with col2:
|
60 |
+
st.subheader("Decision Metrics")
|
61 |
+
st.metric("Buy%", f"{last_row['Buy%']:.4f}")
|
62 |
+
st.metric("Sell%", f"{last_row['Sell%']:.4f}")
|
63 |
+
st.metric("PCA Buy%", f"{last_row['PCA_Buy%']:.4f}")
|
64 |
+
st.metric("PCA Sell%", f"{last_row['PCA_Sell%']:.4f}")
|
65 |
+
|
66 |
+
# Plot portfolio value
|
67 |
+
st.subheader("Portfolio Value Over Time")
|
68 |
+
fig, ax = plt.subplots(figsize=(12, 6))
|
69 |
+
ax.plot(processed_data.index[1:], portfolio_values, label='Portfolio Value', color='blue')
|
70 |
+
ax.set_title('Portfolio Value Over Time (Backtest)')
|
71 |
+
ax.set_xlabel('Date')
|
72 |
+
ax.set_ylabel('Portfolio Value ($)')
|
73 |
+
ax.grid(True)
|
74 |
+
ax.legend()
|
75 |
+
st.pyplot(fig)
|
76 |
+
|
77 |
+
# Feature importance
|
78 |
+
st.subheader("Feature Importance")
|
79 |
+
st.dataframe(feature_importance)
|
80 |
+
|
81 |
+
except Exception as e:
|
82 |
+
st.error(f"An error occurred: {str(e)}")
|