Update pages/technical_analysis.py
Browse files- 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 |
-
|
| 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 |
-
# 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 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 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.
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
st.
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 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)
|