ratulsur commited on
Commit
c209383
Β·
verified Β·
1 Parent(s): a823289

Update pages/technical_analysis.py

Browse files
Files changed (1) hide show
  1. pages/technical_analysis.py +107 -164
pages/technical_analysis.py CHANGED
@@ -1,170 +1,113 @@
1
  import streamlit as st
2
  import pandas as pd
 
3
  import matplotlib.pyplot as plt
4
- from utils.data_loader import (
5
- load_nifty50_symbols,
6
- get_market_summary,
7
- load_market_indices,
8
- process_uploaded_file,
9
- fetch_stock_data,
10
- get_stock_suggestions
11
- )
12
- from utils.market_analysis import MarketAnalyzer
13
- from datetime import datetime
14
- import asyncio
15
-
16
- # Initialize market analyzer
17
- market_analyzer = MarketAnalyzer()
18
-
19
- # Page configuration
20
- st.set_page_config(
21
- page_title="Indian Stock Market Analysis",
22
- page_icon="πŸ“ˆ",
23
- layout="wide",
24
- initial_sidebar_state="expanded"
25
- )
26
-
27
- # Sidebar
28
- st.sidebar.title("Navigation")
29
-
30
- # File Upload Section
31
- st.sidebar.header("Data Input")
32
- uploaded_file = st.sidebar.file_uploader(
33
- "Upload CSV/Excel file",
34
- type=['csv', 'xlsx', 'xls'],
35
- help="Upload your own stock data for analysis"
36
- )
37
-
38
- # Data Source Selection
39
- data_source = st.sidebar.radio(
40
- "Select Data Source",
41
- ["Market Data", "Uploaded File"],
42
- index=0
43
- )
44
-
45
- st.sidebar.markdown("---")
46
-
47
- # Main content
48
- st.title("Indian Stock Market Analysis")
49
- st.markdown("---")
50
-
51
- async def analyze_stock_data(stock_data, symbol):
52
- """Analyze stock data and generate reports"""
53
- # Calculate technical indicators
54
- data_with_indicators = market_analyzer.calculate_technical_indicators(stock_data)
55
-
56
- # Get AI sentiment
57
- ai_sentiment = await market_analyzer.get_ai_sentiment(symbol, data_with_indicators)
58
-
59
- # Generate detailed report
60
- report = market_analyzer.generate_detailed_report(symbol, data_with_indicators, ai_sentiment)
61
-
62
- return report, data_with_indicators
63
-
64
- # Market Summary
65
- if data_source == "Market Data":
66
- market_summary = get_market_summary()
67
- if market_summary:
68
- st.subheader("Market Overview")
69
- cols = st.columns(len(market_summary))
70
-
71
- for i, (index_name, summary) in enumerate(market_summary.items()):
72
- with cols[i]:
73
- st.metric(
74
- index_name,
75
- f"β‚Ή{summary['index_value']:,.2f}",
76
- f"{summary['change_percent']:.2f}%"
77
- )
78
 
