File size: 25,893 Bytes
e4e60c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a4444d
 
e4e60c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb75667
e4e60c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a734b5e
e4e60c1
0a3df69
 
 
 
 
 
 
e4e60c1
a734b5e
e4e60c1
 
 
 
 
 
 
 
 
 
 
 
2bd7f02
e4e60c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a4444d
e4e60c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb75667
e4e60c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a734b5e
e4e60c1
0a3df69
 
 
 
 
 
 
e4e60c1
a734b5e
e4e60c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a4444d
e4e60c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb75667
 
e4e60c1
 
 
 
 
 
 
 
 
 
b3e6023
e4e60c1
 
 
 
 
 
 
 
75eb0c5
e4e60c1
 
 
 
 
 
 
 
 
 
6201f7a
e4e60c1
 
 
 
 
 
 
 
 
 
13984a2
 
 
e4e60c1
 
 
 
 
6201f7a
 
e4e60c1
0356a8c
e4e60c1
 
 
75eb0c5
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
# %%
# Import section
# (Please don't edit this section unless if necessary)
import copy
from pathlib import Path
import warnings
import holidays
import seaborn as sns
import matplotlib
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import numpy as np
import pandas as pd
import glob
import csv
import lightning.pytorch as pl
from lightning.pytorch.callbacks import EarlyStopping, LearningRateMonitor
from lightning.pytorch.loggers import TensorBoardLogger
import torch
from pytorch_forecasting import Baseline, TemporalFusionTransformer, TimeSeriesDataSet
from pytorch_forecasting.data import GroupNormalizer, NaNLabelEncoder
from pytorch_forecasting.metrics import SMAPE, PoissonLoss, QuantileLoss
from pytorch_forecasting.models.temporal_fusion_transformer.tuning import optimize_hyperparameters
import random
import gc
import tensorflow as tf
import tensorboard as tb
tf.io.gfile = tb.compat.tensorflow_stub.io.gfile
import os
import math
import sys
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
from tensorflow.keras.layers import Conv1D, LSTM, Dense, Dropout, Bidirectional, TimeDistributed
from tensorflow.keras.layers import MaxPooling1D, Flatten
from tensorflow.keras.regularizers import L1, L2
from tensorflow.keras.metrics import Accuracy
from tensorflow.keras.metrics import RootMeanSquaredError
from sklearn.metrics import mean_squared_error as MSE
from sklearn.model_selection import KFold
from sklearn.inspection import permutation_importance
from tensorflow.keras.utils import plot_model
from sklearn.metrics import explained_variance_score, mean_poisson_deviance, mean_gamma_deviance, mean_squared_error, mean_squared_log_error, d2_absolute_error_score, d2_pinball_score, d2_tweedie_score
from sklearn.metrics import r2_score
from sklearn.metrics import max_error
import datetime
from datetime import date
import optuna 
from tensorflow.keras.callbacks import Callback
from optuna.integration import TFKerasPruningCallback
import shutil
import gradio as gr

# Some variables (don't edit these variables unless if necessary)
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
random.seed(30)
np.random.seed(30)
tf.random.set_seed(30)
torch.manual_seed(30)
torch.cuda.manual_seed(30)

# Global variables
PATIENCE = 30
MAX_EPOCHS = 3
LEARNING_RATE = 0.01
OPTUNA = True
ACCELERATOR = "cpu"
# This below line is only for GPU. Don't use it for CPU
#os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:1024"

# Variables to count the number of files
w = 7
prax = [0 for x in range(w)] 

