Falcao Zane Vijay commited on
Commit
7508b69
Β·
1 Parent(s): 9537a59

deploy #10

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +28 -0
src/streamlit_app.py CHANGED
@@ -18,6 +18,8 @@ from indicators.macd import macd
18
 
19
  from strategy.rule_based_strategy import generate_signals_sma, generate_signals_ema
20
  from utils.backtester import backtest_signals
 
 
21
 
22
  from indicators.enhanced_features import (
23
  create_volatility_features, create_enhanced_lag_features,
@@ -34,6 +36,12 @@ st.set_page_config(
34
  layout="wide"
35
  )
36
 
 
 
 
 
 
 
37
  # Stock symbols
38
  STOCK_SYMBOLS = [
39
  'ADANIENT.NS', 'ADANIPORTS.NS', 'APOLLOHOSP.NS', 'ASIANPAINT.NS',
@@ -72,13 +80,16 @@ FEATURES = [
72
  @st.cache_data
73
  def load_stock_data(symbol, start_date, end_date):
74
  """Load stock data from Yahoo Finance"""
 
75
  try:
76
  data = yf.download(symbol, start=start_date, end=end_date, session=session)
77
  # Flatten the MultiIndex columns
78
  if data.columns.nlevels > 1:
79
  data.columns = [col[0] for col in data.columns]
 
80
  return data
81
  except Exception as e:
 
82
  st.error(f"Error loading data: {e}")
83
  return None
84
 
@@ -133,11 +144,15 @@ selected_stock = st.sidebar.selectbox("Select Stock Symbol", STOCK_SYMBOLS, inde
133
  start_date = st.sidebar.date_input("Start Date", value=datetime(2023, 1, 1))
134
  end_date = st.sidebar.date_input("End Date", value=datetime.now())
135
 
 
 
136
  st.sidebar.subheader("πŸ“ˆ Technical Indicators")
137
  rsi_period = st.sidebar.slider("RSI Period", min_value=5, max_value=30, value=14, step=1)
138
  short_period = st.sidebar.slider("Short-term Period", min_value=5, max_value=50, value=20, step=1)
139
  long_period = st.sidebar.slider("Long-term Period", min_value=50, max_value=200, value=50, step=1)
140
 
 
 
141
  # Strategy selection (for trading dashboard)
142
  strategy_type = st.sidebar.selectbox("Strategy Type", ["SMA-based", "EMA-based", "Both"])
143
 
@@ -148,6 +163,9 @@ stop_loss = st.sidebar.slider("Stop Loss (%)", 0.0, 20.0, 5.0, step=1.0) / 100
148
  take_profit = st.sidebar.slider("Take Profit (%)", 0.0, 50.0, 15.0, step=5.0) / 100
149
  use_risk_mgmt = st.sidebar.checkbox("Enable Risk Management", value=True)
150
 
 
 
 
151
  # ========================= PRICE PREDICTION TAB =========================
152
 
153
  with tab1:
@@ -188,10 +206,14 @@ with tab1:
188
  # Create feature vector
189
  feature_vector = latest_data[FEATURES].values.reshape(1, -1)
190
  feature_vector_scaled = scaler.transform(feature_vector)
 
 
191
 
192
  # Make prediction
193
  prediction = model.predict(feature_vector_scaled)[0]
194
  probability = model.predict_proba(feature_vector_scaled)[0].max()
 
 
195
 
196
 
197
  # Display prediction
@@ -325,10 +347,12 @@ with tab2:
325
 
326
  with tab_sma:
327
  st.subheader("πŸ“Š SMA Strategy Results")
 
328
  sma_results, sma_metrics = backtest_signals(
329
  df, signal_col='SMA_Signal', price_col='Close',
330
  initial_cash=initial_cash, transaction_cost=transaction_cost if use_risk_mgmt else 0
331
  )
 
332
 
333
  # Set variables for common sections
334
  results = sma_results
@@ -389,10 +413,12 @@ with tab2:
389
 
390
  with tab_ema:
391
  st.subheader("πŸ“Š EMA Strategy Results")
 
392
  ema_results, ema_metrics = backtest_signals(
393
  df, signal_col='EMA_Signal', price_col='Close',
394
  initial_cash=initial_cash, transaction_cost=transaction_cost if use_risk_mgmt else 0
395
  )
 
396
 
397
  # Set variables for common sections
398
  results = ema_results
@@ -456,10 +482,12 @@ with tab2:
456
  signal_col = 'SMA_Signal' if strategy_type == "SMA-based" else 'EMA_Signal'
457
  strategy_name = strategy_type.split('-')[0]
458
 
 
459
  results, metrics = backtest_signals(
460
  df, signal_col=signal_col, price_col='Close',
461
  initial_cash=initial_cash, transaction_cost=transaction_cost if use_risk_mgmt else 0
462
  )
 
463
 
464
  # Display metrics
465
  col1, col2, col3, col4 = st.columns(4)
 
18
 
19
  from strategy.rule_based_strategy import generate_signals_sma, generate_signals_ema
20
  from utils.backtester import backtest_signals
21
+ from utils.logger import setup_logger
22
+ import logging
23
 
24
  from indicators.enhanced_features import (
25
  create_volatility_features, create_enhanced_lag_features,
 
36
  layout="wide"
37
  )
38
 
39
+ # Initialize logging once
40
+ if 'logging_initialized' not in st.session_state:
41
+ setup_logger(log_dir="logs", log_level=logging.INFO)
42
+ st.session_state.logging_initialized = True
43
+ logging.info("=== Streamlit Trading App Started ===")
44
+
45
  # Stock symbols
46
  STOCK_SYMBOLS = [
47
  'ADANIENT.NS', 'ADANIPORTS.NS', 'APOLLOHOSP.NS', 'ASIANPAINT.NS',
 
80
  @st.cache_data
81
  def load_stock_data(symbol, start_date, end_date):
82
  """Load stock data from Yahoo Finance"""
83
+ logging.info(f"Loading stock data for {symbol} from {start_date} to {end_date}")
84
  try:
85
  data = yf.download(symbol, start=start_date, end=end_date, session=session)
86
  # Flatten the MultiIndex columns
87
  if data.columns.nlevels > 1:
88
  data.columns = [col[0] for col in data.columns]
89
+ logging.info(f"Successfully loaded {len(data)} records for {symbol}")
90
  return data
91
  except Exception as e:
92
+ logging.error(f"Error loading data for {symbol}: {str(e)}")
93
  st.error(f"Error loading data: {e}")
94
  return None
95
 
 
144
  start_date = st.sidebar.date_input("Start Date", value=datetime(2023, 1, 1))
145
  end_date = st.sidebar.date_input("End Date", value=datetime.now())
146
 
147
+ logging.info(f"User selected stock: {selected_stock}, date range: {start_date} to {end_date}")
148
+
149
  st.sidebar.subheader("πŸ“ˆ Technical Indicators")
150
  rsi_period = st.sidebar.slider("RSI Period", min_value=5, max_value=30, value=14, step=1)
151
  short_period = st.sidebar.slider("Short-term Period", min_value=5, max_value=50, value=20, step=1)
152
  long_period = st.sidebar.slider("Long-term Period", min_value=50, max_value=200, value=50, step=1)
153
 
154
+ logging.info(f"RSI Period: {rsi_period}, Short-term Period: {short_period}, Long-term Period: {long_period}")
155
+
156
  # Strategy selection (for trading dashboard)
157
  strategy_type = st.sidebar.selectbox("Strategy Type", ["SMA-based", "EMA-based", "Both"])
158
 
 
163
  take_profit = st.sidebar.slider("Take Profit (%)", 0.0, 50.0, 15.0, step=5.0) / 100
164
  use_risk_mgmt = st.sidebar.checkbox("Enable Risk Management", value=True)
165
 
166
+ logging.info(f"Initial Cash: β‚Ή{initial_cash}, Transaction Cost: {transaction_cost*100}%, "
167
+ f"Stop Loss: {stop_loss*100}%, Take Profit: {take_profit*100}%, Risk Management: {use_risk_mgmt}")
168
+
169
  # ========================= PRICE PREDICTION TAB =========================
170
 
171
  with tab1:
 
206
  # Create feature vector
207
  feature_vector = latest_data[FEATURES].values.reshape(1, -1)
208
  feature_vector_scaled = scaler.transform(feature_vector)
209
+
210
+ logging.info(f"Making price prediction for {selected_stock}")
211
 
212
  # Make prediction
213
  prediction = model.predict(feature_vector_scaled)[0]
214
  probability = model.predict_proba(feature_vector_scaled)[0].max()
215
+
216
+ logging.info(f"Prediction: {'UP' if prediction == 1 else 'DOWN'} with {probability:.1%} confidence")
217
 
218
 
219
  # Display prediction
 
347
 
348
  with tab_sma:
349
  st.subheader("πŸ“Š SMA Strategy Results")
350
+ logging.info(f"Starting backtest for {selected_stock} with {strategy_type} strategy")
351
  sma_results, sma_metrics = backtest_signals(
352
  df, signal_col='SMA_Signal', price_col='Close',
353
  initial_cash=initial_cash, transaction_cost=transaction_cost if use_risk_mgmt else 0
354
  )
355
+ logging.info(f"Backtest completed for {selected_stock} with {strategy_type} strategy")
356
 
357
  # Set variables for common sections
358
  results = sma_results
 
413
 
414
  with tab_ema:
415
  st.subheader("πŸ“Š EMA Strategy Results")
416
+ logging.info(f"Starting backtest for {selected_stock} with {strategy_type} strategy")
417
  ema_results, ema_metrics = backtest_signals(
418
  df, signal_col='EMA_Signal', price_col='Close',
419
  initial_cash=initial_cash, transaction_cost=transaction_cost if use_risk_mgmt else 0
420
  )
421
+ logging.info(f"Backtest completed for {selected_stock} with {strategy_type} strategy")
422
 
423
  # Set variables for common sections
424
  results = ema_results
 
482
  signal_col = 'SMA_Signal' if strategy_type == "SMA-based" else 'EMA_Signal'
483
  strategy_name = strategy_type.split('-')[0]
484
 
485
+ logging.info(f"Starting backtest for {selected_stock} with {strategy_type} strategy")
486
  results, metrics = backtest_signals(
487
  df, signal_col=signal_col, price_col='Close',
488
  initial_cash=initial_cash, transaction_cost=transaction_cost if use_risk_mgmt else 0
489
  )
490
+ logging.info(f"Backtest completed. Final return: {metrics['Total Return']}")
491
 
492
  # Display metrics
493
  col1, col2, col3, col4 = st.columns(4)