├── 01.PNG ├── 02.PNG ├── 03.PNG ├── 04.PNG ├── 05.PNG ├── 06.PNG ├── 07.PNG ├── README.md └── new.py /01.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Krishnasahu810/Alpha-Vantage-Stock-Visualization/HEAD/01.PNG -------------------------------------------------------------------------------- /02.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Krishnasahu810/Alpha-Vantage-Stock-Visualization/HEAD/02.PNG -------------------------------------------------------------------------------- /03.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Krishnasahu810/Alpha-Vantage-Stock-Visualization/HEAD/03.PNG -------------------------------------------------------------------------------- /04.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Krishnasahu810/Alpha-Vantage-Stock-Visualization/HEAD/04.PNG -------------------------------------------------------------------------------- /05.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Krishnasahu810/Alpha-Vantage-Stock-Visualization/HEAD/05.PNG -------------------------------------------------------------------------------- /06.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Krishnasahu810/Alpha-Vantage-Stock-Visualization/HEAD/06.PNG -------------------------------------------------------------------------------- /07.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Krishnasahu810/Alpha-Vantage-Stock-Visualization/HEAD/07.PNG -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This project focuses on analyzing stock market data using Python libraries such as Pandas, Matplotlib, and Seaborn. It involves detailed exploration of stock prices and trading volumes, prediction of future stock prices using Linear Regression, and analysis of market correlations between different stocks. Various visualizations like line plots for closing prices, daily returns, and stock performance comparisons are created to better understand stock behavior. The objective is to extract meaningful insights from the data, identify market trends, and build predictive models to assist in better decision-making for investors and financial analysts. This project emphasizes real-world application of data science skills. 2 | -------------------------------------------------------------------------------- /new.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | import certifi 5 | print(certifi.where()) 6 | 7 | 8 | import os 9 | import certifi 10 | import numpy as np 11 | import pandas as pd 12 | import matplotlib.pyplot as plt 13 | import seaborn as sns 14 | from alpha_vantage.timeseries import TimeSeries 15 | from sklearn.model_selection import train_test_split 16 | from sklearn.linear_model import LinearRegression 17 | from sklearn.metrics import mean_absolute_error, mean_squared_error 18 | 19 | # Fix SSL certificate issue 20 | os.environ['SSL_CERT_FILE'] = certifi.where() 21 | 22 | # Alpha Vantage API Key 23 | API_KEY = "SQA4D550151BL3GJ" # Replace with your API Key 24 | 25 | # Function to Fetch Large Stock Data 26 | def get_stock_data(symbol, interval="daily"): # symbol: the stock ticker symbol, e.g., "AAPL" for Apple, "GOOG" for Google. 27 | # interval: how frequently you want the stock data (default is "daily"). 28 | ts = TimeSeries(key=API_KEY, output_format="pandas") # TimeSeries is a class provided by the alpha_vantage library. 29 | # output_format="pandas" means the data will be automatically returned in a pandas DataFrame (instead of JSON). 30 | if interval == "daily": 31 | data, meta_data = ts.get_daily(symbol=symbol, outputsize="full") 32 | else: 33 | raise ValueError("Invalid interval") 34 | 35 | data.columns = ["Open", "High", "Low", "Close", "Volume"] 36 | data = data.iloc[::-1] # Reverse order to ascending 37 | data.index = pd.to_datetime(data.index) 38 | return data.head(5000) # Limit to 5000 rows 39 | 40 | # Fetch Data 41 | symbol = "AAPL" 42 | df = get_stock_data(symbol) 43 | 44 | # 1️⃣ Stock Price Analysis 45 | df["SMA_50"] = df["Close"].rolling(window=50).mean() 46 | df["SMA_200"] = df["Close"].rolling(window=200).mean() 47 | plt.figure(figsize=(12, 5)) 48 | plt.plot(df["Close"], label="Close Price") 49 | plt.plot(df["SMA_50"], label="50-Day SMA", linestyle="dashed") 50 | plt.plot(df["SMA_200"], label="200-Day SMA", linestyle="dashed") 51 | plt.title(f"{symbol} Stock Price & Moving Averages") 52 | plt.legend() 53 | plt.show() 54 | 55 | # 2️⃣ Trading Volume Insights 56 | plt.figure(figsize=(12, 5)) 57 | plt.plot(df["Volume"], label="Trading Volume", color="purple") 58 | plt.title(f"{symbol} Trading Volume Over Time") 59 | plt.legend() 60 | plt.show() 61 | 62 | # 3️⃣ Stock Price Prediction (Linear Regression) 63 | df["Target"] = df["Close"].shift(-5) # Predict 5 days ahead 64 | df.dropna(inplace=True) 65 | X = df[["Open", "High", "Low", "Close"]] 66 | y = df["Target"] 67 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 68 | model = LinearRegression() 69 | model.fit(X_train, y_train) 70 | y_pred = model.predict(X_test) 71 | print(f"MAE: {mean_absolute_error(y_test, y_pred):.2f}") 72 | print(f"RMSE: {np.sqrt(mean_squared_error(y_test, y_pred)):.2f}") 73 | plt.figure(figsize=(12, 5)) 74 | plt.plot(y_test.values, label="Actual") 75 | plt.plot(y_pred, label="Predicted", linestyle="dashed") 76 | plt.title("Stock Price Prediction") 77 | plt.legend() 78 | plt.show() 79 | 80 | # 4️⃣ Market Correlation Analysis 81 | symbols = ["AAPL", "MSFT", "GOOGL"] 82 | stock_data = {} 83 | for sym in symbols: 84 | stock_data[sym] = get_stock_data(sym)["Close"] 85 | df_corr = pd.DataFrame(stock_data) 86 | sns.heatmap(df_corr.corr(), annot=True, cmap="coolwarm") 87 | plt.title("Stock Correlation Matrix") 88 | plt.show() 89 | 90 | # 5️⃣ Stock Performance Comparison 91 | returns = df_corr.pct_change().mean() * 252 # Annualized Returns 92 | volatility = df_corr.pct_change().std() * np.sqrt(252) # Annualized Volatility 93 | performance_df = pd.DataFrame({"Returns": returns, "Volatility": volatility}) 94 | print(performance_df) 95 | plt.figure(figsize=(10, 6)) 96 | sns.scatterplot(x=volatility, y=returns, hue=returns.index, s=100) 97 | plt.xlabel("Volatility (Risk)") 98 | plt.ylabel("Annualized Returns") 99 | plt.title("Stock Performance (Risk vs. Return)") 100 | plt.legend() 101 | plt.show() 102 | 103 | 104 | import seaborn as sns 105 | import matplotlib.pyplot as plt 106 | 107 | # Create a Seaborn Lineplot for Closing Prices 108 | plt.figure(figsize=(12, 6)) 109 | sns.lineplot(data=df, x=df.index, y="Close", color="blue") 110 | plt.title(f"{symbol} Closing Price Over Time", fontsize=16) 111 | plt.xlabel("Date", fontsize=14) 112 | plt.ylabel("Close Price", fontsize=14) 113 | plt.xticks(rotation=45) 114 | plt.grid(True) 115 | plt.show() 116 | 117 | 118 | # Calculate daily returns 119 | df['Daily Return'] = df['Close'].pct_change() 120 | 121 | # Seaborn KDE plot 122 | plt.figure(figsize=(12,6)) 123 | sns.kdeplot(df['Daily Return'].dropna(), fill=True, color="green", alpha=0.6) 124 | plt.title(f"{symbol} Daily Return Distribution", fontsize=16) 125 | plt.xlabel("Daily Return", fontsize=14) 126 | plt.ylabel("Density", fontsize=14) 127 | plt.grid(True) 128 | plt.show() 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | # import os 149 | # import certifi 150 | # os.environ["SSL_CERT_FILE"] = certifi.where() 151 | 152 | 153 | 154 | # import os 155 | # import certifi 156 | # import numpy as np 157 | # import pandas as pd 158 | # import matplotlib.pyplot as plt 159 | # import seaborn as sns 160 | # import plotly.graph_objects as go 161 | # import plotly.express as px 162 | # from alpha_vantage.timeseries import TimeSeries 163 | # from sklearn.model_selection import train_test_split 164 | # from sklearn.linear_model import LinearRegression 165 | # from sklearn.metrics import mean_absolute_error, mean_squared_error 166 | 167 | # import requests 168 | 169 | # url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=AAPL&outputsize=full&apikey=VYIATSQKQZ41EHOX&datatype=json" 170 | # response = requests.get(url, verify=False) 171 | 172 | 173 | 174 | 175 | # # Fix SSL certificate issue 176 | # os.environ['SSL_CERT_FILE'] = certifi.where() 177 | 178 | # # Alpha Vantage API Key 179 | # API_KEY = "VYIATSQKQZ41EHOX" # Replace with your API Key 180 | 181 | # # Function to Fetch Large Stock Data 182 | # def get_stock_data(symbol, interval="daily"): 183 | # ts = TimeSeries(key=API_KEY, output_format="pandas") 184 | # if interval == "daily": 185 | # data, meta_data = ts.get_daily(symbol=symbol, outputsize="full") 186 | # else: 187 | # raise ValueError("Invalid interval") 188 | 189 | # data.columns = ["Open", "High", "Low", "Close", "Volume"] 190 | # data = data.iloc[::-1] # Reverse order to ascending 191 | # data.index = pd.to_datetime(data.index) 192 | # return data.head(5000) # Limit to 5000 rows 193 | 194 | # # Fetch Data 195 | # symbol = "AAPL" 196 | # df = get_stock_data(symbol) 197 | 198 | # # 1️⃣ Stock Price Analysis 199 | # df["SMA_50"] = df["Close"].rolling(window=50).mean() 200 | # df["SMA_200"] = df["Close"].rolling(window=200).mean() 201 | # fig = go.Figure() 202 | # fig.add_trace(go.Scatter(x=df.index, y=df["Close"], mode='lines', name='Close Price')) 203 | # fig.add_trace(go.Scatter(x=df.index, y=df["SMA_50"], mode='lines', name='50-Day SMA', line=dict(dash='dash'))) 204 | # fig.add_trace(go.Scatter(x=df.index, y=df["SMA_200"], mode='lines', name='200-Day SMA', line=dict(dash='dot'))) 205 | # fig.update_layout(title=f"{symbol} Stock Price & Moving Averages", xaxis_title='Date', yaxis_title='Price', template='plotly_dark') 206 | # fig.show() 207 | 208 | # # 2️⃣ Trading Volume Insights 209 | # fig = px.line(df, x=df.index, y="Volume", title=f"{symbol} Trading Volume Over Time", labels={'Volume': 'Trading Volume'}) 210 | # fig.update_layout(template='plotly_dark') 211 | # fig.show() 212 | 213 | # # 3️⃣ Stock Price Prediction (Linear Regression) 214 | # df["Target"] = df["Close"].shift(-5) # Predict 5 days ahead 215 | # df.dropna(inplace=True) 216 | # X = df[["Open", "High", "Low", "Close"]] 217 | # y = df["Target"] 218 | # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 219 | # model = LinearRegression() 220 | # model.fit(X_train, y_train) 221 | # y_pred = model.predict(X_test) 222 | # print(f"MAE: {mean_absolute_error(y_test, y_pred):.2f}") 223 | # print(f"RMSE: {np.sqrt(mean_squared_error(y_test, y_pred)):.2f}") 224 | # fig = go.Figure() 225 | # fig.add_trace(go.Scatter(y=y_test.values, mode='lines', name='Actual')) 226 | # fig.add_trace(go.Scatter(y=y_pred, mode='lines', name='Predicted', line=dict(dash='dash'))) 227 | # fig.update_layout(title="Stock Price Prediction", xaxis_title='Days', yaxis_title='Price', template='plotly_dark') 228 | # fig.show() 229 | 230 | # # 4️⃣ Market Correlation Analysis 231 | # symbols = ["AAPL", "MSFT", "GOOGL"] 232 | # stock_data = {} 233 | # for sym in symbols: 234 | # stock_data[sym] = get_stock_data(sym)["Close"] 235 | # df_corr = pd.DataFrame(stock_data) 236 | # fig = px.imshow(df_corr.corr(), text_auto=True, title="Stock Correlation Matrix", color_continuous_scale='RdBu') 237 | # fig.show() 238 | 239 | # # 5️⃣ Stock Performance Comparison 240 | # returns = df_corr.pct_change().mean() * 252 # Annualized Returns 241 | # volatility = df_corr.pct_change().std() * np.sqrt(252) # Annualized Volatility 242 | # performance_df = pd.DataFrame({"Returns": returns, "Volatility": volatility}) 243 | # fig = px.scatter(performance_df, x="Volatility", y="Returns", text=performance_df.index, size=[10]*len(performance_df), title="Stock Performance (Risk vs. Return)", labels={'Volatility': 'Risk', 'Returns': 'Annualized Return'}) 244 | # fig.update_traces(textposition='top center') 245 | # fig.show() 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | # import os 256 | # import certifi 257 | # import numpy as np 258 | # import pandas as pd 259 | # import plotly.graph_objects as go 260 | # import plotly.express as px 261 | # from alpha_vantage.timeseries import TimeSeries 262 | # from sklearn.model_selection import train_test_split 263 | # from sklearn.linear_model import LinearRegression 264 | # from sklearn.metrics import mean_absolute_error, mean_squared_error 265 | 266 | # # Fix SSL certificate issue 267 | # os.environ["SSL_CERT_FILE"] = certifi.where() 268 | 269 | # # Alpha Vantage API Key 270 | # API_KEY = "VYIATSQKQZ41EHOX" # Replace with your actual API Key 271 | 272 | # # Function to Fetch Stock Data 273 | # def get_stock_data(symbol): 274 | # ts = TimeSeries(key=API_KEY, output_format="pandas") 275 | # data, _ = ts.get_daily(symbol=symbol, outputsize="full") 276 | # data.columns = ["Open", "High", "Low", "Close", "Volume"] 277 | # data = data.iloc[::-1] # Reverse to ascending order 278 | # data.index = pd.to_datetime(data.index) 279 | # return data.head(5000) # Limit to 5000 rows 280 | 281 | # # Fetch Data 282 | # symbol = "AAPL" 283 | # df = get_stock_data(symbol) 284 | 285 | # # Stock Price Analysis with Moving Averages 286 | # df["SMA_50"] = df["Close"].rolling(window=50).mean() 287 | # df["SMA_200"] = df["Close"].rolling(window=200).mean() 288 | 289 | # fig = go.Figure() 290 | # fig.add_trace(go.Scatter(x=df.index, y=df["Close"], mode='lines', name='Close Price')) 291 | # fig.add_trace(go.Scatter(x=df.index, y=df["SMA_50"], mode='lines', name='50-Day SMA', line=dict(dash='dash'))) 292 | # fig.add_trace(go.Scatter(x=df.index, y=df["SMA_200"], mode='lines', name='200-Day SMA', line=dict(dash='dot'))) 293 | # fig.update_layout(title=f"{symbol} Stock Price & Moving Averages", template='plotly_dark') 294 | # fig.show() 295 | 296 | # # Trading Volume Insights 297 | # fig = px.line(df, x=df.index, y="Volume", title=f"{symbol} Trading Volume Over Time") 298 | # fig.update_layout(template='plotly_dark') 299 | # fig.show() 300 | 301 | # # Stock Price Prediction (Linear Regression) 302 | # df["Target"] = df["Close"].shift(-5) # Predict 5 days ahead 303 | # df.dropna(inplace=True) 304 | 305 | # X = df[["Open", "High", "Low", "Close"]] 306 | # y = df["Target"] 307 | # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 308 | 309 | # model = LinearRegression() 310 | # model.fit(X_train, y_train) 311 | # y_pred = model.predict(X_test) 312 | 313 | # print(f"MAE: {mean_absolute_error(y_test, y_pred):.2f}") 314 | # print(f"RMSE: {np.sqrt(mean_squared_error(y_test, y_pred)):.2f}") 315 | 316 | # fig = go.Figure() 317 | # fig.add_trace(go.Scatter(y=y_test.values, mode='lines', name='Actual')) 318 | # fig.add_trace(go.Scatter(y=y_pred, mode='lines', name='Predicted', line=dict(dash='dash'))) 319 | # fig.update_layout(title="Stock Price Prediction", template='plotly_dark') 320 | # fig.show() 321 | 322 | # # Market Correlation Analysis 323 | # symbols = ["AAPL", "MSFT", "GOOGL"] 324 | # stock_data = {sym: get_stock_data(sym)["Close"] for sym in symbols} 325 | # df_corr = pd.DataFrame(stock_data) 326 | 327 | # fig = px.imshow(df_corr.corr(), text_auto=True, title="Stock Correlation Matrix", color_continuous_scale='RdBu') 328 | # fig.show() 329 | 330 | # # Stock Performance Comparison 331 | # returns = df_corr.pct_change(fill_method=None).mean() * 252 # Annualized Returns 332 | # volatility = df_corr.pct_change(fill_method=None).std() * np.sqrt(252) # Annualized Volatility 333 | 334 | # performance_df = pd.DataFrame({"Returns": returns, "Volatility": volatility}) 335 | 336 | # fig = px.scatter(performance_df, x="Volatility", y="Returns", text=performance_df.index, size=[10]*len(performance_df), 337 | # title="Stock Performance (Risk vs. Return)") 338 | # fig.update_traces(textposition='top center') 339 | # fig.show() 340 | --------------------------------------------------------------------------------