Delete master_card_stock_data_159_(2008_2024).py
Browse files
master_card_stock_data_159_(2008_2024).py
DELETED
@@ -1,376 +0,0 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
"""Master Card Stock Data.159 (2008-2024)
|
3 |
-
|
4 |
-
Automatically generated by Colab.
|
5 |
-
|
6 |
-
Original file is located at
|
7 |
-
https://colab.research.google.com/drive/127-oS8O1T914B2Fx1z0r0JAfHc3RJ8NB
|
8 |
-
"""
|
9 |
-
|
10 |
-
import pandas as pd
|
11 |
-
|
12 |
-
data = pd.read_csv('MVR.csv')
|
13 |
-
|
14 |
-
print(data.head())
|
15 |
-
|
16 |
-
print(data.isnull().sum())
|
17 |
-
|
18 |
-
data['Date'] = pd.to_datetime(data['Date'])
|
19 |
-
|
20 |
-
data.set_index('Date', inplace=True)
|
21 |
-
|
22 |
-
print(data.dtypes)
|
23 |
-
|
24 |
-
print(data.info())
|
25 |
-
|
26 |
-
print(data.describe())
|
27 |
-
|
28 |
-
import matplotlib.pyplot as plt
|
29 |
-
|
30 |
-
plt.figure(figsize=(14, 7))
|
31 |
-
plt.plot(data.index, data['Close_M'], label='MasterCard Close')
|
32 |
-
plt.plot(data.index, data['Close_V'], label='Visa Close')
|
33 |
-
plt.title('Stock Prices of MasterCard and Visa')
|
34 |
-
plt.xlabel('Date')
|
35 |
-
plt.ylabel('Stock Price')
|
36 |
-
plt.legend()
|
37 |
-
plt.show()
|
38 |
-
|
39 |
-
data['MA_Close_M'] = data['Close_M'].rolling(window=30).mean()
|
40 |
-
data['MA_Close_V'] = data['Close_V'].rolling(window=30).mean()
|
41 |
-
|
42 |
-
plt.figure(figsize=(14, 7))
|
43 |
-
plt.plot(data['Close_M'], label='MasterCard Close Price')
|
44 |
-
plt.plot(data['MA_Close_M'], label='MasterCard 30-Day MA')
|
45 |
-
plt.title('Moving Averages of Stock Prices')
|
46 |
-
plt.xlabel('Date')
|
47 |
-
plt.ylabel('Price')
|
48 |
-
plt.legend()
|
49 |
-
plt.show()
|
50 |
-
|
51 |
-
plt.figure(figsize=(14, 7))
|
52 |
-
plt.plot(data['Volume_M'], label='MasterCard Volume')
|
53 |
-
plt.plot(data['Volume_V'], label='Visa Volume')
|
54 |
-
plt.title('Volume of Stocks Traded')
|
55 |
-
plt.xlabel('Date')
|
56 |
-
plt.ylabel('Volume')
|
57 |
-
plt.legend()
|
58 |
-
plt.show()
|
59 |
-
|
60 |
-
data['SMA50_M'] = data['Close_M'].rolling(window=50).mean()
|
61 |
-
data['SMA200_M'] = data['Close_M'].rolling(window=200).mean()
|
62 |
-
|
63 |
-
data['SMA50_V'] = data['Close_V'].rolling(window=50).mean()
|
64 |
-
data['SMA200_V'] = data['Close_V'].rolling(window=200).mean()
|
65 |
-
|
66 |
-
plt.figure(figsize=(14, 7))
|
67 |
-
plt.plot(data.index, data['Close_M'], label='MasterCard Close')
|
68 |
-
plt.plot(data.index, data['SMA50_M'], label='MasterCard SMA50')
|
69 |
-
plt.plot(data.index, data['SMA200_M'], label='MasterCard SMA200')
|
70 |
-
plt.title('MasterCard Stock Price and Moving Averages')
|
71 |
-
plt.xlabel('Date')
|
72 |
-
plt.ylabel('Stock Price')
|
73 |
-
plt.legend()
|
74 |
-
plt.show()
|
75 |
-
|
76 |
-
plt.figure(figsize=(14, 7))
|
77 |
-
plt.plot(data.index, data['Close_V'], label='Visa Close')
|
78 |
-
plt.plot(data.index, data['SMA50_V'], label='Visa SMA50')
|
79 |
-
plt.plot(data.index, data['SMA200_V'], label='Visa SMA200')
|
80 |
-
plt.title('Visa Stock Price and Moving Averages')
|
81 |
-
plt.xlabel('Date')
|
82 |
-
plt.ylabel('Stock Price')
|
83 |
-
plt.legend()
|
84 |
-
plt.show
|
85 |
-
|
86 |
-
data['Volatility_M'] = data['Close_M'].rolling(window=30).std()
|
87 |
-
data['Volatility_V'] = data['Close_V'].rolling(window=30).std()
|
88 |
-
|
89 |
-
plt.figure(figsize=(14, 7))
|
90 |
-
plt.plot(data.index, data['Volatility_M'], label='MasterCard Volatility')
|
91 |
-
plt.plot(data.index, data['Volatility_V'], label='Visa Volatility')
|
92 |
-
plt.title('Stock Price Volatility of MasterCard and Visa')
|
93 |
-
plt.xlabel('Date')
|
94 |
-
plt.ylabel('Volatility')
|
95 |
-
plt.legend()
|
96 |
-
plt.show()
|
97 |
-
|
98 |
-
data['Return_M'] = data['Close_M'].pct_change()
|
99 |
-
data['Return_V'] = data['Close_V'].pct_change()
|
100 |
-
|
101 |
-
data['Cumulative_Return_M'] = (1 + data['Return_M']).cumprod()
|
102 |
-
data['Cumulative_Return_V'] = (1 + data['Return_V']).cumprod()
|
103 |
-
|
104 |
-
plt.figure(figsize=(14, 7))
|
105 |
-
plt.plot(data.index, data['Cumulative_Return_M'], label='MasterCard Cumulative Return')
|
106 |
-
plt.plot(data.index, data['Cumulative_Return_V'], label='Visa Cumulative Return')
|
107 |
-
plt.title('Cumulative Returns of MasterCard and Visa')
|
108 |
-
plt.xlabel('Date')
|
109 |
-
plt.ylabel('Cumulative Return')
|
110 |
-
plt.legend()
|
111 |
-
plt.show()
|
112 |
-
|
113 |
-
correlation = data[['Close_M', 'Close_V']].corr()
|
114 |
-
print(correlation)
|
115 |
-
|
116 |
-
from statsmodels.tsa.seasonal import seasonal_decompose
|
117 |
-
|
118 |
-
decomposition_M = seasonal_decompose(data['Close_M'], model='multiplicative', period=365)
|
119 |
-
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, figsize=(15, 12))
|
120 |
-
|
121 |
-
ax1.plot(decomposition_M.observed)
|
122 |
-
ax1.set_title('Observed - MasterCard')
|
123 |
-
ax2.plot(decomposition_M.trend)
|
124 |
-
ax2.set_title('Tren - MasterCard')
|
125 |
-
ax3.plot(decomposition_M.seasonal)
|
126 |
-
ax3.set_title('Seasonal - MasterCard')
|
127 |
-
ax4.plot(decomposition_M.resid)
|
128 |
-
ax4.set_title('Residual - MasterCard')
|
129 |
-
|
130 |
-
plt.tight_layout()
|
131 |
-
plt.show
|
132 |
-
|
133 |
-
decomposition_V = seasonal_decompose(data['Close_V'], model='multiplicative', period=365)
|
134 |
-
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, figsize=(15, 12))
|
135 |
-
|
136 |
-
ax1.plot(decomposition_V.observed)
|
137 |
-
ax1.set_title('Observed - Visa')
|
138 |
-
ax2.plot(decomposition_V.trend)
|
139 |
-
ax2.set_title('Trend - Visa')
|
140 |
-
ax3.plot(decomposition_V.seasonal)
|
141 |
-
ax3.set_title('Seasonal - Visa')
|
142 |
-
ax4.plot(decomposition_V.resid)
|
143 |
-
ax4.set_title('Residual - Visa')
|
144 |
-
|
145 |
-
plt.tight_layout()
|
146 |
-
plt.show()
|
147 |
-
|
148 |
-
from statsmodels.tsa.stattools import adfuller
|
149 |
-
|
150 |
-
def adf_test(series):
|
151 |
-
result = adfuller(series.dropna())
|
152 |
-
print('ADF Statistic:', result[0])
|
153 |
-
print('p-value:', result[1])
|
154 |
-
for key, value in result[4].items():
|
155 |
-
print('Critial Values:')
|
156 |
-
print(f' {key}, {value}')
|
157 |
-
|
158 |
-
print("ADF Test for MasterCard Close Price:")
|
159 |
-
adf_test(data['Close_M'])
|
160 |
-
|
161 |
-
print("\ADF Test for Visa Close Price:")
|
162 |
-
adf_test(data['Close_V'])
|
163 |
-
|
164 |
-
import numpy as np
|
165 |
-
from sklearn.preprocessing import MinMaxScaler
|
166 |
-
from keras.models import Sequential
|
167 |
-
from keras.layers import LSTM, Dense, Input
|
168 |
-
from sklearn.metrics import mean_squared_error
|
169 |
-
|
170 |
-
scaler = MinMaxScaler(feature_range=(0, 1))
|
171 |
-
scaled_data_M = scaler.fit_transform(data[['Close_M']])
|
172 |
-
scaled_data_V = scaler.fit_transform(data[['Close_V']])
|
173 |
-
|
174 |
-
train_len_M = int(len(scaled_data_M) * 0.8)
|
175 |
-
train_len_V = int(len(scaled_data_V) * 0.8)
|
176 |
-
|
177 |
-
train_data_M = scaled_data_M[:train_len_M]
|
178 |
-
test_data_M = scaled_data_M[train_len_M:]
|
179 |
-
|
180 |
-
train_data_V = scaled_data_V[:train_len_V]
|
181 |
-
test_data_V = scaled_data_V[train_len_V:]
|
182 |
-
|
183 |
-
def create_sequences(data, seq_length):
|
184 |
-
x = []
|
185 |
-
y = []
|
186 |
-
for i in range(seq_length, len(data)):
|
187 |
-
x.append(data[i-seq_length:i, 0])
|
188 |
-
y.append(data[i, 0])
|
189 |
-
return np.array(x), np.array(y)
|
190 |
-
|
191 |
-
seq_length = 60
|
192 |
-
x_train_M, y_train_M = create_sequences(train_data_M, seq_length)
|
193 |
-
x_test_M, y_test_M = create_sequences(test_data_M, seq_length)
|
194 |
-
|
195 |
-
x_train_V, y_train_V = create_sequences(train_data_V, seq_length)
|
196 |
-
x_test_V, y_test_V = create_sequences(test_data_V, seq_length)
|
197 |
-
|
198 |
-
x_train_M = np.reshape(x_train_M, (x_train_M.shape[0], x_train_M.shape[1], 1))
|
199 |
-
x_test_M = np.reshape(x_test_M, (x_test_M.shape[0], x_test_M.shape[1], 1))
|
200 |
-
|
201 |
-
x_train_V = np.reshape(x_train_V, (x_train_V.shape[0], x_train_V.shape[1], 1))
|
202 |
-
x_test_V = np.reshape(x_test_V, (x_test_V.shape[0], x_test_V.shape[1], 1))
|
203 |
-
|
204 |
-
model_M = Sequential()
|
205 |
-
model_M.add(Input(shape=(x_train_M.shape[1], 1)))
|
206 |
-
model_M.add(LSTM(units=50, return_sequences=True))
|
207 |
-
model_M.add(LSTM(units=50, return_sequences=False))
|
208 |
-
model_M.add(Dense(units=25))
|
209 |
-
model_M.add(Dense(units=1))
|
210 |
-
|
211 |
-
model_M.compile(optimizer='adam', loss='mean_squared_error')
|
212 |
-
|
213 |
-
model_V = Sequential()
|
214 |
-
model_V.add(Input(shape=(x_train_V.shape[1], 1)))
|
215 |
-
model_V.add(LSTM(units=50, return_sequences=True))
|
216 |
-
model_V.add(LSTM(units=50, return_sequences=False))
|
217 |
-
model_V.add(Dense(units=25))
|
218 |
-
model_V.add(Dense(units=1))
|
219 |
-
|
220 |
-
model_V.compile(optimizer ='adam', loss='mean_squared_error')
|
221 |
-
|
222 |
-
model_M.fit(x_train_M, y_train_M, batch_size=32, epochs=100)
|
223 |
-
model_V.fit(x_train_V, y_train_V, batch_size=32, epochs=100)
|
224 |
-
|
225 |
-
predictions_M = model_M.predict(x_test_M)
|
226 |
-
predictions_M = scaler.inverse_transform(predictions_M)
|
227 |
-
|
228 |
-
predictions_V = model_V.predict(x_test_V)
|
229 |
-
predictions_V = scaler.inverse_transform(predictions_V)
|
230 |
-
|
231 |
-
rmse_M = np.sqrt(mean_squared_error(y_test_M, predictions_M))
|
232 |
-
rmse_V = np.sqrt(mean_squared_error(y_test_V, predictions_V))
|
233 |
-
|
234 |
-
print(f'RMSE for MasterCard: {rmse_M}')
|
235 |
-
print(f'RMSE for Visa: {rmse_V}')
|
236 |
-
|
237 |
-
train_M = data[:train_len_M]['Close_M']
|
238 |
-
valid_M = data[train_len_M:train_len_M + len(predictions_M)]['Close_M']
|
239 |
-
valid_M = valid_M.to_frame()
|
240 |
-
valid_M['Predictions'] = predictions_M
|
241 |
-
|
242 |
-
train_V = data[:train_len_V]['Close_V']
|
243 |
-
valid_V = data[train_len_V:train_len_V + len(predictions_V)]['Close_V']
|
244 |
-
valid_V = valid_V.to_frame()
|
245 |
-
valid_V['Predictions'] = predictions_V
|
246 |
-
|
247 |
-
plt.figure(figsize=(14, 7))
|
248 |
-
plt.plot(train_M, label='Train - MasterCard')
|
249 |
-
plt.plot(valid_M['Close_M'], label='Valid - MasterCard')
|
250 |
-
plt.plot(valid_M['Predictions'], label='Predictions - MasterCard')
|
251 |
-
plt.legend()
|
252 |
-
plt.show()
|
253 |
-
|
254 |
-
plt.figure(figsize=(14, 7))
|
255 |
-
plt.plot(train_V, label ='Train -Visa')
|
256 |
-
plt.plot(valid_V['Close_V'], label='Valid -Visa')
|
257 |
-
plt.plot(valid_V['Predictions'], label='Predictions - Visa')
|
258 |
-
plt.legend()
|
259 |
-
plt.show()
|
260 |
-
|
261 |
-
from statsmodels.tsa.arima.model import ARIMA
|
262 |
-
|
263 |
-
data = data.asfreq('B')
|
264 |
-
|
265 |
-
train_size = int(len(data) * 0.8)
|
266 |
-
train, test = data['Close_M'][:train_size], data['Close_M'][train_size:]
|
267 |
-
|
268 |
-
model = ARIMA(train, order=(5, 1, 0))
|
269 |
-
model_fit = model.fit()
|
270 |
-
print(model_fit.summary())
|
271 |
-
|
272 |
-
predictions = model_fit.forecast(steps=len(test))
|
273 |
-
predictions = pd.Series(predictions, index=test.index)
|
274 |
-
|
275 |
-
plt.figure(figsize=(14, 7))
|
276 |
-
plt.plot(train, label='Training Data')
|
277 |
-
plt.plot(test, label='Test Data')
|
278 |
-
plt.plot(predictions, label='Predicted Data')
|
279 |
-
plt.title('ARIMA Model Predictions for MasterCard')
|
280 |
-
plt.xlabel('Date')
|
281 |
-
plt.ylabel('Price')
|
282 |
-
plt.legend()
|
283 |
-
plt.show()
|
284 |
-
|
285 |
-
data = data.asfreq('B')
|
286 |
-
|
287 |
-
train_size = int(len(data) * 0.8)
|
288 |
-
train_V, test_V = data['Close_V'][:train_size], data['Close_V'][train_size:]
|
289 |
-
|
290 |
-
model_V = ARIMA(train_V, order=(5, 1, 0))
|
291 |
-
model_fit_V = model_V.fit()
|
292 |
-
print(model_fit_V.summary())
|
293 |
-
|
294 |
-
predictions_V = model_fit_V.forecast(steps=len(test_V))
|
295 |
-
predictions_V = pd.Series(predictions_V, index=test_V.index)
|
296 |
-
|
297 |
-
plt.figure(figsize=(14, 7))
|
298 |
-
plt.plot(train_V, label='Training Data')
|
299 |
-
plt.plot(test_V, label='Test Data')
|
300 |
-
plt.plot(predictions_V, label='Predicted Data'),
|
301 |
-
plt.title('ARIMA Model Predictions for Visa')
|
302 |
-
plt.xlabel('Date')
|
303 |
-
plt.ylabel('Price')
|
304 |
-
plt.legend()
|
305 |
-
plt.show()
|
306 |
-
|
307 |
-
import warnings
|
308 |
-
warnings.filterwarnings('ignore')
|
309 |
-
import plotly.graph_objects as go
|
310 |
-
|
311 |
-
def predict_stock_price(data, column_name, forecast_periods):
|
312 |
-
train_size = int(len(data) * 0.8)
|
313 |
-
train, test = data[column_name][:train_size], data[column_name][train_size:]
|
314 |
-
|
315 |
-
model = ARIMA(train, order=(5, 1, 0))
|
316 |
-
model_fit = model.fit()
|
317 |
-
|
318 |
-
future_dates = pd.date_range(start=data.index[-1], periods=forecast_periods, freq='B')
|
319 |
-
forecast = model_fit.forecast(steps=forecast_periods)
|
320 |
-
forecast_series = pd.Series(forecast, index=future_dates)
|
321 |
-
|
322 |
-
return forecast_series
|
323 |
-
|
324 |
-
forecast_periods = 3 * 252
|
325 |
-
forecast_M = predict_stock_price(data, 'Close_M', forecast_periods)
|
326 |
-
forecast_V = predict_stock_price(data, 'Close_V', forecast_periods)
|
327 |
-
|
328 |
-
extended_data_M = pd.concat([data['Close_M'], forecast_M])
|
329 |
-
extended_data_V = pd.concat([data['Close_V'], forecast_V])
|
330 |
-
|
331 |
-
candlestick_data_M = pd.DataFrame({
|
332 |
-
'Date': extended_data_M.index,
|
333 |
-
'Open': extended_data_M.shift(1).fillna(method='bfill'),
|
334 |
-
'High': extended_data_M.rolling(2).max(),
|
335 |
-
'Low': extended_data_M.rolling(2).min(),
|
336 |
-
'Close': extended_data_M
|
337 |
-
}).reset_index(drop=True)
|
338 |
-
|
339 |
-
candlestick_data_V = pd.DataFrame({
|
340 |
-
'Date': extended_data_V.index,
|
341 |
-
'Open': extended_data_V.shift(1).fillna(method='bfill'),
|
342 |
-
'High': extended_data_V.rolling(2).max(),
|
343 |
-
'Low': extended_data_V.rolling(2).min(),
|
344 |
-
'Close': extended_data_V
|
345 |
-
}).reset_index(drop=True)
|
346 |
-
|
347 |
-
fig = go.Figure()
|
348 |
-
|
349 |
-
fig.add_trace(go.Candlestick(
|
350 |
-
x=candlestick_data_M['Date'],
|
351 |
-
open=candlestick_data_M['Open'],
|
352 |
-
high=candlestick_data_M['High'],
|
353 |
-
low=candlestick_data_M['Low'],
|
354 |
-
close=candlestick_data_M['Close'],
|
355 |
-
name='MasterCard',
|
356 |
-
increasing_line_color='blue', decreasing_line_color='red'
|
357 |
-
))
|
358 |
-
|
359 |
-
fig.add_trace(go.Candlestick(
|
360 |
-
x=candlestick_data_V['Date'],
|
361 |
-
open=candlestick_data_V['Open'],
|
362 |
-
high=candlestick_data_V['High'],
|
363 |
-
low=candlestick_data_V['Low'],
|
364 |
-
close=candlestick_data_V['Close'],
|
365 |
-
name='Visa',
|
366 |
-
increasing_line_color='green', decreasing_line_color='orange'
|
367 |
-
))
|
368 |
-
|
369 |
-
fig.update_layout(
|
370 |
-
title='MasterCard and Visa Stock Prices (Historical and Predicted)',
|
371 |
-
xaxis_title='Date',
|
372 |
-
yaxis_title='Price',
|
373 |
-
xaxis_rangeslider_visible=False
|
374 |
-
)
|
375 |
-
|
376 |
-
fig.show()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|