File size: 9,754 Bytes
42c2fbe |
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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
import streamlit as st
import pandas as pd
import numpy as np
import logging
from model import fetch_data, calculate_indicators, calculate_support_resistance, predict_future_prices
from visualizations import (
plot_stock_price, plot_predictions, plot_technical_indicators, plot_risk_levels,
plot_feature_importance, plot_candlestick, plot_volume, plot_moving_averages,
plot_feature_correlations
)
from sklearn.metrics import ConfusionMatrixDisplay
from ui import display_analysis
from logger import get_logger
from dashboard import display_dashboard, display_profile,fetch_stock_profile,display_quarterly_results, display_shareholding_pattern, display_financial_ratios
from llm import display_recommendation #analyze_stock_with_llm
# import argparse
# parser = argparse.ArgumentParser()
# parser.add_argument('--token', required=True)
# args = parser.parse_args()
# API_TOKEN = args.token
logger = get_logger(__name__)
st.title("Stock Analysis and Prediction")
# Sidebar for navigation
st.sidebar.title("Navigation")
# Initialize `page` to "Analytics" by default
if 'page' not in st.session_state:
st.session_state['page'] = "Analytics"
if st.sidebar.button("Analytics"):
st.session_state['page'] = "Analytics"
if st.sidebar.button("Ask to AI"):
st.session_state['page'] = "Ask to AI"
if st.sidebar.button("Dashboard"):
st.session_state['page'] = "Dashboard"
if st.sidebar.button("Profile"):
st.session_state['page'] = "Profile"
page = st.session_state['page']
# Function to fetch and prepare data
def get_data():
ticker = st.session_state.get('ticker')
start_date = st.session_state.get('start_date')
end_date = st.session_state.get('end_date')
try:
data = fetch_data(ticker, start_date, end_date)
if data is not None:
data = calculate_indicators(data)
return data
else:
st.error("Failed to fetch data. Please check the stock ticker symbol and date range.")
return None
except Exception as e:
st.error(f"An error occurred: {e}")
return None
# Display content based on selected page
if page == "Analytics":
st.header("Analytics")
# Data input section
ticker = st.text_input("Stock Ticker", "BHEL.NS")
start_date = st.date_input("Start Date", pd.to_datetime("2020-01-01"))
end_date = st.date_input("End Date", pd.to_datetime("2024-09-04"))
algorithm = st.selectbox(
"Choose an Algorithm",
['Linear Regression','LSTM', 'ARIMA','Decision Tree', 'Random Forest', 'XGBoost', 'CatBoost', 'SARIMA']
)
st.session_state['ticker'] = ticker
st.session_state['start_date'] = start_date
st.session_state['end_date'] = end_date
st.session_state['algorithm'] = algorithm
# Tabs for Analyze and Visualization under Analytics
tab1, tab2 = st.tabs(["Analyze", "Visualization"])
# Analyze Tab
with tab1:
if st.button("Analyze"):
data = get_data()
if data is not None:
display_analysis(data, st.session_state.get('algorithm'))
# Visualization Tab
with tab2:
st.write("### Visualizations")
# Fetch and prepare data for visualization
data = get_data()
if data is not None:
indicators = {
'SMA_50': data['SMA_50'],
'EMA_50': data['EMA_50'],
'RSI': data['RSI'],
'MACD': data['MACD'],
'MACD_Signal': data['MACD_Signal'],
'Bollinger_High': data['Bollinger_High'],
'Bollinger_Low': data['Bollinger_Low'],
'ATR': data['ATR'],
'OBV': data['OBV']
}
# Visualization choices
choice = st.selectbox(
"Choose a type of visualization",
[
"Stock Price","Volume",
"Moving Averages",
"Feature Correlations",
"Predictions vs Actual",
"Technical Indicators",
"Risk Levels",
"Feature Importance",
"Candlestick"
]
)
try:
if choice == "Stock Price":
plot_stock_price(data, st.session_state.get('ticker'), indicators)
elif choice == "Predictions vs Actual":
future_prices, _, _, _, _ = predict_future_prices(data, st.session_state.get('algorithm'))
if future_prices is not None:
st.line_chart(pd.DataFrame({'Actual Prices': data['Close'], 'Predicted Prices': pd.Series(future_prices).values}))
else:
st.error("Failed to fetch predictions.")
logger.error("Failed to fetch predictions.")
elif choice == "Technical Indicators":
plot_technical_indicators(data, indicators)
elif choice == "Risk Levels":
plot_risk_levels(data)
elif choice == "Feature Importance":
plot_feature_importance()
elif choice == "Candlestick":
plot_candlestick(data)
elif choice == "Volume":
plot_volume(data)
elif choice == "Moving Averages":
plot_moving_averages(data)
elif choice == "Feature Correlations":
plot_feature_correlations(data)
except Exception as e:
logger.error(f"An error occurred during visualization: {e}")
st.error(f"An error occurred during visualization: {e}")
else:
st.error("Failed to fetch data. Please check the stock ticker symbol and date range.")
logger.error("Failed to fetch data. Please check the stock ticker symbol and date range.")
elif page == "Dashboard":
st.title("Stock analysis and screening tool for investors in India")
ticker = st.text_input("Enter stock ticker (e.g., TATAMOTORS.NS):").upper()
days = st.sidebar.slider("Select number of days for top movers:", 1, 30, 30)
profile = {}
if ticker:
profile = fetch_stock_profile(ticker)
if profile: # Only display profile if it's not empty
display_profile(profile)
display_quarterly_results(ticker)
display_shareholding_pattern(ticker)
display_financial_ratios(ticker)
else:
st.write("No data available for the ticker entered.")
st.sidebar.write("### Overview")
st.sidebar.write(f"Showing top gainers and losers over the past {days} day(s).")
display_dashboard()
# display_profile()
# # Display the main dashboard
# display_dashboard()
st.write("<div style='background-color: black; color: white; padding: 10px;'>Coming Soon A lot Updates.......</div>", unsafe_allow_html=True)
elif page == "Profile":
st.image("https://via.placeholder.com/150", caption="User Profile Photo")
st.write("### User Profile")
st.write("Name: Nandan Dutta")
st.write("Role: Data Analyst")
st.write("Email: [email protected]")
elif page == "Ask to AI":
st.title("Ask Stock Recommendation to AI")
st.write("Model: Meta LLaMA 3.1")
# Input fields for the user
ticker = st.text_input("Enter Stock Ticker (e.g., BHEL.NS, RELIANCE.NS):")
start_date = st.date_input("Start Date", value=None)
end_date = st.date_input("End Date", value=None)
if st.button("Get Recommendation"):
if ticker and start_date and end_date:
# Ensure dates are in the correct format
start_date_str = start_date.strftime('%Y-%m-%d')
end_date_str = end_date.strftime('%Y-%m-%d')
st.write(f"Fetching recommendation for {ticker} from {start_date_str} to {end_date_str}...")
try:
# Fetch the recommendation using the LLaMA model
recommendations = display_recommendation(ticker, start_date_str, end_date_str)
except Exception as e:
st.error(f"An error occurred: {e}")
else:
st.error("Please enter a valid ticker and date range.")
st.markdown(
"""
<style>
@keyframes blink {
0% { opacity: 1; }
50% { opacity: 0; }
100% { opacity: 1; }
}
.blinking-heart {
animation: blink 1s infinite;
}
</style>
<div style='background-color: #f1f1f1; color: #333; padding: 5px; text-align: center; border-top: 1px solid #ddd;'>
<p>Made with <span class="blinking-heart">❤️</span> from Nandan</p>
</div>
""",
unsafe_allow_html=True
)
# Display animated running disclaimer text
st.write(
"""
<div style='background-color: black; color: white; padding: 10px; border-radius: 5px;'>
<marquee behavior="scroll" direction="left" scrollamount="5" style="font-size: 14px;">
This project is for educational purposes only. The information provided here should not be used for real investment decisions. Please perform your own research and consult with a financial advisor before making any investment decisions. Use this information at your own risk.
</marquee>
</div>
""",
unsafe_allow_html=True
)
|