-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtensor_stock_git.py
More file actions
931 lines (565 loc) · 22 KB
/
tensor_stock_git.py
File metadata and controls
931 lines (565 loc) · 22 KB
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 20 09:43:38 2024
@author: MANJEET SINGH
Stock-MArket-Forecasting--Lstm git repo
"""
import yfinance as yf
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error, r2_score
import seaborn as sns
import matplotlib.pyplot as plt
### Create the Stacked LSTM model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import LSTM
import tensorflow as tf
import tensorflow
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
import numpy
from datetime import datetime,timedelta
from tensorflow.keras.layers import Bidirectional
from tensorflow.keras import regularizers
from tensorflow.keras.optimizers import Adam
# Define the ticker symbol for the stock you're interested in
ticker_symbol = 'WMT'
ticker = yf.Ticker(ticker_symbol)
data=ticker.info
df = ticker.history(period='2y', interval='1h')
df.reset_index(inplace=True)
df1=df['Open']
plt.plot(df1)
scaler_open=MinMaxScaler(feature_range=(0,1))
df1=scaler_open.fit_transform(np.array(df1).reshape(-1,1))
##splitting dataset into train and test split
training_size=int(len(df1)*1)
training_size1=int(len(df1)*0.65)
test_size=len(df1)-training_size1
train_data,test_data=df1[0:training_size,:],df1[training_size1:len(df1),:1]
# convert an array of values into a dataset matrix
def create_dataset(dataset,time_step=1):
dataX, dataY = [], []
for i in range(len(dataset)-time_step-1):
a = dataset[i:(i+time_step), 0]
dataX.append(a)
dataY.append(dataset[i + time_step, 0])
dataX=numpy.array(dataX)
dataY=numpy.array(dataY)
return dataX, dataY
time_step = 100
X_train, y_train = create_dataset(train_data, time_step)
X_test, ytest = create_dataset(test_data, time_step)
print(X_train)
print(y_train.shape)
print(X_test.shape), print(ytest.shape)
X_train =X_train.reshape(X_train.shape[0],X_train.shape[1] , 1)
X_test = X_test.reshape(X_test.shape[0],X_test.shape[1] , 1)
huber_loss = tf.keras.losses.Huber()
model_open=Sequential()
model_open.add(Bidirectional(LSTM(50, return_sequences=True,input_shape=(120,1))))
model_open.add(Bidirectional(LSTM(50, return_sequences=True, kernel_regularizer=regularizers.l2(0.01))))
model_open.add(Bidirectional(LSTM(50)))
model_open.add(Dense(5, activation="relu"))
# model.add(Dense(3, activation="relu"))
model_open.add(Dense(1, ))
model_open.compile(loss=huber_loss,optimizer=Adam(learning_rate=0.001))
model_open.summary()
model_open.fit(X_train,y_train,validation_data=(X_train,y_train),epochs=100,batch_size=50,verbose=1)
#############################################################
train_predict=model_open.predict(X_train)
test_predict=model_open.predict(X_test)
##Transformback to original form
train_predict=scaler_open.inverse_transform(train_predict)
test_predict=scaler_open.inverse_transform(test_predict)
### Calculate RMSE performance metrics
import math
from sklearn.metrics import mean_squared_error
math.sqrt(mean_squared_error(y_train,train_predict))
### Test Data RMSE
math.sqrt(mean_squared_error(ytest,test_predict))
### Plotting
# shift train predictions for plotting
# look_back=140
# trainPredictPlot = numpy.empty_like(df1)
# trainPredictPlot[:, :] = np.nan
# trainPredictPlot[look_back:len(train_predict)+look_back, :] = train_predict
# # shift test predictions for plotting
# testPredictPlot = numpy.empty_like(df1)
# testPredictPlot[:, :] = numpy.nan
# testPredictPlot[len(train_predict)+(look_back*2)+1:len(df1)-1, :] = test_predict
# # plot baseline and predictions 3490-2364
# plt.plot(scaler_open.inverse_transform(df1))
# plt.plot(trainPredictPlot)
# plt.plot(testPredictPlot)
# plt.show()
len(test_data)
x_input=test_data[1100:-25].reshape(1,-1)
x_input.shape
temp_input=list(x_input)
temp_input=temp_input[0].tolist()
temp_input
from numpy import array
lst_output=[]
n_steps=100
i=0
while(i<7*5):
if(len(temp_input)>100):
#print(temp_input)
x_input=np.array(temp_input[1:])
print("{} day input {}".format(i,x_input))
x_input=x_input.reshape(1,-1)
x_input = x_input.reshape((1, n_steps, 1))
#print(x_input)
yhat = model_open.predict(x_input, verbose=0)
print("{} day output {}".format(i,yhat))
temp_input.extend(yhat[0].tolist())
temp_input=temp_input[1:]
#print(temp_input)
lst_output.extend(yhat.tolist())
i=i+1
else:
x_input = x_input.reshape((1, n_steps,1))
yhat = model_open.predict(x_input, verbose=0)
print(yhat[0])
temp_input.extend(yhat[0].tolist())
print(len(temp_input))
lst_output.extend(yhat.tolist())
i=i+1
print('open model',lst_output)
res1=scaler_open.inverse_transform(test_data[-25:])
res=scaler_open.inverse_transform(lst_output)
plt.plot(res1)
plt.plot(res)
1224-35
day_new=np.arange(1,101)
day_pred=np.arange(101,101+len(lst_output))
import matplotlib.pyplot as plt
len(df1)
# plt.plot(day_new,scaler_open.inverse_transform(df1[3391:]))
# plt.plot(day_pred,scaler_open.inverse_transform(lst_output))
# df3=df1.tolist()
# df3.extend(lst_output)
# plt.plot(df3[3491:])
# df3=scaler_open.inverse_transform(df3).tolist()
# plt.plot(df3)
# plt.plot(scaler_open.inverse_transform(df1).tolist())
# plt.show()
"""
Model to predict High
"""
df1=df[['High','Open','Datetime']]
df1.set_index('Datetime', inplace=True)
plt.plot(df1)
scaler_high=MinMaxScaler(feature_range=(0,1))
df1.iloc[:,0]=scaler_high.fit_transform(np.array(df1.iloc[:,0]).reshape(-1,1))
df1.iloc[:,1]=scaler_high.transform(np.array(df1.iloc[:,1]).reshape(-1,1))
##splitting dataset into train and test split
training_size=int(len(df1)*1)
training_size1=int(len(df1)*0.65)
test_size=len(df1)-training_size1
train_data,test_data=df1.iloc[0:training_size,:],df1.iloc[training_size1:len(df1),:]
# convert an array of values into a dataset matrix
def create_dataset_high(dataset,time_step=1):
dataX, dataY = [], []
for i in range(len(dataset)-time_step-1):
a = dataset.iloc[i:(i+time_step), :]
dataX.append(a)
dataY.append(dataset.iloc[i + time_step, 0])
dataX=numpy.array(dataX)
dataY=numpy.array(dataY)
return dataX, dataY
time_step = 120
X_train, y_train = create_dataset_high(train_data, time_step)
X_test, ytest = create_dataset_high(test_data, time_step)
print(X_train)
print(y_train.shape)
print(X_test.shape), print(ytest.shape)
X_train =X_train.reshape(X_train.shape[0],X_train.shape[1] , 2)
X_test = X_test.reshape(X_test.shape[0],X_test.shape[1] , 2)
model_high=Sequential()
model_high.add(Bidirectional(LSTM(50, return_sequences=True,input_shape=(120,2))))
model_high.add(Bidirectional(LSTM(50,return_sequences=True,kernel_regularizer=regularizers.l2(0.01))))
model_high.add(Bidirectional(LSTM(50)))
model_high.add(Dense(5, activation="relu"))
# model.add(Dense(3, activation="relu"))
model_high.add(Dense(1))
model_high.compile(loss=huber_loss,optimizer=Adam(learning_rate=0.001))
model_high.summary()
model_high.fit(X_train,y_train,validation_data=(X_train,y_train),epochs=150,batch_size=70,verbose=1)
#############################################################
train_predict=model_high.predict(X_train)
test_predict=model_high.predict(X_test)
##Transformback to original form
train_predict=scaler_high.inverse_transform(train_predict)
test_predict=scaler_high.inverse_transform(test_predict)
### Calculate RMSE performance metrics
import math
from sklearn.metrics import mean_squared_error
math.sqrt(mean_squared_error(y_train,train_predict))
### Test Data RMSE
math.sqrt(mean_squared_error(ytest,test_predict))
### Plotting
# shift train predictions for plotting
# look_back=140
# trainPredictPlot = numpy.empty_like(df1)
# trainPredictPlot[:, :] = np.nan
# trainPredictPlot[look_back:len(train_predict)+look_back, :] = train_predict
# # shift test predictions for plotting
# testPredictPlot = numpy.empty_like(df1)
# testPredictPlot[:, :] = numpy.nan
# testPredictPlot[len(train_predict)+(look_back*2)+1:len(df1)-1, :] = test_predict
# # plot baseline and predictions
# plt.plot(scaler_high.inverse_transform(df1))
# plt.plot(trainPredictPlot)
# plt.plot(testPredictPlot)
# plt.show()
len(test_data)
x_input=test_data[1100:-25]
x_input.shape
x_input=np.array(x_input.reshape(1,-1)).reshape(1,-1)
temp_input=np.array(x_input)
# temp_input=temp_input[0].tolist()
temp_input
from numpy import array
lst_output_high=[]
n_steps=120
i=0
while(i<7*5):
if(len(temp_input)>n_steps):
#print(temp_input)
x_input=np.array(temp_input[1:])
print("{} day input {}".format(i,x_input))
x_input=x_input
x_input = x_input.reshape((1, n_steps, 2))
#print(x_input)
yhat = model_high.predict(x_input, verbose=0)
print("{} day output {}".format(i,yhat))
new = np.array([yhat[0], lst_output[i]]).reshape(1, 2)
# Concatenating along axis 0 (rows)
temp_input = np.concatenate((temp_input, new), axis=0)
temp_input=temp_input[1:]
#print(temp_input)
lst_output_high.extend(yhat.tolist())
i=i+1
else:
x_input = x_input.reshape((1, n_steps,2))
yhat = model_high.predict(x_input, verbose=0)
print(yhat[0])
new = np.array([yhat[0], lst_output[i]]).reshape(1, 2)
# Concatenating along axis 0 (rows)
temp_input = np.concatenate((temp_input, new), axis=0)
# temp_input.append(new)
print(len(temp_input))
lst_output_high.extend(yhat.tolist())
i=i+1
print(lst_output_high)
day_new=np.arange(1,101)
day_pred=np.arange(101,101+len(lst_output_high))
import matplotlib.pyplot as plt
len(df1)
# plt.plot(day_new,scaler_high.inverse_transform(df1[3391:]))
# plt.plot(day_pred,scaler_high.inverse_transform(lst_output_high))
# df3=df1.tolist()
# df3.extend(lst_output_high)
# plt.plot(df3[3491:])
# df3=scaler_high.inverse_transform(df3).tolist()
# plt.plot(df3)
# plt.plot(scaler_high.inverse_transform(df1).tolist())
# plt.show()
"""
Model to predict Low
"""
df1=df[['Low','Open','Datetime']]
df1.set_index('Datetime', inplace=True)
plt.plot(df1)
scaler_low=MinMaxScaler(feature_range=(0,1))
df1.iloc[:,0]=scaler_low.fit_transform(np.array(df1.iloc[:,0]).reshape(-1,1))
df1.iloc[:,1]=scaler_low.transform(np.array(df1.iloc[:,1]).reshape(-1,1))
##splitting dataset into train and test split
training_size=int(len(df1)*1)
training_size1=int(len(df1)*0.65)
test_size=len(df1)-training_size1
train_data,test_data=df1.iloc[0:training_size,:],df1.iloc[training_size1:len(df1),:]
# convert an array of values into a dataset matrix
def create_dataset_high(dataset,time_step=1):
dataX, dataY = [], []
for i in range(len(dataset)-time_step-1):
a = dataset.iloc[i:(i+time_step), :]
dataX.append(a)
dataY.append(dataset.iloc[i + time_step, 0])
dataX=numpy.array(dataX)
dataY=numpy.array(dataY)
return dataX, dataY
time_step = 7*15
X_train, y_train = create_dataset_high(train_data, time_step)
X_test, ytest = create_dataset_high(test_data, time_step)
print(X_train)
print(y_train.shape)
print(X_test.shape), print(ytest.shape)
X_train =X_train.reshape(X_train.shape[0],X_train.shape[1] , 2)
X_test = X_test.reshape(X_test.shape[0],X_test.shape[1] , 2)
model_low=Sequential()
model_low.add(Bidirectional(LSTM(50,return_sequences=True,input_shape=(120,2))))_
model_low.add(Bidirectional(LSTM(50,return_sequences=True,kernel_regularizer=regularizers.l2(0.01))))
model_low.add(Bidirectional(LSTM(50)))
model.add(Dense(5, activation="relu"))
# model.add(Dense(3, activation="relu"))
model_low.add(Dense(1))
model_low.compile(loss=huber_loss,optimizer=Adam(learning_rate=0.001))
model_low.summary()
model_low.fit(X_train,y_train,validation_data=(X_train,y_train),epochs=150,batch_size=70,verbose=1)
#############################################################
train_predict=model_low.predict(X_train)
test_predict=model_low.predict(X_test)
##Transformback to original form
train_predict=scaler_low.inverse_transform(train_predict)
test_predict=scaler_low.inverse_transform(test_predict)
### Calculate RMSE performance metrics
import math
from sklearn.metrics import mean_squared_error
math.sqrt(mean_squared_error(y_train,train_predict))
### Test Data RMSE
math.sqrt(mean_squared_error(ytest,test_predict))
### Plotting
# shift train predictions for plotting
# look_back=140
# trainPredictPlot = numpy.empty_like(df1)
# trainPredictPlot[:, :] = np.nan
# trainPredictPlot[look_back:len(train_predict)+look_back, :] = train_predict
# # shift test predictions for plotting
# testPredictPlot = numpy.empty_like(df1)
# testPredictPlot[:, :] = numpy.nan
# testPredictPlot[len(train_predict)+(look_back*2)+1:len(df1)-1, :] = test_predict
# # plot baseline and predictions
# plt.plot(scaler_low.inverse_transform(df1))
# plt.plot(trainPredictPlot)
# plt.plot(testPredictPlot)
# plt.show()
len(test_data)
x_input=test_data[1085:]
x_input.shape
x_input=np.array(x_input)
temp_input=np.array(x_input)
# temp_input=temp_input[0].tolist()
temp_input
from numpy import array
lst_output_low=[]
n_steps=140
i=0
while(i<7*5):
if(len(temp_input)>140):
#print(temp_input)
x_input=np.array(temp_input[1:])
print("{} day input {}".format(i,x_input))
x_input=x_input
x_input = x_input.reshape((1, n_steps, 2))
#print(x_input)
yhat = model_low.predict(x_input, verbose=0)
print("{} day output {}".format(i,yhat))
new = np.array([yhat[0], lst_output[i]]).reshape(1, 2)
# Concatenating along axis 0 (rows)
temp_input = np.concatenate((temp_input, new), axis=0)
temp_input=temp_input[1:]
#print(temp_input)
lst_output_low.extend(yhat.tolist())
i=i+1
else:
x_input = x_input.reshape((1, n_steps,2))
yhat = model_low.predict(x_input, verbose=0)
print(yhat[0])
new = np.array([yhat[0], lst_output[i]]).reshape(1, 2)
# Concatenating along axis 0 (rows)
temp_input = np.concatenate((temp_input, new), axis=0)
# temp_input.append(new)
print(len(temp_input))
lst_output_low.extend(yhat.tolist())
i=i+1
print(lst_output_low)
day_new=np.arange(1,101)
day_pred=np.arange(101,101+len(lst_output_high))
import matplotlib.pyplot as plt
len(df1)
# plt.plot(day_new,scaler_low.inverse_transform(df1[3391:]))
# plt.plot(day_pred,scaler_low.inverse_transform(lst_output_low))
# df3=df1.tolist()
# df3.extend(lst_output_high)
# plt.plot(df3[3491:])
# df3=scaler_low.inverse_transform(df3).tolist()
# plt.plot(df3)
# plt.plot(scaler_low.inverse_transform(df1).tolist())
# plt.show()
"""
Model to predict close
"""
df1=df[['Open','High','Low','Close','Datetime']]
df1.set_index('Datetime', inplace=True)
plt.plot(df1)
scaler_close=MinMaxScaler(feature_range=(0,1))
df1.iloc[:,0]=scaler_close.fit_transform(np.array(df1.iloc[:,0]).reshape(-1,1))
df1.iloc[:,1]=scaler_close.transform(np.array(df1.iloc[:,1]).reshape(-1,1))
df1.iloc[:,2]=scaler_close.transform(np.array(df1.iloc[:,2]).reshape(-1,1))
df1.iloc[:,3]=scaler_close.transform(np.array(df1.iloc[:,3]).reshape(-1,1))
##splitting dataset into train and test split
training_size=int(len(df1)*1)
training_size1=int(len(df1)*0.65)
test_size=len(df1)-training_size1
train_data,test_data=df1.iloc[0:training_size,:],df1.iloc[training_size1:len(df1),:]
# convert an array of values into a dataset matrix
def create_dataset_high(dataset,time_step=1):
dataX, dataY = [], []
for i in range(len(dataset)-time_step-1):
a = dataset.iloc[i:(i+time_step), :]
dataX.append(a)
dataY.append(dataset.iloc[i + time_step, 3])
dataX=numpy.array(dataX)
dataY=numpy.array(dataY)
return dataX, dataY
time_step = 140
X_train, y_train = create_dataset_high(train_data, time_step)
X_test, ytest = create_dataset_high(test_data, time_step)
print(X_train)
print(y_train.shape)
print(X_test.shape), print(ytest.shape)
X_train =X_train.reshape(X_train.shape[0],X_train.shape[1] , 4)
X_test = X_test.reshape(X_test.shape[0],X_test.shape[1] , 4)
model_close=Sequential()
model_close.add(Bidirectional(LSTM(50,return_sequences=True,input_shape=(120,4))))
model_close.add(Bidirectional(LSTM(50,return_sequences=True,kernel_regularizer=regularizers.l2(0.01))))
model_close.add(Bidirectional(LSTM(50)))
model.add(Dense(5, activation="relu"))
# model.add(Dense(3, activation="relu"))
model_close.add(Dense(1))
model_close.compile(loss=huber_loss,optimizer=Adam(learning_rate=0.001))
model_close.summary()
model_close.fit(X_train,y_train,validation_data=(X_train,y_train),epochs=150,batch_size=70,verbose=1)
#############################################################
train_predict=model_close.predict(X_train)
test_predict=model_close.predict(X_test)
##Transformback to original form
train_predict=scaler_close.inverse_transform(train_predict)
test_predict=scaler_close.inverse_transform(test_predict)
### Calculate RMSE performance metrics
import math
from sklearn.metrics import mean_squared_error
math.sqrt(mean_squared_error(y_train,train_predict))
### Test Data RMSE
math.sqrt(mean_squared_error(ytest,test_predict))
### Plotting
# shift train predictions for plotting
# look_back=140
# trainPredictPlot = numpy.empty_like(df1)
# trainPredictPlot[:, :] = np.nan
# trainPredictPlot[look_back:len(train_predict)+look_back, :] = train_predict
# # shift test predictions for plotting
# testPredictPlot = numpy.empty_like(df1)
# testPredictPlot[:, :] = numpy.nan
# testPredictPlot[len(train_predict)+(look_back*2)+1:len(df1)-1, :] = test_predict
# # plot baseline and predictions
# plt.plot(scaler_close.inverse_transform(df1))
# plt.plot(trainPredictPlot)
# plt.plot(testPredictPlot)
# plt.show()
len(test_data)
x_input=test_data[1085:]
x_input.shape
x_input=np.array(x_input)
temp_input=np.array(x_input)
# temp_input=temp_input[0].tolist()
temp_input
from numpy import array
lst_output_close=[]
n_steps=140
i=0
while(i<7*5):
if(len(temp_input)>140):
#print(temp_input)
x_input=np.array(temp_input[1:])
print("{} day input {}".format(i,x_input))
x_input=x_input
x_input = x_input.reshape((1, n_steps, 4))
#print(x_input)
yhat = model_close.predict(x_input, verbose=0)
print("{} day output {}".format(i,yhat))
new = np.array([ lst_output[i],lst_output_high[i],lst_output_low[i],yhat[0]]).reshape(1,4)
# Concatenating along axis 0 (rows)
temp_input = np.concatenate((temp_input, new), axis=0)
temp_input=temp_input[1:]
#print(temp_input)
lst_output_close.extend(yhat.tolist())
i=i+1
else:
x_input = x_input.reshape((1, n_steps,4))
yhat = model_close.predict(x_input, verbose=0)
print(yhat[0])
new = np.array( [lst_output[i],lst_output_high[i],lst_output_low[i],yhat[0]]).reshape(1,4)
# Concatenating along axis 0 (rows)
temp_input = np.concatenate((temp_input, new), axis=0)
# temp_input.append(new)
print(len(temp_input))
lst_output_close.extend(yhat.tolist())
i=i+1
print(lst_output_close)
day_new=np.arange(1,101)
day_pred=np.arange(101,101+len(lst_output_high))
import matplotlib.pyplot as plt
len(df1)
# plt.plot(day_new,scaler_close.inverse_transform(df1[3391:]))
# plt.plot(day_pred,scaler_close.inverse_transform(lst_output_low))
# df3=df1.tolist()
# df3.extend(lst_output_high)
# plt.plot(df3[3491:])
# df3=scaler_close.inverse_transform(df3).tolist()
# plt.plot(df3)
# plt.plot(scaler_close.inverse_transform(df1).tolist())
# plt.show()
############################
dfcandle=pd.DataFrame(index=range(len(lst_output)))
lst_output=scaler_open.inverse_transform(lst_output)
lst_output_high=scaler_high.inverse_transform(lst_output_high)
lst_output_low=scaler_low.inverse_transform(lst_output_low)
lst_output_close= scaler_close.inverse_transform(lst_output_close)
# lst_output= [x[0] for x in lst_output]
# lst_output_high= [x[0] for x in lst_output_high]
# lst_output_low= [x[0] for x in lst_output_low]
# lst_output_close= [x[0] for x in lst_output_close]
dfcandle['Open']=lst_output
dfcandle['High']=lst_output_high
dfcandle['Low']=lst_output_low
dfcandle['Close']=lst_output_close
# Define start and end dates
start_date = datetime.now().date()-timedelta(days=10)
end_date = start_date+timedelta(days=50)
# Generate a date range
date_range = pd.date_range(start=start_date, end=end_date, freq='B') # 'B' is for business days
date_range=date_range[:5]
# Create a list of timestamps for each weekday
timestamps = []
for date in date_range:
for hour in range(9, 16): # From 09:00 to 15:00 (inclusive)
if hour==9:
print(str(date.strftime(f'%Y-%m-%d 0{hour}:30:00-04:00')))
timestamps.append(str(date.strftime(f'%Y-%m-%d 0{hour}:30:00-04:00')))
else:
timestamps.append(str(date.strftime(f'%Y-%m-%d {hour}:30:00-04:00')))
dfcandle['Datetime']=timestamps
dfcandle['Datetime']=pd.to_datetime(dfcandle['Datetime'])
import mplfinance as mpf
# Ensure your dataframe is formatted correctly for mplfinance
dfcandle.set_index('Datetime', inplace=True)
# df.set_index('Datetime', inplace=True)
# Create a new DataFrame that contains the required OHLC (Open, High, Low, Close) data
df_candlestick = dfcandle[['Open', 'High', 'Low', 'Close',]]
# Add volume data if you have it
# df_candlestick['Volume'] = df['Volume']
figsize = (12, 8) # Width x Height in inches
dpi = 100
# Plot the candlestick chart
mpf.plot(df_candlestick, type='candle', style='charles', title='Candlestick Chart',ylabel='Price', volume=False,figsize=figsize) # volume=True if you have volume data