79
- # Stock Selection
80
- st.subheader("Stock Analysis")
81
-
82
- # Index Selection
83
- indices = load_market_indices()
84
- selected_index = st.selectbox("Select Index", list(indices.keys()))
85
-
86
- # Stock Selection
87
- symbols = load_nifty50_symbols()
88
- selected_symbol = st.selectbox("Select Stock", symbols)
89
-
90
- # Time Period Selection
91
- timeframe = st.select_slider(
92
- "Select Time Period",
93
- options=["1w", "1mo", "3mo", "6mo", "1y", "3y", "5y"],
94
- value="1mo",
95
- format_func=lambda x: {
96
- "1w": "1 Week",
97
- "1mo": "1 Month",
98
- "3mo": "1 Quarter",
99
- "6mo": "6 Months",
100
- "1y": "1 Year",
101
- "3y": "3 Years",
102
- "5y": "5 Years"
103
- }[x]
104
- )
105
-
106
- # Fetch and display stock data
107
- stock_data = fetch_stock_data(selected_symbol, period=timeframe)
108
- if stock_data is not None:
109
- # Run analysis
110
- report, data_with_indicators = asyncio.run(analyze_stock_data(stock_data, selected_symbol))
111
-
112
- # Display Analysis Results
113
- st.subheader("Market Analysis")
114
-
115
- # Action Signal
116
- col1, col2, col3 = st.columns(3)
117
- with col1:
118
- st.metric(
119
- "Recommended Action",
120
- report['trade_signals']['action'],
121
- delta=f"Confidence: {report['trade_signals']['confidence']}"
122
- )
123
- with col2:
124
- st.metric(
125
- "Risk Level",
126
- report['risk_assessment']['level'],
127
- delta=f"Volatility: {report['risk_assessment']['volatility']:.2f}%"
128
- )
129
- with col3:
130
- st.metric(
131
- "Current Price",
132
- f"β‚Ή{report['price_analysis']['current_price']:,.2f}",
133
- delta=f"{report['price_analysis']['changes']['1d']:.2f}% (1d)"
134
- )
135
-
136
- # Price Chart with Indicators
137
- st.subheader("Stock Price Chart")
138
- fig, ax = plt.subplots(figsize=(10, 5))
139
- ax.plot(data_with_indicators.index, data_with_indicators['Close'], label='Close Price', color='blue')
140
- ax.set_xlabel("Date")
141
- ax.set_ylabel("Price")
142
- ax.legend()
143
- st.pyplot(fig)
144
 
 
 
 
 
 
145
  else:
