File size: 11,309 Bytes
0dd9440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import pandas as pd

data = pd.read_csv('MVR.csv')

print(data.head())

print(data.isnull().sum())

data['Date'] = pd.to_datetime(data['Date'])

data.set_index('Date', inplace=True)

print(data.dtypes)

print(data.info())

print(data.describe())

import matplotlib.pyplot as plt

plt.figure(figsize=(14, 7))
plt.plot(data.index, data['Close_M'], label='MasterCard Close')
plt.plot(data.index, data['Close_V'], label='Visa Close')
plt.title('Stock Prices of MasterCard and Visa')
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.legend()
plt.show()

data['MA_Close_M'] = data['Close_M'].rolling(window=30).mean()
data['MA_Close_V'] = data['Close_V'].rolling(window=30).mean()

plt.figure(figsize=(14, 7))
plt.plot(data['Close_M'], label='MasterCard Close Price')
plt.plot(data['MA_Close_M'], label='MasterCard 30-Day MA')
plt.title('Moving Averages of Stock Prices')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()

plt.figure(figsize=(14, 7))
plt.plot(data['Volume_M'], label='MasterCard Volume')
plt.plot(data['Volume_V'], label='Visa Volume')
plt.title('Volume of Stocks Traded')
plt.xlabel('Date')
plt.ylabel('Volume')
plt.legend()
plt.show()

data['SMA50_M'] = data['Close_M'].rolling(window=50).mean()
data['SMA200_M'] = data['Close_M'].rolling(window=200).mean()

data['SMA50_V'] = data['Close_V'].rolling(window=50).mean()
data['SMA200_V'] = data['Close_V'].rolling(window=200).mean()

plt.figure(figsize=(14, 7))
plt.plot(data.index, data['Close_M'], label='MasterCard Close')
plt.plot(data.index, data['SMA50_M'], label='MasterCard SMA50')
plt.plot(data.index, data['SMA200_M'], label='MasterCard SMA200')
plt.title('MasterCard Stock Price and Moving Averages')
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.legend()
plt.show()

plt.figure(figsize=(14, 7))
plt.plot(data.index, data['Close_V'], label='Visa Close')
plt.plot(data.index, data['SMA50_V'], label='Visa SMA50')
plt.plot(data.index, data['SMA200_V'], label='Visa SMA200')
plt.title('Visa Stock Price and Moving Averages')
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.legend()
plt.show

data['Volatility_M'] = data['Close_M'].rolling(window=30).std()
data['Volatility_V'] = data['Close_V'].rolling(window=30).std()

plt.figure(figsize=(14, 7))
plt.plot(data.index, data['Volatility_M'], label='MasterCard Volatility')
plt.plot(data.index, data['Volatility_V'], label='Visa Volatility')
plt.title('Stock Price Volatility of MasterCard and Visa')
plt.xlabel('Date')
plt.ylabel('Volatility')
plt.legend()
plt.show()

data['Return_M'] = data['Close_M'].pct_change()
data['Return_V'] = data['Close_V'].pct_change()

data['Cumulative_Return_M'] = (1 + data['Return_M']).cumprod()
data['Cumulative_Return_V'] = (1 + data['Return_V']).cumprod()

plt.figure(figsize=(14, 7))
plt.plot(data.index, data['Cumulative_Return_M'], label='MasterCard Cumulative Return')
plt.plot(data.index, data['Cumulative_Return_V'], label='Visa Cumulative Return')
plt.title('Cumulative Returns of MasterCard and Visa')
plt.xlabel('Date')
plt.ylabel('Cumulative Return')
plt.legend()
plt.show()

correlation = data[['Close_M', 'Close_V']].corr()
print(correlation)

from statsmodels.tsa.seasonal import seasonal_decompose

decomposition_M = seasonal_decompose(data['Close_M'], model='multiplicative', period=365)
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, figsize=(15, 12))

ax1.plot(decomposition_M.observed)
ax1.set_title('Observed - MasterCard')
ax2.plot(decomposition_M.trend)
ax2.set_title('Tren - MasterCard')
ax3.plot(decomposition_M.seasonal)
ax3.set_title('Seasonal - MasterCard')
ax4.plot(decomposition_M.resid)
ax4.set_title('Residual - MasterCard')

plt.tight_layout()
plt.show

decomposition_V = seasonal_decompose(data['Close_V'], model='multiplicative', period=365)
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, figsize=(15, 12))