# %%
# Function to train the model (TFT)
def modelTFT(csv_file, prax):
    train = csv_file
    #test = pd.read_csv("/kaggle/input/artemis-test/nifty_daily.csv")
    train['date'] = pd.to_datetime(train['Date/Time'])
    #test['date'] = pd.to_datetime(test['Date'])

    data = pd.concat([train], axis = 0, ignore_index=True)
    # Check that key is country-store-product-date combination
    #assert len(data.drop_duplicates(['country', 'store', 'product', 'date'])) == len(data)
    # Check that there is one date per country-store-product combination
    #assert len(data.drop_duplicates(['country', 'store', 'product'])) == len(data)//data['date'].nunique()

    #display(train.sample(4))

    # Add a time_idx (an sequence of consecutive integers that goes from min to max date)

    data = (data.merge((data[['Date/Time']].drop_duplicates(ignore_index=True)
    .rename_axis('time_idx')).reset_index(), on = ['Date/Time']))
    # add additional features
    data["day_of_week"] = data['date'].dt.dayofweek.astype(str).astype("category")  # categories have be strings
    data["week_of_year"] = data['date'].dt.isocalendar().week.astype(str).astype("category")  # categories have be strings
    data["month"] = data['date'].dt.month.astype(str).astype("category")  # categories have be strings
    #data["log_num_sold"] = np.log(data.num_sold + 1e-8)
    #data["avg_volume_by_country"] = data.groupby(["time_idx", "country"], observed=True).num_sold.transform("mean")
    #data["avg_volume_by_store"] = data.groupby(["time_idx", "store"], observed=True).num_sold.transform("mean")
    #data["avg_volume_by_product"] = data.groupby(["time_idx", "product"], observed=True).num_sold.transform("mean")

    #unique_dates_country = data[['date', 'Ticker']].drop_duplicates(ignore_index = True)
    #unique_dates_country['is_holiday'] = (unique_dates_country
    #                                      .apply(lambda x: x.date in holidays.country_holidays(x.country), axis = 1).astype('category'))
    #unique_dates_country['is_holiday_lead_1'] = (unique_dates_country
    #                                             .apply(lambda x: x.date+pd.Timedelta(days=1) in holidays.country_holidays(x.country), axis = 1).astype('category'))
    #unique_dates_country['is_holiday_lead_2'] = (unique_dates_country
    #                                             .apply(lambda x: x.date+pd.Timedelta(days=2) in holidays.country_holidays(x.country), axis = 1).astype('category'))
    #unique_dates_country['is_holiday_lag_1'] = (unique_dates_country
    #                                            .apply(lambda x: x.date-pd.Timedelta(days=1) in holidays.country_holidays(x.country), axis = 1).astype('category'))
    #unique_dates_country['is_holiday_lag_2'] = (unique_dates_country
    #                                            .apply(lambda x: x.date-pd.Timedelta(days=2) in holidays.country_holidays(x.country), axis = 1).astype('category'))
    #data = data.merge(unique_dates_country, on = ['date', 'Ticker'], validate = "m:1")
    #del unique_dates_country
    gc.collect()
    data.sample(5, random_state=30)

    train = data.iloc[:len(train)]
    test = data.iloc[len(train):]

    max_prediction_length = 2
    max_encoder_length = train.date.nunique()
    training_cutoff = train["time_idx"].max() - max_prediction_length #we will validate on 2020

    # Let's create a Dataset
    training = TimeSeriesDataSet(
        train[lambda x: x.time_idx <= training_cutoff],
        time_idx="time_idx",
        target="Close",
        group_ids=["Ticker"],
        min_encoder_length=max_prediction_length,  # keep encoder length long (as it is in the validation set)
        max_encoder_length=max_encoder_length,
        max_prediction_length=max_prediction_length,
        static_categoricals=["Ticker"],
        time_varying_known_categoricals=["month", "week_of_year", "day_of_week"],
        #variable_groups={"is_holiday": ["is_holiday"]},  # group of categorical variables can be treated as one variable
        time_varying_known_reals=["time_idx"],
        time_varying_unknown_categoricals=[],
        time_varying_unknown_reals=[
            'Open','High','Low','Close','OI','RSI14','RSI44','HHRSI','Rsi Weekly','LLCHHV','white','Vap44','Vap14','Ema5','Ema20','Ema50','Ema200'
        ],
        target_normalizer=GroupNormalizer(
            groups=['Ticker'], transformation="softplus"
        ),  # use softplus and normalize by group
        categorical_encoders={
            'week_of_year':NaNLabelEncoder(add_nan=True)
        },
        #lags={'num_sold': [7, 30, 365]},
        add_relative_time_idx=True,
        add_target_scales=True,
        add_encoder_length=True,
    )

    # create validation set (predict=True) which means to predict the last max_prediction_length points in time
    # for each series
    validation = TimeSeriesDataSet.from_dataset(training, train, predict=True, stop_randomization=True)

    # create dataloaders for model
    batch_size = 128  # set this between 32 to 128
    train_dataloader = training.to_dataloader(train=True, batch_size=batch_size, num_workers=0)
    val_dataloader = validation.to_dataloader(train=False, batch_size=batch_size * 10, num_workers=0)

    #let's see how a naive model does

    actuals = torch.cat([y for x, (y, weight) in iter(val_dataloader)])#.cuda()
    baseline_predictions = Baseline().predict(val_dataloader)#.cuda()
    (actuals - baseline_predictions).abs().mean().item()

    sm = SMAPE()

    print(f"Median loss for naive prediction on validation: {sm.loss(actuals, baseline_predictions).mean(axis = 1).median().item()}")

    early_stop_callback = EarlyStopping(monitor="train_loss", min_delta=1e-2, patience=PATIENCE, verbose=False, mode="min")
    lr_logger = LearningRateMonitor()  # log the learning rate
    logger = TensorBoardLogger("lightning_logs")  # logging results to a tensorboard

    trainer = pl.Trainer(
        max_epochs=1,
        accelerator=ACCELERATOR,
        enable_model_summary=False,
        gradient_clip_val=0.25,
        limit_train_batches=10,  # coment in for training, running valiation every 30 batches
        #fast_dev_run=True,  # comment in to check that networkor dataset has no serious bugs
        callbacks=[lr_logger, early_stop_callback],
        logger=logger,
    )

    tft = TemporalFusionTransformer.from_dataset(
        training,
        learning_rate=LEARNING_RATE,
        lstm_layers=2,
        hidden_size=16,
        attention_head_size=2,
        dropout=0.2,
        hidden_continuous_size=8,
        output_size=1,  # 7 quantiles by default
        loss=SMAPE(),
        log_interval=10,  # uncomment for learning rate finder and otherwise, e.g. to 10 for logging every 10 batches
        reduce_on_plateau_patience=4
    )

    tft.to(DEVICE)
    trainer.fit(
        tft,
        train_dataloaders=train_dataloader,
        val_dataloaders=val_dataloader,
    )
    #torch.cuda.empty_cache()
    #print(f"Number of parameters in network: {tft.size()/1e3:.1f}k")

    if OPTUNA:
        from pytorch_forecasting.models.temporal_fusion_transformer.tuning import optimize_hyperparameters

        # create study
        study = optimize_hyperparameters(
            train_dataloader,
            val_dataloader,
            model_path="optuna_test",
            n_trials=5,
            max_epochs=MAX_EPOCHS,
            gradient_clip_val_range=(0.01, 0.3),
            hidden_size_range=(8, 24),
            hidden_continuous_size_range=(8, 12),
            attention_head_size_range=(2, 4),
            learning_rate_range=(0.01, 0.05),
            dropout_range=(0.1, 0.25),
            trainer_kwargs=dict(limit_train_batches=20),
            reduce_on_plateau_patience=4,
            pruner=optuna.pruners.MedianPruner(n_min_trials=3, n_startup_trials=3),
            use_learning_rate_finder=False,  # use Optuna to find ideal learning rate or use in-built learning rate finder
        )
    #torch.cuda.empty_cache()
    #'''
    trainer = pl.Trainer(
        max_epochs=MAX_EPOCHS,
        accelerator=ACCELERATOR,
        enable_model_summary=False,
        gradient_clip_val=study.best_params['gradient_clip_val'],
        limit_train_batches=20,  # coment in for training, running valiation every 30 batches
        #fast_dev_run=True,  # comment in to check that networkor dataset has no serious bugs
        callbacks=[lr_logger, early_stop_callback],
        logger=logger, 
    )
    
    tft = TemporalFusionTransformer.from_dataset(
        training,
        learning_rate=study.best_params['learning_rate'],
        lstm_layers=2,
        hidden_size=study.best_params['hidden_size'],
        attention_head_size=study.best_params['attention_head_size'],
        dropout=study.best_params['dropout'],
        hidden_continuous_size=study.best_params['hidden_continuous_size'],
        output_size=1,  # 7 quantiles by default
        loss=SMAPE(),
        log_interval=10,  # uncomment for learning rate finder and otherwise, e.g. to 10 for logging every 10 batches
        reduce_on_plateau_patience=4
    )

    tft.to(DEVICE)
    trainer.fit(
        tft,
        train_dataloaders=train_dataloader,
        val_dataloaders=val_dataloader,
    )
    #'''    
    #torch.cuda.empty_cache()
    best_model_path = trainer.checkpoint_callback.best_model_path
    best_tft = TemporalFusionTransformer.load_from_checkpoint(best_model_path)
    actuals = torch.cat([y[0] for x, y in iter(val_dataloader)])#.cuda()
    predictions = best_tft.predict(val_dataloader, mode="prediction")
    raw_predictions = best_tft.predict(val_dataloader, mode="raw", return_x=True)

    sm = SMAPE()
    print(f"Validation median SMAPE loss: {sm.loss(actuals, predictions).mean(axis = 1).median().item()}")
    prax[5] = sm.loss(actuals, predictions).mean(axis = 1).median().item()
    #best_tft.plot_prediction(raw_predictions.x, raw_predictions.output, idx=0, add_loss_to_title=True);

    print(raw_predictions[0][0])
    prax[3] = '-'
    prax[4] = raw_predictions[0][0].data.cpu().tolist()[0][0]
    t = prax[4]
    tm = data['Close'][len(data)-1]
    if(t-tm>0):
        prax[6] = 1 
    elif(t-tm==0):
        prax[6] = 0
    else:
        prax[6] = -1
    #prax[i][3] = raw_predictions[0][0].data[1]
    print("-----------")

    #with open("out.csv", "w", newline="") as f:
    #  writer = csv.writer(f)
    #  writer.writerows(prax)

