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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import plotly.graph_objects as go
|
| 3 |
+
from datetime import datetime, timedelta
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from utils.patterns import identify_patterns, calculate_technical_indicators
|
| 8 |
+
from utils.predictions import predict_movement
|
| 9 |
+
from utils.trading import fetch_market_data, is_market_open
|
| 10 |
+
|
| 11 |
+
# Page configuration
|
| 12 |
+
st.set_page_config(
|
| 13 |
+
page_title="Trading Pattern Analysis",
|
| 14 |
+
page_icon="📈",
|
| 15 |
+
layout="wide"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
# Load custom CSS
|
| 19 |
+
with open('styles/custom.css') as f:
|
| 20 |
+
st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
|
| 21 |
+
|
| 22 |
+
# Pattern descriptions from the uploaded file
|
| 23 |
+
PATTERN_DESCRIPTIONS = {
|
| 24 |
+
'HAMMER': 'Small body near the top with long lower wick, indicating buying pressure overcoming selling pressure.',
|
| 25 |
+
'INVERTED_HAMMER': 'Small body with long upper wick after downtrend, indicating resistance but potential upward movement.',
|
| 26 |
+
'PIERCING_LINE': 'Two-candlestick pattern where second closes above midpoint of first, signaling bullish shift.',
|
| 27 |
+
'BULLISH_ENGULFING': 'Small bearish candle followed by larger bullish candle that engulfs previous one.',
|
| 28 |
+
'MORNING_STAR': 'Three-candlestick pattern with bearish, small-bodied, and bullish candle indicating reversal.',
|
| 29 |
+
'THREE_WHITE_SOLDIERS': 'Three consecutive long bullish candles with small/no wicks, showing strong buying pressure.',
|
| 30 |
+
'BULLISH_HARAMI': 'Small bullish candle within body of preceding large bearish candle.',
|
| 31 |
+
'HANGING_MAN': 'Small body at top with long lower wick, signaling potential reversal.',
|
| 32 |
+
'DARK_CLOUD_COVER': 'Two-candlestick pattern with bearish closing below midpoint of previous bullish.',
|
| 33 |
+
'BEARISH_ENGULFING': 'Small bullish candle followed by larger bearish candle that engulfs it.',
|
| 34 |
+
'EVENING_STAR': 'Three-candlestick pattern with bullish, small-bodied, and bearish candle.',
|
| 35 |
+
'THREE_BLACK_CROWS': 'Three consecutive bearish candles showing strong selling.',
|
| 36 |
+
'SHOOTING_STAR': 'Small body with long upper wick, signaling resistance.',
|
| 37 |
+
'DOJI': 'Small body with wicks, showing market indecision.',
|
| 38 |
+
'DRAGONFLY_DOJI': 'Doji with long lower wick, showing buying pressure at bottom.',
|
| 39 |
+
'GRAVESTONE_DOJI': 'Doji with long upper wick, showing selling pressure at top.'
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
# Sidebar
|
| 43 |
+
st.sidebar.title("Trading Controls")
|
| 44 |
+
|
| 45 |
+
# Market Status Indicator
|
| 46 |
+
market_open = is_market_open()
|
| 47 |
+
status_color = "🟢" if market_open else "🔴"
|
| 48 |
+
market_status = "Market Open" if market_open else "Market Closed"
|
| 49 |
+
st.sidebar.write(f"{status_color} {market_status}")
|
| 50 |
+
|
| 51 |
+
symbol = st.sidebar.text_input("Symbol", value="AAPL", help="Enter a valid stock symbol (e.g., AAPL, MSFT)")
|
| 52 |
+
timeframe = st.sidebar.selectbox(
|
| 53 |
+
"Timeframe",
|
| 54 |
+
["30m", "1h", "2h", "4h"],
|
| 55 |
+
index=0,
|
| 56 |
+
help="Select analysis timeframe (each candle represents 15 minutes)"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# Add auto-refresh option
|
| 60 |
+
auto_refresh = st.sidebar.checkbox("Auto-refresh data", value=True)
|
| 61 |
+
if auto_refresh:
|
| 62 |
+
st.sidebar.write("Updates every minute")
|
| 63 |
+
st.rerun() # Use st.rerun() instead of experimental_rerun()
|
| 64 |
+
|
| 65 |
+
# Main content
|
| 66 |
+
st.title("Trading Pattern Analysis")
|
| 67 |
+
|
| 68 |
+
try:
|
| 69 |
+
# Fetch and process data
|
| 70 |
+
with st.spinner('Fetching market data...'):
|
| 71 |
+
df = fetch_market_data(symbol, period='1d', interval='15m')
|
| 72 |
+
|
| 73 |
+
if len(df) >= 2:
|
| 74 |
+
df = calculate_technical_indicators(df)
|
| 75 |
+
patterns = identify_patterns(df)
|
| 76 |
+
|
| 77 |
+
# Create candlestick chart
|
| 78 |
+
fig = go.Figure(data=[go.Candlestick(
|
| 79 |
+
x=df.index,
|
| 80 |
+
open=df['Open'],
|
| 81 |
+
high=df['High'],
|
| 82 |
+
low=df['Low'],
|
| 83 |
+
close=df['Close']
|
| 84 |
+
)])
|
| 85 |
+
|
| 86 |
+
# Update layout for dark theme
|
| 87 |
+
fig.update_layout(
|
| 88 |
+
template="plotly_dark",
|
| 89 |
+
plot_bgcolor="#252525",
|
| 90 |
+
paper_bgcolor="#252525",
|
| 91 |
+
xaxis_rangeslider_visible=False,
|
| 92 |
+
height=600,
|
| 93 |
+
title=f"{symbol} - Live Market Data ({timeframe} timeframe)"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# Display chart
|
| 97 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 98 |
+
|
| 99 |
+
# Pattern Analysis
|
| 100 |
+
col1, col2 = st.columns(2)
|
| 101 |
+
|
| 102 |
+
with col1:
|
| 103 |
+
st.subheader("Pattern Analysis")
|
| 104 |
+
if not patterns.empty and len(patterns) > 0:
|
| 105 |
+
latest_patterns = patterns.iloc[-1]
|
| 106 |
+
detected_patterns = latest_patterns[latest_patterns == 1].index.tolist()
|
| 107 |
+
|
| 108 |
+
if detected_patterns:
|
| 109 |
+
st.write("Detected Patterns:")
|
| 110 |
+
for pattern in detected_patterns:
|
| 111 |
+
st.markdown(f"""
|
| 112 |
+
<div class="pattern-container">
|
| 113 |
+
<h4>• {pattern.replace('_', ' ')}</h4>
|
| 114 |
+
<p>{PATTERN_DESCRIPTIONS.get(pattern, '')}</p>
|
| 115 |
+
</div>
|
| 116 |
+
""", unsafe_allow_html=True)
|
| 117 |
+
else:
|
| 118 |
+
st.info("No patterns detected in current timeframe")
|
| 119 |
+
else:
|
| 120 |
+
st.write("No pattern data available")
|
| 121 |
+
|
| 122 |
+
with col2:
|
| 123 |
+
st.subheader("Prediction")
|
| 124 |
+
if len(df) >= 30:
|
| 125 |
+
prediction, probability = predict_movement(df)
|
| 126 |
+
|
| 127 |
+
if prediction is not None and probability is not None:
|
| 128 |
+
direction = "Upward" if prediction else "Downward"
|
| 129 |
+
confidence = probability[1] if prediction else probability[0]
|
| 130 |
+
|
| 131 |
+
direction_class = "profit" if direction == "Upward" else "loss"
|
| 132 |
+
st.markdown(f"""
|
| 133 |
+
<div class="prediction-container">
|
| 134 |
+
<h3 class="{direction_class}">Predicted Movement: {direction}</h3>
|
| 135 |
+
<p>Confidence: {confidence:.2%}</p>
|
| 136 |
+
<p>(Next 15-minute prediction)</p>
|
| 137 |
+
</div>
|
| 138 |
+
""", unsafe_allow_html=True)
|
| 139 |
+
else:
|
| 140 |
+
st.write("Could not generate prediction")
|
| 141 |
+
else:
|
| 142 |
+
st.write("Insufficient data for prediction")
|
| 143 |
+
|
| 144 |
+
# Technical Indicators
|
| 145 |
+
st.subheader("Technical Indicators")
|
| 146 |
+
col3, col4, col5 = st.columns(3)
|
| 147 |
+
|
| 148 |
+
with col3:
|
| 149 |
+
last_rsi = df['RSI'].iloc[-1] if 'RSI' in df else None
|
| 150 |
+
prev_rsi = df['RSI'].iloc[-2] if 'RSI' in df and len(df) > 1 else None
|
| 151 |
+
|
| 152 |
+
if last_rsi is not None and prev_rsi is not None:
|
| 153 |
+
delta = last_rsi - prev_rsi
|
| 154 |
+
delta_color = "profit" if delta > 0 else "loss"
|
| 155 |
+
st.markdown(f"""
|
| 156 |
+
<div class="metric-container">
|
| 157 |
+
<h4>RSI</h4>
|
| 158 |
+
<p>{last_rsi:.2f}</p>
|
| 159 |
+
<p class="{delta_color}">({delta:+.2f})</p>
|
| 160 |
+
</div>
|
| 161 |
+
""", unsafe_allow_html=True)
|
| 162 |
+
|
| 163 |
+
with col4:
|
| 164 |
+
last_macd = df['MACD'].iloc[-1] if 'MACD' in df else None
|
| 165 |
+
prev_macd = df['MACD'].iloc[-2] if 'MACD' in df and len(df) > 1 else None
|
| 166 |
+
|
| 167 |
+
if last_macd is not None and prev_macd is not None:
|
| 168 |
+
delta = last_macd - prev_macd
|
| 169 |
+
delta_color = "profit" if delta > 0 else "loss"
|
| 170 |
+
st.markdown(f"""
|
| 171 |
+
<div class="metric-container">
|
| 172 |
+
<h4>MACD</h4>
|
| 173 |
+
<p>{last_macd:.2f}</p>
|
| 174 |
+
<p class="{delta_color}">({delta:+.2f})</p>
|
| 175 |
+
</div>
|
| 176 |
+
""", unsafe_allow_html=True)
|
| 177 |
+
|
| 178 |
+
with col5:
|
| 179 |
+
last_sma = df['SMA_20'].iloc[-1] if 'SMA_20' in df else None
|
| 180 |
+
last_close = df['Close'].iloc[-1] if len(df) > 0 else None
|
| 181 |
+
|
| 182 |
+
if last_sma is not None and last_close is not None:
|
| 183 |
+
delta = last_close - last_sma
|
| 184 |
+
delta_color = "profit" if delta > 0 else "loss"
|
| 185 |
+
st.markdown(f"""
|
| 186 |
+
<div class="metric-container">
|
| 187 |
+
<h4>15-min SMA</h4>
|
| 188 |
+
<p>{last_sma:.2f}</p>
|
| 189 |
+
<p class="{delta_color}">({delta:+.2f})</p>
|
| 190 |
+
</div>
|
| 191 |
+
""", unsafe_allow_html=True)
|
| 192 |
+
else:
|
| 193 |
+
st.warning("Insufficient data points. This could be because the market is closed or the selected timeframe is too short.")
|
| 194 |
+
|
| 195 |
+
except Exception as e:
|
| 196 |
+
st.error(f"Error: {str(e)}")
|
| 197 |
+
if "Connection Error" in str(e):
|
| 198 |
+
st.warning("Unable to connect to market data. Please check your internet connection and try again.")
|
| 199 |
+
elif "not found" in str(e):
|
| 200 |
+
st.warning("Invalid symbol. Please enter a valid stock symbol.")
|
| 201 |
+
else:
|
| 202 |
+
st.info("If the market is closed, you can still view the most recent trading data.")
|