Spaces:
Sleeping

File size: 6,624 Bytes
a9237fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import streamlit as st
import yfinance as yf
import plotly.graph_objects as go
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

# Configure page
st.set_page_config(
    page_title="AI Stock Trading Signals",
    page_icon="πŸ“ˆ",
    layout="wide"
)

def get_stock_data(symbol, period="3mo"):
    """Get stock data using yfinance"""
    try:
        ticker = yf.Ticker(symbol)
        data = ticker.history(period=period)
        return data
    except Exception as e:
        st.error(f"Error fetching data: {str(e)}")
        return None

def get_live_price(stock_symbol):
    """Get live stock price"""
    try:
        # Try nsepython first
        try:
            import nsepython as nse
            stock_name = stock_symbol.replace('.NS', '')
            live_data = nse.equity_quote(stock_name)
            if live_data and 'lastPrice' in live_data:
                return float(live_data['lastPrice'])
        except:
            pass
        
        # Fallback to yfinance
        ticker = yf.Ticker(stock_symbol)
        data = ticker.history(period="1d", interval="1m")
        if not data.empty:
            return float(data['Close'].iloc[-1])
        
        return None
    except Exception as e:
        st.warning(f"Could not fetch live price: {str(e)}")
        return None

def create_simple_chart(stock_symbol):
    """Create simple price chart"""
    try:
        data = get_stock_data(stock_symbol, period="1mo")
        if data is None or data.empty:
            return None
        
        # Get last 30 days
        data = data.tail(30)
        
        fig = go.Figure()
        
        # Add candlestick chart
        fig.add_trace(go.Candlestick(
            x=data.index,
            open=data['Open'],
            high=data['High'],
            low=data['Low'],
            close=data['Close'],
            name='Price'
        ))
        
        # Add simple moving averages
        sma_20 = data['Close'].rolling(window=20).mean()
        sma_50 = data['Close'].rolling(window=50).mean()
        
        fig.add_trace(go.Scatter(
            x=data.index, 
            y=sma_20, 
            name='SMA 20',
            line=dict(color='orange', width=2)
        ))
        
        fig.add_trace(go.Scatter(
            x=data.index, 
            y=sma_50, 
            name='SMA 50',
            line=dict(color='blue', width=2)
        ))
        
        fig.update_layout(
            title=f"{stock_symbol} - Price Chart",
            xaxis_rangeslider_visible=False,
            height=600,
            yaxis_title="Price (β‚Ή)"
        )
        
        return fig
        
    except Exception as e:
        st.error(f"Error creating chart: {str(e)}")
        return None

def simple_trading_signal(stock_symbol):
    """Generate simple trading signal based on moving averages"""
    try:
        data = get_stock_data(stock_symbol, period="3mo")
        if data is None or data.empty:
            return None, "No data available"
        
        # Calculate simple moving averages
        current_price = data['Close'].iloc[-1]
        sma_20 = data['Close'].rolling(window=20).mean().iloc[-1]
        sma_50 = data['Close'].rolling(window=50).mean().iloc[-1]
        
        # Simple signal logic
        if current_price > sma_20 and sma_20 > sma_50:
            signal = "BUY"
            confidence = 0.75
        elif current_price < sma_20 and sma_20 < sma_50:
            signal = "SELL"
            confidence = 0.75
        else:
            signal = "HOLD"
            confidence = 0.60
        
        return {
            'signal': signal,
            'confidence': confidence,
            'current_price': current_price,
            'sma_20': sma_20,
            'sma_50': sma_50
        }, None
        
    except Exception as e:
        return None, f"Error generating signal: {str(e)}"

def main():
    st.title("πŸ“ˆ Stock Trading Signals App")
    st.markdown("### NSE Stock Analysis (Simplified Version)")
    
    # Sidebar for stock selection
    st.sidebar.header("Stock Selection")
    
    # Stock options
    stock_options = {
        "Reliance Industries": "RELIANCE.NS",
        "Tata Consultancy Services": "TCS.NS",
        "Infosys": "INFY.NS"
    }
    
    selected_stock_name = st.sidebar.selectbox(
        "Choose a stock:",
        list(stock_options.keys())
    )
    
    selected_stock = stock_options[selected_stock_name]
    
    # Main content
    st.header("πŸ“Š Live Market Data")
    
    col1, col2 = st.columns(2)
    
    with col1:
        if st.button("πŸ”„ Get Live Price", type="primary"):
            live_price = get_live_price(selected_stock)
            if live_price:
                st.metric("Live Price (LTP)", f"β‚Ή{live_price:.2f}")
            else:
                st.warning("Could not fetch live price")
    
    # Trading signal section
    st.header("🎯 Trading Signal")
    
    if st.button("πŸ“ˆ Get Signal", type="primary"):
        signal_result, error = simple_trading_signal(selected_stock)
        
        if signal_result:
            signal = signal_result['signal']
            confidence = signal_result['confidence']
            
            # Display signal with color coding
            if signal == "BUY":
                st.success(f"🟒 **{signal}** Signal")
            elif signal == "SELL":
                st.error(f"πŸ”΄ **{signal}** Signal")
            else:
                st.info(f"🟑 **{signal}** Signal")
            
            # Display metrics
            col1, col2, col3 = st.columns(3)
            with col1:
                st.metric("Confidence", f"{confidence:.1%}")
            with col2:
                st.metric("Current Price", f"β‚Ή{signal_result['current_price']:.2f}")
            with col3:
                st.metric("SMA 20", f"β‚Ή{signal_result['sma_20']:.2f}")
            
        else:
            st.error(f"Signal generation failed: {error}")
    
    # Chart section
    st.header("πŸ“ˆ Price Chart")
    
    if st.button("πŸ“Š Show Chart"):
        chart = create_simple_chart(selected_stock)
        if chart:
            st.plotly_chart(chart, use_container_width=True)
    
    # Information section
    st.header("ℹ️ About This App")
    
    col1, col2 = st.columns(2)
    with col1:
        st.info("**Signal Logic:**\n- BUY: Price > SMA20 > SMA50\n- SELL: Price < SMA20 < SMA50\n- HOLD: Mixed signals")
    
    with col2:
        st.info("**Data Source:**\n- Yahoo Finance (yfinance)\n- NSE Python for live prices\n- 3 months historical data")

if __name__ == "__main__":
    main()