ratulsur commited on
Commit
d07df27
·
verified ·
1 Parent(s): f7577f0

Create long_term_analysis.py

Browse files
Files changed (1) hide show
  1. pages/long_term_analysis.py +111 -0
pages/long_term_analysis.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ import numpy as np
5
+ import matplotlib.pyplot as plt
6
+ import seaborn as sns
7
+ from datetime import datetime, timedelta
8
+
9
+ # Page Configuration
10
+ st.set_page_config(page_title="10-Year Market Analysis", page_icon="📊", layout="wide")
11
+
12
+ # Sidebar Controls
13
+ st.sidebar.title("Long-Term Analysis")
14
+ symbol = st.sidebar.text_input("Enter Stock Symbol", value="AAPL", help="Example: AAPL, MSFT, TSLA, NIFTY50")
15
+
16
+ # Get Date Range (Last 10 Years)
17
+ end_date = datetime.today()
18
+ start_date = end_date - timedelta(days=365*10)
19
+
20
+ # Fetch Data Function
21
+ @st.cache_data
22
+ def fetch_long_term_data(symbol):
23
+ try:
24
+ data = yf.download(symbol, start=start_date.strftime('%Y-%m-%d'), end=end_date.strftime('%Y-%m-%d'))
25
+ return data
26
+ except Exception as e:
27
+ st.error(f"Error fetching data: {e}")
28
+ return None
29
+
30
+ # Fetch Data
31
+ df = fetch_long_term_data(symbol)
32
+
33
+ # Check if Data Exists
34
+ if df is not None and not df.empty:
35
+ st.write(f"### {symbol} - Historical Data (Last 10 Years)")
36
+
37
+ # Convert index to date column
38
+ df.reset_index(inplace=True)
39
+
40
+ # Exploratory Data Analysis (EDA)
41
+ st.subheader("1️⃣ Exploratory Data Analysis (EDA)")
42
+
43
+ col1, col2 = st.columns(2)
44
+
45
+ with col1:
46
+ st.write("**Basic Statistics**")
47
+ st.write(df.describe())
48
+
49
+ with col2:
50
+ st.write("**Missing Values**")
51
+ st.write(df.isnull().sum())
52
+
53
+ # Data Visualization
54
+ st.subheader("2️⃣ Data Visualization")
55
+
56
+ # Plot Closing Price
57
+ fig, ax = plt.subplots(figsize=(12, 6))
58
+ ax.plot(df["Date"], df["Close"], label="Close Price", color="blue")
59
+ ax.set_title(f"{symbol} - Closing Price Trend (10 Years)")
60
+ ax.set_xlabel("Year")
61
+ ax.set_ylabel("Stock Price (USD)")
62
+ ax.legend()
63
+ st.pyplot(fig)
64
+
65
+ # Moving Averages
66
+ df["SMA_50"] = df["Close"].rolling(window=50).mean()
67
+ df["SMA_200"] = df["Close"].rolling(window=200).mean()
68
+
69
+ # Plot Moving Averages
70
+ fig, ax = plt.subplots(figsize=(12, 6))
71
+ ax.plot(df["Date"], df["Close"], label="Close Price", color="gray", alpha=0.5)
72
+ ax.plot(df["Date"], df["SMA_50"], label="50-Day SMA", color="blue")
73
+ ax.plot(df["Date"], df["SMA_200"], label="200-Day SMA", color="red")
74
+ ax.set_title(f"{symbol} - Moving Averages (50 & 200 Days)")
75
+ ax.set_xlabel("Year")
76
+ ax.set_ylabel("Stock Price (USD)")
77
+ ax.legend()
78
+ st.pyplot(fig)
79
+
80
+ # Volatility Analysis
81
+ df["Volatility"] = df["Close"].pct_change().rolling(window=30).std()
82
+
83
+ fig, ax = plt.subplots(figsize=(12, 6))
84
+ ax.plot(df["Date"], df["Volatility"], label="30-Day Volatility", color="purple")
85
+ ax.set_title(f"{symbol} - Volatility Over Time (30-Day Rolling)")
86
+ ax.set_xlabel("Year")
87
+ ax.set_ylabel("Volatility")
88
+ ax.legend()
89
+ st.pyplot(fig)
90
+
91
+ # Volume Analysis
92
+ fig, ax = plt.subplots(figsize=(12, 6))
93
+ ax.bar(df["Date"], df["Volume"], color="green", alpha=0.5)
94
+ ax.set_title(f"{symbol} - Trading Volume Over 10 Years")
95
+ ax.set_xlabel("Year")
96
+ ax.set_ylabel("Volume")
97
+ st.pyplot(fig)
98
+
99
+ # Correlation Heatmap
100
+ st.subheader("3️⃣ Correlation Analysis")
101
+ correlation_matrix = df[["Open", "High", "Low", "Close", "Volume"]].corr()
102
+ fig, ax = plt.subplots(figsize=(8, 6))
103
+ sns.heatmap(correlation_matrix, annot=True, cmap="coolwarm", fmt=".2f", linewidths=0.5, ax=ax)
104
+ st.pyplot(fig)
105
+
106
+ # Show Data Table
107
+ st.write("### Raw Data (Last 10 Rows)")
108
+ st.dataframe(df.tail(10))
109
+
110
+ else:
111
+ st.warning("No data found. Please check the stock symbol.")