# %%
# Function to train the model (TFT)
def modelTFT_OpenGap(csv_file, prax):
    train = csv_file
    #test = pd.read_csv("/kaggle/input/artemis-test/nifty_daily.csv")
    train['date'] = pd.to_datetime(train['Date/Time'])
    #test['date'] = pd.to_datetime(test['Date'])
    datLength = len(train)
    train['O-C'] = 0
    for i in range(datLength):
        if i == 0:
            train['O-C'][i] = 0
            continue
        else:
            train['O-C'][i] = train['Open'][i] - train['Close'][i-1]
    data = pd.concat([train], axis = 0, ignore_index=True)
    # Check that key is country-store-product-date combination
    #assert len(data.drop_duplicates(['country', 'store', 'product', 'date'])) == len(data)
    # Check that there is one date per country-store-product combination
    #assert len(data.drop_duplicates(['country', 'store', 'product'])) == len(data)//data['date'].nunique()

    #display(train.sample(4))

    # Add a time_idx (an sequence of consecutive integers that goes from min to max date)

    data = (data.merge((data[['Date/Time']].drop_duplicates(ignore_index=True)
    .rename_axis('time_idx')).reset_index(), on = ['Date/Time']))
    # add additional features
    data["day_of_week"] = data['date'].dt.dayofweek.astype(str).astype("category")  # categories have be strings
    data["week_of_year"] = data['date'].dt.isocalendar().week.astype(str).astype("category")  # categories have be strings
    data["month"] = data['date'].dt.month.astype(str).astype("category")  # categories have be strings
    #data["log_num_sold"] = np.log(data.num_sold + 1e-8)
    #data["avg_volume_by_country"] = data.groupby(["time_idx", "country"], observed=True).num_sold.transform("mean")
    #data["avg_volume_by_store"] = data.groupby(["time_idx", "store"], observed=True).num_sold.transform("mean")
    #data["avg_volume_by_product"] = data.groupby(["time_idx", "product"], observed=True).num_sold.transform("mean")

    #unique_dates_country = data[['date', 'Ticker']].drop_duplicates(ignore_index = True)
    #unique_dates_country['is_holiday'] = (unique_dates_country
    #                                      .apply(lambda x: x.date in holidays.country_holidays(x.country), axis = 1).astype('category'))
    #unique_dates_country['is_holiday_lead_1'] = (unique_dates_country
    #                                             .apply(lambda x: x.date+pd.Timedelta(days=1) in holidays.country_holidays(x.country), axis = 1).astype('category'))
    #unique_dates_country['is_holiday_lead_2'] = (unique_dates_country
    #                                             .apply(lambda x: x.date+pd.Timedelta(days=2) in holidays.country_holidays(x.country), axis = 1).astype('category'))
    #unique_dates_country['is_holiday_lag_1'] = (unique_dates_country
    #                                            .apply(lambda x: x.date-pd.Timedelta(days=1) in holidays.country_holidays(x.country), axis = 1).astype('category'))
    #unique_dates_country['is_holiday_lag_2'] = (unique_dates_country
    #                                            .apply(lambda x: x.date-pd.Timedelta(days=2) in holidays.country_holidays(x.country), axis = 1).astype('category'))
    #data = data.merge(unique_dates_country, on = ['date', 'Ticker'], validate = "m:1")
    #del unique_dates_country
    gc.collect()
    data.sample(5, random_state=30)

    train = data.iloc[:len(train)]
    test = data.iloc[len(train):]

    max_prediction_length = 2
    max_encoder_length = train.date.nunique()
    training_cutoff = train["time_idx"].max() - max_prediction_length #we will validate on 2020

    # Let's create a Dataset
    training = TimeSeriesDataSet(
        train[lambda x: x.time_idx <= training_cutoff],
        time_idx="time_idx",
        target="Close",
        group_ids=["Ticker"],
        min_encoder_length=max_prediction_length,  # keep encoder length long (as it is in the validation set)
        max_encoder_length=max_encoder_length,
        max_prediction_length=max_prediction_length,
        static_categoricals=["Ticker"],
        time_varying_known_categoricals=["month", "week_of_year", "day_of_week"],
        #variable_groups={"is_holiday": ["is_holiday"]},  # group of categorical variables can be treated as one variable
        time_varying_known_reals=["time_idx"],
        time_varying_unknown_categoricals=[],
        time_varying_unknown_reals=[
            'Open','High','Low','Close','OI','RSI14','RSI44','HHRSI','Rsi Weekly','LLCHHV','white','Vap44','Vap14','Ema5','Ema20','Ema50','Ema200', 'O-C'
        ],
        target_normalizer=GroupNormalizer(
            groups=['Ticker'], transformation="softplus"
        ),  # use softplus and normalize by group
        categorical_encoders={
            'week_of_year':NaNLabelEncoder(add_nan=True)
        },
        #lags={'num_sold': [7, 30, 365]},
        add_relative_time_idx=True,
        add_target_scales=True,
        add_encoder_length=True,
    )

    # create validation set (predict=True) which means to predict the last max_prediction_length points in time
    # for each series
    validation = TimeSeriesDataSet.from_dataset(training, train, predict=True, stop_randomization=True)

    # create dataloaders for model
    batch_size = 128  # set this between 32 to 128
    train_dataloader = training.to_dataloader(train=True, batch_size=batch_size, num_workers=0)
    val_dataloader = validation.to_dataloader(train=False, batch_size=batch_size * 10, num_workers=0)

    #let's see how a naive model does

    actuals = torch.cat([y for x, (y, weight) in iter(val_dataloader)])#.cuda()
    baseline_predictions = Baseline().predict(val_dataloader)#.cuda()
    (actuals - baseline_predictions).abs().mean().item()

    sm = SMAPE()

    print(f"Median loss for naive prediction on validation: {sm.loss(actuals, baseline_predictions).mean(axis = 1).median().item()}")

    early_stop_callback = EarlyStopping(monitor="train_loss", min_delta=1e-2, patience=PATIENCE, verbose=False, mode="min")
    lr_logger = LearningRateMonitor()  # log the learning rate
    logger = TensorBoardLogger("lightning_logs")  # logging results to a tensorboard

    trainer = pl.Trainer(
        max_epochs=1,
        accelerator=ACCELERATOR,
        enable_model_summary=False,
        gradient_clip_val=0.25,
        limit_train_batches=10,  # coment in for training, running valiation every 30 batches
        #fast_dev_run=True,  # comment in to check that networkor dataset has no serious bugs
        callbacks=[lr_logger, early_stop_callback],
        logger=logger,
    )

    tft = TemporalFusionTransformer.from_dataset(
        training,
        learning_rate=LEARNING_RATE,
        lstm_layers=2,
        hidden_size=16,
        attention_head_size=2,
        dropout=0.2,
        hidden_continuous_size=8,
        output_size=1,  # 7 quantiles by default
        loss=SMAPE(),
        log_interval=10,  # uncomment for learning rate finder and otherwise, e.g. to 10 for logging every 10 batches
        reduce_on_plateau_patience=4
    )

    tft.to(DEVICE)
    trainer.fit(
        tft,
        train_dataloaders=train_dataloader,
        val_dataloaders=val_dataloader,
    )
    #torch.cuda.empty_cache()
    #print(f"Number of parameters in network: {tft.size()/1e3:.1f}k")

    if OPTUNA:
        from pytorch_forecasting.models.temporal_fusion_transformer.tuning import optimize_hyperparameters

        # create study
        study = optimize_hyperparameters(
            train_dataloader,
            val_dataloader,
            model_path="optuna_test",
            n_trials=5,
            max_epochs=MAX_EPOCHS,
            gradient_clip_val_range=(0.01, 0.3),
            hidden_size_range=(8, 24),
            hidden_continuous_size_range=(8, 12),
            attention_head_size_range=(2, 4),
            learning_rate_range=(0.01, 0.05),
            dropout_range=(0.1, 0.25),
            trainer_kwargs=dict(limit_train_batches=20),
            reduce_on_plateau_patience=4,
            pruner=optuna.pruners.MedianPruner(n_min_trials=3, n_warmup_steps=3),
            use_learning_rate_finder=False,  # use Optuna to find ideal learning rate or use in-built learning rate finder
        )
    #torch.cuda.empty_cache()
    #'''
    trainer = pl.Trainer(
        max_epochs=MAX_EPOCHS,
        accelerator=ACCELERATOR,
        enable_model_summary=False,
        gradient_clip_val=study.best_params['gradient_clip_val'],
        limit_train_batches=20,  # coment in for training, running valiation every 30 batches
        #fast_dev_run=True,  # comment in to check that networkor dataset has no serious bugs
        callbacks=[lr_logger, early_stop_callback],
        logger=logger,
    )
    
    tft = TemporalFusionTransformer.from_dataset(
        training,
        learning_rate=study.best_params['learning_rate'],
        lstm_layers=2,
        hidden_size=study.best_params['hidden_size'],
        attention_head_size=study.best_params['attention_head_size'],
        dropout=study.best_params['dropout'],
        hidden_continuous_size=study.best_params['hidden_continuous_size'],
        output_size=1,  # 7 quantiles by default
        loss=SMAPE(),
        log_interval=10,  # uncomment for learning rate finder and otherwise, e.g. to 10 for logging every 10 batches
        reduce_on_plateau_patience=4
    )

    tft.to(DEVICE)
    trainer.fit(
        tft,
        train_dataloaders=train_dataloader,
        val_dataloaders=val_dataloader,
    )
    #'''    
    #torch.cuda.empty_cache()
    best_model_path = trainer.checkpoint_callback.best_model_path
    best_tft = TemporalFusionTransformer.load_from_checkpoint(best_model_path)
    actuals = torch.cat([y[0] for x, y in iter(val_dataloader)])#.cuda()
    predictions = best_tft.predict(val_dataloader, mode="prediction")
    raw_predictions = best_tft.predict(val_dataloader, mode="raw", return_x=True)

    sm = SMAPE()
    print(f"Validation median SMAPE loss: {sm.loss(actuals, predictions).mean(axis = 1).median().item()}")
    prax[5] = sm.loss(actuals, predictions).mean(axis = 1).median().item()
    #best_tft.plot_prediction(raw_predictions.x, raw_predictions.output, idx=0, add_loss_to_title=True);

    print(raw_predictions[0][0])
    prax[3] = '-'
    prax[4] = raw_predictions[0][0].data.cpu().tolist()[0][0]
    t = prax[4]
    tm = data['Close'][len(data)-1]
    if(t-tm>0):
        prax[6] = 1 
    elif(t-tm==0):
        prax[6] = 0
    else:
        prax[6] = -1
    #prax[i][3] = raw_predictions[0][0].data[1]
    print("-----------")

    #with open("out.csv", "w", newline="") as f:
    #  writer = csv.writer(f)
    #  writer.writerows(prax)