ax1.plot(decomposition_V.observed)
ax1.set_title('Observed - Visa')
ax2.plot(decomposition_V.trend)
ax2.set_title('Trend - Visa')
ax3.plot(decomposition_V.seasonal)
ax3.set_title('Seasonal - Visa')
ax4.plot(decomposition_V.resid)
ax4.set_title('Residual - Visa')

plt.tight_layout()
plt.show()

from statsmodels.tsa.stattools import adfuller

def adf_test(series):
  result = adfuller(series.dropna())
  print('ADF Statistic:', result[0])
  print('p-value:', result[1])
  for key, value in result[4].items():
    print('Critial Values:')
    print(f' {key}, {value}')

print("ADF Test for MasterCard Close Price:")
adf_test(data['Close_M'])

print("\ADF Test for Visa Close Price:")
adf_test(data['Close_V'])

import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense, Input
from sklearn.metrics import mean_squared_error

scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data_M = scaler.fit_transform(data[['Close_M']])
scaled_data_V = scaler.fit_transform(data[['Close_V']])

train_len_M = int(len(scaled_data_M) * 0.8)
train_len_V = int(len(scaled_data_V) * 0.8)

train_data_M = scaled_data_M[:train_len_M]
test_data_M = scaled_data_M[train_len_M:]

train_data_V = scaled_data_V[:train_len_V]
test_data_V = scaled_data_V[train_len_V:]

def create_sequences(data, seq_length):
  x = []
  y = []
  for i in range(seq_length, len(data)):
    x.append(data[i-seq_length:i, 0])
    y.append(data[i, 0])
  return np.array(x), np.array(y)

seq_length = 60
x_train_M, y_train_M = create_sequences(train_data_M, seq_length)
x_test_M, y_test_M = create_sequences(test_data_M, seq_length)

x_train_V, y_train_V = create_sequences(train_data_V, seq_length)
x_test_V, y_test_V = create_sequences(test_data_V, seq_length)

x_train_M = np.reshape(x_train_M, (x_train_M.shape[0], x_train_M.shape[1], 1))
x_test_M = np.reshape(x_test_M, (x_test_M.shape[0], x_test_M.shape[1], 1))

x_train_V = np.reshape(x_train_V, (x_train_V.shape[0], x_train_V.shape[1], 1))
x_test_V = np.reshape(x_test_V, (x_test_V.shape[0], x_test_V.shape[1], 1))

model_M = Sequential()
model_M.add(Input(shape=(x_train_M.shape[1], 1)))
model_M.add(LSTM(units=50, return_sequences=True))
model_M.add(LSTM(units=50, return_sequences=False))
model_M.add(Dense(units=25))
model_M.add(Dense(units=1))

model_M.compile(optimizer='adam', loss='mean_squared_error')

model_V = Sequential()
model_V.add(Input(shape=(x_train_V.shape[1], 1)))
model_V.add(LSTM(units=50, return_sequences=True))
model_V.add(LSTM(units=50, return_sequences=False))
model_V.add(Dense(units=25))
model_V.add(Dense(units=1))

model_V.compile(optimizer ='adam', loss='mean_squared_error')

model_M.fit(x_train_M, y_train_M, batch_size=32, epochs=100)
model_V.fit(x_train_V, y_train_V, batch_size=32, epochs=100)

predictions_M = model_M.predict(x_test_M)
predictions_M = scaler.inverse_transform(predictions_M)

predictions_V = model_V.predict(x_test_V)
predictions_V = scaler.inverse_transform(predictions_V)

rmse_M = np.sqrt(mean_squared_error(y_test_M, predictions_M))
rmse_V = np.sqrt(mean_squared_error(y_test_V, predictions_V))

print(f'RMSE for MasterCard: {rmse_M}')
print(f'RMSE for Visa: {rmse_V}')

train_M = data[:train_len_M]['Close_M']
valid_M = data[train_len_M:train_len_M + len(predictions_M)]['Close_M']
valid_M = valid_M.to_frame()
valid_M['Predictions'] = predictions_M

train_V = data[:train_len_V]['Close_V']
valid_V = data[train_len_V:train_len_V + len(predictions_V)]['Close_V']
valid_V = valid_V.to_frame()
valid_V['Predictions'] = predictions_V

