DagonGod / predictions.py
ratulsur's picture
Upload 10 files
b7c6830 verified
import streamlit as st
import plotly.graph_objects as go
import numpy as np
from datetime import datetime, timedelta
from utils.data_loader import load_nifty50_symbols, fetch_stock_data
from utils.quantum_algorithms import QuantumInspiredOptimizer
st.title("Market Predictions")
# Initialize quantum optimizer
quantum_optimizer = QuantumInspiredOptimizer()
# Stock selection
symbol = st.selectbox("Select Stock", load_nifty50_symbols())
prediction_days = st.slider("Prediction Window (days)", 5, 30, 7)
# Fetch data
data = fetch_stock_data(symbol, period='1y')
if data is not None:
prices = data['Close'].values
# Calculate predictions
predictions = quantum_optimizer.quantum_trend_prediction(prices)
# Create future dates for predictions
last_date = data.index[-1]
future_dates = [last_date + timedelta(days=x) for x in range(1, prediction_days + 1)]
# Calculate confidence intervals (simple example)
confidence_high = predictions * 1.02
confidence_low = predictions * 0.98
# Plotting
fig = go.Figure()
# Historical prices
fig.add_trace(go.Scatter(
x=data.index,
y=data['Close'],
name='Historical Price',
line=dict(color='#00B894')
))
# Predictions
fig.add_trace(go.Scatter(
x=future_dates,
y=predictions[-prediction_days:],
name='Predicted Price',
line=dict(color='#FFA500', dash='dash')
))
# Confidence interval
fig.add_trace(go.Scatter(
x=future_dates,
y=confidence_high[-prediction_days:],
fill=None,
mode='lines',
line_color='rgba(255, 165, 0, 0)',
showlegend=False
))
fig.add_trace(go.Scatter(
x=future_dates,
y=confidence_low[-prediction_days:],
fill='tonexty',
mode='lines',
line_color='rgba(255, 165, 0, 0)',
name='Confidence Interval'
))
fig.update_layout(
title=f"Price Prediction for {symbol}",
xaxis_title="Date",
yaxis_title="Price",
height=600
)
st.plotly_chart(fig, use_container_width=True)
# Prediction metrics
col1, col2, col3 = st.columns(3)
with col1:
predicted_change = (predictions[-1] - prices[-1]) / prices[-1] * 100
st.metric(
"Predicted Change",
f"{predicted_change:.2f}%",
delta=f"{predicted_change:.2f}%"
)
with col2:
confidence_range = (confidence_high[-1] - confidence_low[-1]) / predictions[-1] * 100
st.metric(
"Confidence Range",
f"±{confidence_range:.2f}%"
)
with col3:
trend = "Bullish" if predicted_change > 0 else "Bearish"
st.metric(
"Predicted Trend",
trend,
delta="↑" if predicted_change > 0 else "↓"
)
# Additional analysis
st.subheader("Technical Factors")
# Calculate some basic technical indicators for the prediction
momentum = np.gradient(predictions[-30:])
volatility = np.std(prices[-30:]) / np.mean(prices[-30:]) * 100
factors_col1, factors_col2 = st.columns(2)
with factors_col1:
st.markdown("""
### Momentum Analysis
- Short-term trend: **{}**
- Momentum strength: **{:.2f}**
""".format(
"Positive" if momentum[-1] > 0 else "Negative",
abs(momentum[-1])
))
with factors_col2:
st.markdown("""
### Risk Metrics
- Historical volatility: **{:.2f}%**
- Prediction confidence: **{:.2f}%**
""".format(
volatility,
100 - confidence_range
))
# Warning/Disclaimer
st.warning("""
**Disclaimer**: These predictions are based on quantum-inspired algorithms and historical data analysis.
Market behavior is inherently unpredictable and these projections should not be used as the sole basis
for investment decisions. Always conduct thorough research and consider multiple factors before making
investment choices.
""")
else:
st.error("Unable to fetch data. Please try again later.")