# %%
def generate_csv(data_list):
    today = date.today().strftime("%Y_%m_%d")
    filename = f"result_{today}.csv"
    file_exists = os.path.isfile(filename)
    with open(filename, mode='a', newline='') as csv_file:
        fieldnames = ['Ticker', 'Prev_Close_Real', 'Model', 'Prev_Close_Model', 'Close_Model', 'Max_Err', 'Up_Down' ] # replace with your own column names
        writer = csv.writer(csv_file, delimiter=',')
        if not file_exists:
            writer.writerow(fieldnames)  # file doesn't exist yet, write a header
        writer.writerow(data_list)
    csv_file.close()

def guess_date(string):
    for fmt in ["%Y/%m/%d", "%d-%m-%Y", "%Y%m%d", "%m/%d/%Y", "%d/%m/%Y", "%Y-%m-%d", "%d/%m/%y", "%m/%d/%y"]:
        try:
            return datetime.datetime.strptime(string, fmt).date()
        except ValueError:
            continue
    raise ValueError(string)

# %%
# Main function
def main(files):
    # Get a list of all the CSV files uploaded
    prax = [0,0,0,0,0,0,0]
    for idx, file in enumerate(files):
        print(f"File #{idx+1}: {file}")
        print(file.name)
        df = pd.read_csv(file.name)
        print(df['Ticker'][0])
        prax[0] = df['Ticker'][0]
        prax[1] = df['Close'][len(df)-1]
        print('------------------')
        #df = df.drop(['EMARSI'], axis=1)
        #df['Date/Time'] = pd.to_datetime(df['Date/Time'])
        for i in range(len(df)):
            x = guess_date(df['Date/Time'][i])
            df['Date/Time'][i] = x.strftime("%Y-%m-%d")
        df['Date/Time'] = pd.to_datetime(df['Date/Time'])
        df.fillna(0, inplace=True)
        #df.to_csv('out.csv')
        modelTFT(df, prax)
        prax[2] = "TFT"
        generate_csv(prax)
        modelTFT_OpenGap(df, prax)
        prax[2] = "TFT_OpenGap"
        generate_csv(prax)
        # Generate blank line
        prax=["","","","","","",""]
        generate_csv(prax)
        # Reset prax
        prax = [0,0,0,0,0,0,0]
    today = date.today().strftime("%Y_%m_%d")
    return f"result_{today}.csv"

gradioApp = gr.Interface(fn=main, inputs=gr.File(file_count="multiple"), outputs="file")

if __name__ == "__main__":
    # Calling main function
    gradioApp.launch()