146
- st.error("Unable to fetch data. Please try again later.")
147
-
148
- # Quick Links
149
- st.sidebar.markdown("## Quick Links")
150
- pages = {
151
- "Market Overview": "pages/market_overview.py",
152
- "Technical Analysis": "pages/technical_analysis.py",
153
- "Quantum Patterns": "pages/quantum_patterns.py",
154
- "Predictions": "pages/predictions.py"
155
- }
156
-
157
- for page, path in pages.items():
158
- st.sidebar.page_link(path, label=page)
159
-
160
- # Footer
161
- st.sidebar.markdown("---")
162
- st.sidebar.markdown(
163
- """
164
- <div style='text-align: center'>
165
- <p>Built with ❀️ using Streamlit</p>
166
- <p>Data provided by Yahoo Finance</p>
167
- </div>
168
- """,
169
- unsafe_allow_html=True
170
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
+ import numpy as np
4
  import matplotlib.pyplot as plt
5
+ import time
6
+ import json
7
+ from utils.quantum_algorithms import QuantumInspiredOptimizer
8
+ from utils.deepseek_api import DeepSeekAI # Integrating DeepSeek
9
+ import openai
10
+
11
+ # πŸ”§ DeepSeek API Configuration
12
+ DEEPSEEK_API_KEY = "sk-d52b48c40d494fb88acee4e20e881240" # Replace with your actual key
13
+ openai.api_key = DEEPSEEK_API_KEY
14
+
15
+ # βš›οΈ Initialize Quantum Optimizer
16
+ quantum_optimizer = QuantumInspiredOptimizer()
17
+ deepseek_ai = DeepSeekAI()
18
+
19
+ st.set_page_config(page_title="Quantum File Analysis", layout="wide")
20
+ st.title("πŸ“‚ Quantum File Analysis with DeepSeek AI")
21
+
22
+ # πŸ“Œ File Upload Section
23
+ uploaded_file = st.file_uploader("πŸ“€ Upload your CSV/Excel file", type=["csv", "xlsx"])
24
+
25
+ if uploaded_file:
26
+ st.success("βœ… File Uploaded Successfully!")
27
+
28
+ # πŸ› οΈ Read File
29
+ file_extension = uploaded_file.name.split(".")[-1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ if file_extension == "csv":
32
+ df = pd.read_csv(uploaded_file)
33
+ else:
34
+ df = pd.read_excel(uploaded_file)
35
+
36
+ # πŸ“Œ Display Data Preview
37
+ st.subheader("πŸ“Š Data Preview")
38
+ st.write(df.head())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ # 🎯 Select Column for Analysis
41
+ numeric_columns = df.select_dtypes(include=[np.number]).columns.tolist()
42
+
43
+ if not numeric_columns:
44
+ st.error("⚠️ No numerical columns found! Please upload a valid dataset.")
45
  else:
46
+ target_column = st.selectbox("πŸ“ˆ Select Column for Quantum Analysis", numeric_columns)
47
+
48
+ if target_column:
49
+ st.success(f"βœ… Selected Column: {target_column}")
50
+ prices = df[target_column].values
51
+
52
+ # πŸ› οΈ Quantum Pattern Detection
53
+ st.subheader("πŸ”¬ Quantum-Inspired Pattern Detection")
54
+ pattern_strength = quantum_optimizer.quantum_pattern_detection(prices)
55
+
56
+ fig, ax1 = plt.subplots(figsize=(12, 6))
57
+ ax1.plot(df.index, prices, label="Price", color="blue")
58
+ ax1.set_ylabel("Value", color="blue")
59
+
60
+ ax2 = ax1.twinx()
61
+ ax2.plot(df.index, pattern_strength, label="Pattern Strength", color="orange", linestyle="dashed")
62
+ ax2.set_ylabel("Pattern Strength", color="orange")
63
+
64
+ ax1.set_title("Quantum Pattern Detection")
65
+ ax1.legend(loc="upper left")
66
+ ax2.legend(loc="upper right")
67
+ st.pyplot(fig)
68
+
69
+ # ⚑ Quantum Predictive Modeling
70
+ st.subheader("πŸ“ˆ Quantum Prediction with DeepSeek AI")
71
+
72
+ # Generate Predictions
73
+ predictions = quantum_optimizer.quantum_trend_prediction(prices)
74
+ future_dates = np.arange(len(prices), len(prices) + 10) # Predict next 10 steps
75
+
76
+ fig, ax = plt.subplots(figsize=(12, 6))
77
+ ax.plot(df.index, prices, label="Historical Data", color="blue")
78
+ ax.plot(future_dates, predictions[-10:], label="Predictions", color="red", linestyle="dashed")
79
+ ax.set_title("Quantum Trend Prediction")
80
+ ax.legend()
81
+ st.pyplot(fig)
82
+
83
+ # 🧠 DeepSeek AI Insights
84
+ st.subheader("πŸ€– AI-Powered Insights (DeepSeek)")
85
+
86
+ deepseek_prompt = f"""
87
+ Analyze the following financial data using quantum-inspired methods.
88
+ Provide insights on potential trends, risks, and investment strategies.
89
+ Data: {json.dumps(prices.tolist())}
90
+ """
91
+
92
+ with st.spinner("πŸ” Generating AI-powered insights..."):
93
+ deepseek_response = openai.ChatCompletion.create(
94
+ model="deepseek-chat",
95
+ messages=[{"role": "user", "content": deepseek_prompt}]
96
+ )
97
+
98
+ ai_insights = deepseek_response["choices"][0]["message"]["content"]
99
+ st.write(ai_insights)
100
+
101
+ # πŸ† Display Key Stats
102
+ st.subheader("πŸ“Š Statistical Insights")
103
+ col1, col2, col3 = st.columns(3)
104
+
105
+ with col1:
106
+ st.metric("πŸ”— Quantum Entropy", f"{-np.sum(pattern_strength**2 * np.log(pattern_strength**2 + 1e-10)):.4f}")
107
+ with col2:
108
+ st.metric("πŸ“‘ Phase Coherence", f"{np.std(pattern_strength):.4f}")
109
+ with col3:
110
+ st.metric("πŸ“ˆ Prediction Confidence", f"{np.mean(np.abs(predictions - prices[-10:])):.4f}")
111
+
112
+ # βœ… Refresh Every **10 Seconds**
113
+ time.sleep(10)