plt.figure(figsize=(14, 7))
plt.plot(train_M, label='Train - MasterCard')
plt.plot(valid_M['Close_M'], label='Valid - MasterCard')
plt.plot(valid_M['Predictions'], label='Predictions - MasterCard')
plt.legend()
plt.show()

plt.figure(figsize=(14, 7))
plt.plot(train_V, label ='Train -Visa')
plt.plot(valid_V['Close_V'], label='Valid -Visa')
plt.plot(valid_V['Predictions'], label='Predictions - Visa')
plt.legend()
plt.show()

from statsmodels.tsa.arima.model import ARIMA

data = data.asfreq('B')

train_size = int(len(data) * 0.8)
train, test = data['Close_M'][:train_size], data['Close_M'][train_size:]

model = ARIMA(train, order=(5, 1, 0))
model_fit = model.fit()
print(model_fit.summary())

predictions = model_fit.forecast(steps=len(test))
predictions = pd.Series(predictions, index=test.index)

plt.figure(figsize=(14, 7))
plt.plot(train, label='Training Data')
plt.plot(test, label='Test Data')
plt.plot(predictions, label='Predicted Data')
plt.title('ARIMA Model Predictions for MasterCard')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()

data = data.asfreq('B')

train_size = int(len(data) * 0.8)
train_V, test_V = data['Close_V'][:train_size], data['Close_V'][train_size:]

model_V = ARIMA(train_V, order=(5, 1, 0))
model_fit_V = model_V.fit()
print(model_fit_V.summary())

predictions_V = model_fit_V.forecast(steps=len(test_V))
predictions_V = pd.Series(predictions_V, index=test_V.index)

plt.figure(figsize=(14, 7))
plt.plot(train_V, label='Training Data')
plt.plot(test_V, label='Test Data')
plt.plot(predictions_V, label='Predicted Data'),
plt.title('ARIMA Model Predictions for Visa')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()

import warnings
warnings.filterwarnings('ignore')
import plotly.graph_objects as go

def predict_stock_price(data, column_name, forecast_periods):
    train_size = int(len(data) * 0.8)
    train, test = data[column_name][:train_size], data[column_name][train_size:]

    model = ARIMA(train, order=(5, 1, 0))
    model_fit = model.fit()

    future_dates = pd.date_range(start=data.index[-1], periods=forecast_periods, freq='B')
    forecast = model_fit.forecast(steps=forecast_periods)
    forecast_series = pd.Series(forecast, index=future_dates)

    return forecast_series

forecast_periods = 3 * 252
forecast_M = predict_stock_price(data, 'Close_M', forecast_periods)
forecast_V = predict_stock_price(data, 'Close_V', forecast_periods)

extended_data_M = pd.concat([data['Close_M'], forecast_M])
extended_data_V = pd.concat([data['Close_V'], forecast_V])

candlestick_data_M = pd.DataFrame({
    'Date': extended_data_M.index,
    'Open': extended_data_M.shift(1).fillna(method='bfill'),
    'High': extended_data_M.rolling(2).max(),
    'Low': extended_data_M.rolling(2).min(),
    'Close': extended_data_M
}).reset_index(drop=True)

candlestick_data_V = pd.DataFrame({
    'Date': extended_data_V.index,
    'Open': extended_data_V.shift(1).fillna(method='bfill'),
    'High': extended_data_V.rolling(2).max(),
    'Low': extended_data_V.rolling(2).min(),
    'Close': extended_data_V
}).reset_index(drop=True)

fig = go.Figure()

fig.add_trace(go.Candlestick(
    x=candlestick_data_M['Date'],
    open=candlestick_data_M['Open'],
    high=candlestick_data_M['High'],
    low=candlestick_data_M['Low'],
    close=candlestick_data_M['Close'],
    name='MasterCard',
     increasing_line_color='blue', decreasing_line_color='red'
))

fig.add_trace(go.Candlestick(
    x=candlestick_data_V['Date'],
    open=candlestick_data_V['Open'],
    high=candlestick_data_V['High'],
    low=candlestick_data_V['Low'],
    close=candlestick_data_V['Close'],
    name='Visa',
     increasing_line_color='green', decreasing_line_color='orange'
))

fig.update_layout(
    title='MasterCard and Visa Stock Prices (Historical and Predicted)',
    xaxis_title='Date',
    yaxis_title='Price',
    xaxis_rangeslider_visible=False
)

fig.show()