Kaggle competition: Two Sigma: Using News to Predict Stock Movements
<SOS> metric: custom Kaggle data source: two-sigma-financial-news<train_model>
import numpy as np
import lightgbm as lgb
import pandas as pd
from kaggle.competitions import twosigmanews
import matplotlib.pyplot as plt
import random
from datetime import datetime, date
from xgboost import XGBClassifier
from sklearn import model_selection
from sklearn.metrics import mean_squared_error
import time
if VALIDATE:
model2.fit(
 get_training_dataset(do_aug=DO_AUG), steps_per_epoch=STEPS_PER_EPOCH, epochs=30,
validation_data=get_validation_dataset() , callbacks=[es_acc, lr_schedule], verbose=1 
)
 else:
model2.fit(
 get_train_val_dataset(do_aug=DO_AUG), steps_per_epoch=STEPS_PER_EPOCH, epochs=30,
callbacks=[es_val_acc, lr_schedule], verbose=1
)<feature_engineering>
env = twosigmanews.make_env()
print('Done!' )
POST_TRAINING_TIME_START = datetime.now()<compute_test_metric>
( market_train_df, news_train_df)= env.get_training_data()
if VALIDATE:
cmat, score, precision, recall, acc = evaluate(model )<compute_test_metric>
market_train_df['time'] = market_train_df['time'].dt.date
market_train_df = market_train_df.loc[market_train_df['time']>=date(2010, 1, 1)]
if VALIDATE:
display_confusion_matrix(cmat, score, precision, recall, acc )<compute_test_metric>
def create_lag(df_code,n_lag=[3,7,14,],shift_size=1):
code = df_code['assetCode'].unique()
for col in return_features:
for window in n_lag:
rolled = df_code[col].shift(shift_size ).rolling(window=window)
 lag_mean = rolled.mean()
lag_max = rolled.max()
lag_min = rolled.min()
lag_std = rolled.std()
df_code['%s_lag_%s_mean'%(col,window)] = lag_mean
df_code['%s_lag_%s_max'%(col,window)] = lag_max
df_code['%s_lag_%s_min'%(col,window)] = lag_min
return df_code.fillna(-1)
 def generate_lag_features(df,n_lag = [3,7,14]):
features = ['time', 'assetCode', 'assetName', 'volume', 'close', 'open',
'returnsClosePrevRaw1', 'returnsOpenPrevRaw1',
'returnsClosePrevMktres1', 'returnsOpenPrevMktres1',
'returnsClosePrevRaw10', 'returnsOpenPrevRaw10',
'returnsClosePrevMktres10', 'returnsOpenPrevMktres10',
'returnsOpenNextMktres10', 'universe']
assetCodes = df['assetCode'].unique()
print(assetCodes)
 all_df = []
df_codes = df.groupby('assetCode')
 df_codes = [df_code[1][['time','assetCode']+return_features] for df_code in df_codes]
print('total %s df'%len(df_codes))
pool = Pool(4)
 all_df = pool.map(create_lag, df_codes)
 new_df = pd.concat(all_df)
 new_df.drop(return_features,axis=1,inplace=True)
 pool.close()
return new_df
if VALIDATE:
cmat, score, precision, recall, acc = evaluate(model2 )<compute_test_metric>
if VALIDATE:
display_confusion_matrix(cmat, score, precision, recall, acc )<compute_test_metric>
return_features = ['returnsClosePrevMktres10','returnsClosePrevRaw10','open','close']
n_lag = [3,7,14]
new_df = generate_lag_features(market_train_df,n_lag=n_lag )
if VALIDATE:
cmat, score, precision, recall, acc = evaluate([model, model2] )<compute_test_metric>
market_train_df = pd.merge(market_train_df,new_df,how='left',on=['time','assetCode'] )
if VALIDATE:
display_confusion_matrix(cmat, score, precision, recall, acc )<predict_on_test>
def mis_impute(data):
for i in data.columns:
if data[i].dtype == "object":
data[i] = data[i].fillna("other")
 elif(data[i].dtype == "int64" or data[i].dtype == "float64"):
data[i] = data[i].fillna(data[i].mean())
 else:
pass
return data
market_train_df = mis_impute(market_train_df )
def show_predict_val(m):
row, col = 3, 5
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(row * col)
 images, labels = next(iter(dataset))
probabilities = m.predict(images)
 predictions = np.argmax(probabilities, axis=-1)
 plt.figure(figsize=(15,int(15*row/col)))
 for i in range(row*col):
plt.subplot(row,col,i+1)
 pred = CLASSES[predictions[i]]
real = CLASSES[labels[i]]
if pred == real:
plt.title(f'{pred} [OK]')
 else:
plt.title(f'{pred} [NO -> {real}]', color='red')
 plt.axis('off')
 plt.imshow(images[i,])
 plt.show()<predict_on_test>
def data_prep(market_train):
lbl = {k: v for v, k in enumerate(market_train['assetCode'].unique())}
market_train['assetCodeT'] = market_train['assetCode'].map(lbl)
 market_train = market_train.dropna(axis=0)
 return market_train
market_train_df = data_prep(market_train_df)
 print(market_train_df.shape )
if VALIDATE:
show_predict_val(model )<predict_on_test>
up = market_train_df['returnsOpenNextMktres10'] >= 0
universe = market_train_df['universe'].values
if VALIDATE:
show_predict_val(model2 )<predict_on_test>
d = market_train_df['time']
fcol = [c for c in market_train_df if c not in ['assetCode', 'assetCodes', 'assetCodesLen', 'assetName', 'audiences',
'firstCreated', 'headline', 'headlineTag', 'marketCommentary', 'time_x','provider',
'returnsOpenNextMktres10', 'sourceId', 'subjects', 'time', 'universe','sourceTimestamp']]
fcol
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 model_pred = model.predict(test_images_ds)
 model2_pred = model2.predict(test_images_ds)
 probabilities =(model_pred * 0.56)+(model2_pred * 0.44)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 print('Generating submission.csv file...')
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 !head submission.csv<train_model>
X = market_train_df[fcol].values
X
print(f'Post training time : {(datetime.now() - POST_TRAINING_TIME_START ).total_seconds() } seconds' )<install_modules>
up = up.values
up
!pip install -q efficientnet<import_modules>
r = market_train_df.returnsOpenNextMktres10.values
r
print("Tensorflow version " + tf.__version__)
<train_on_grid>
mins = np.min(X, axis=0)
 mins
AUTO = tf.data.experimental.AUTOTUNE
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
 except ValueError:
tpu = None
if tpu:
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu)
 else:
strategy = tf.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync)
 GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification')
 GCS_DS_PATH2 = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec')
 img_size=512
IMAGE_SIZE = [img_size, img_size]
EPOCHS = 25
BATCH_SIZE = 16 * strategy.num_replicas_in_sync<init_hyperparams>
maxs = np.max(X, axis=0)
 maxs
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<define_variables>
rng = maxs - mins
rng
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH_SELECT2 = {
192: GCS_DS_PATH2 + '/oxford102/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/oxford102/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/oxford102/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/oxford102/tfrecords-jpeg-512x512'
}
GCS_PATH_SELECT3 = {
192: GCS_DS_PATH2 + '/imagenet/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/imagenet/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/imagenet/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/imagenet/tfrecords-jpeg-512x512'
}
GCS_PATH_SELECT4 = {
192: GCS_DS_PATH2 + '/inaturalist/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/inaturalist/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/inaturalist/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/inaturalist/tfrecords-jpeg-512x512'
}
GCS_PATH_SELECT5 = {
192: GCS_DS_PATH2 + '/inaturalist_1/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/inaturalist_1/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/inaturalist_1/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/inaturalist_1/tfrecords-jpeg-512x512'
}
GCS_PATH_SELECT6 = {
192: GCS_DS_PATH2 + '/tf_flowers/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/tf_flowers/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/tf_flowers/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/tf_flowers/tfrecords-jpeg-512x512'
}
GCS_PATH_SELECT7 = {
192: GCS_DS_PATH2 + '/openimage/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/openimage/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/openimage/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/openimage/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
GCS_PATH2 = GCS_PATH_SELECT2[IMAGE_SIZE[0]]
GCS_PATH3 = GCS_PATH_SELECT3[IMAGE_SIZE[0]]
GCS_PATH4 = GCS_PATH_SELECT4[IMAGE_SIZE[0]]
GCS_PATH5 = GCS_PATH_SELECT5[IMAGE_SIZE[0]]
GCS_PATH6 = GCS_PATH_SELECT6[IMAGE_SIZE[0]]
GCS_PATH7 = GCS_PATH_SELECT7[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 TRAINING_FILENAMES2 = tf.io.gfile.glob(GCS_PATH2 + '/*.tfrec')
 TRAINING_FILENAMES3 = tf.io.gfile.glob(GCS_PATH3 + '/*.tfrec')
 TRAINING_FILENAMES4 = tf.io.gfile.glob(GCS_PATH4 + '/*.tfrec')
 TRAINING_FILENAMES5 = tf.io.gfile.glob(GCS_PATH5 + '/*.tfrec')
 TRAINING_FILENAMES6 = tf.io.gfile.glob(GCS_PATH6 + '/*.tfrec')
 TRAINING_FILENAMES7 = tf.io.gfile.glob(GCS_PATH7 + '/*.tfrec')
 TRAINING_FILENAMES=TRAINING_FILENAMES+TRAINING_FILENAMES2+TRAINING_FILENAMES3+TRAINING_FILENAMES5+TRAINING_FILENAMES6+TRAINING_FILENAMES7
VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 SKIP_VALIDATION = True
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES<set_options>
X = 1 -(( maxs - X)/ rng)
 X
MIXED_PRECISION = True
XLA_ACCELERATE = True
if MIXED_PRECISION:
if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')
 else: policy = tf.keras.mixed_precision.experimental.Policy('float32')
 mixed_precision.set_policy(policy)
 print('Mixed precision enabled')
 if XLA_ACCELERATE:
tf.config.optimizer.set_jit(True)
 print('Accelerated Linear Algebra enabled' )<define_variables>
from xgboost import XGBClassifier
from sklearn import model_selection
from sklearn.metrics import mean_squared_error
import time
CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']<categorify>
X_train, X_test, up_train, up_test, r_train, r_test,u_train,u_test,d_train,d_test = \
model_selection.train_test_split(X, up, r,universe,d, test_size=0.25, random_state=99 )
def random_blockout(img, sl=0.1, sh=0.2, rl=0.4):
h, w, c = img_size, img_size, 3
origin_area = tf.cast(h*w, tf.float32)
 e_size_l = tf.cast(tf.round(tf.sqrt(origin_area * sl * rl)) , tf.int32)
 e_size_h = tf.cast(tf.round(tf.sqrt(origin_area * sh / rl)) , tf.int32)
 e_height_h = tf.minimum(e_size_h, h)
 e_width_h = tf.minimum(e_size_h, w)
 erase_height = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_height_h, dtype=tf.int32)
 erase_width = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_width_h, dtype=tf.int32)
 erase_area = tf.zeros(shape=[erase_height, erase_width, c])
 erase_area = tf.cast(erase_area, tf.uint8)
 pad_h = h - erase_height
pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_h, dtype=tf.int32)
 pad_bottom = pad_h - pad_top
pad_w = w - erase_width
pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_w, dtype=tf.int32)
 pad_right = pad_w - pad_left
erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1)
 erase_mask = tf.squeeze(erase_mask, axis=0)
 erased_img = tf.multiply(tf.cast(img,tf.float32), tf.cast(erase_mask, tf.float32))
return tf.cast(erased_img, img.dtype )<categorify>
train_data = lgb.Dataset(X, label=up.astype(int))
test_data = lgb.Dataset(X_test, label=up_test.astype(int))
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
 NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES =(1 - SKIP_VALIDATION)* count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<choose_model_class>
x_1 = [0.19000424246380565, 2452, 212, 328, 202]
x_2 = [0.19016805202090095, 2583, 213, 312, 220]
print(up_train)
 def exp_loss(p,y):
y = y.get_label()
grad = -y*(1.0-1.0/(1.0+np.exp(-y*p)))
 hess = -(np.exp(y*p)*(y*p-1)-1)/(( np.exp(y*p)+1)**2)
 return grad,hess
params_1 = {
'task': 'train',
'boosting_type': 'gbdt',
'objective': 'binary',
'learning_rate': x_1[0],
'num_leaves': x_1[1],
'min_data_in_leaf': x_1[2],
'num_iteration': 239,
'max_bin': x_1[4],
'verbose': 1
}
params_2 = {
'task': 'train',
'boosting_type': 'gbdt',
'objective': 'binary',
'learning_rate': x_2[0],
'num_leaves': x_2[1],
'min_data_in_leaf': x_2[2],
'num_iteration': 172,
'max_bin': x_2[4],
'verbose': 1
}
gbm_1 = lgb.train(params_1,
train_data,
num_boost_round=133,
valid_sets=test_data,
early_stopping_rounds=5, 
)
 gbm_2 = lgb.train(params_2,
train_data,
num_boost_round=133,
valid_sets=test_data,
early_stopping_rounds=5,
)
<choose_model_class>
confidence_test =(gbm_1.predict(X_test)+ gbm_2.predict(X_test)) /2
confidence_test
<choose_model_class>
confidence_test =(confidence_test-confidence_test.min())/(confidence_test.max() -confidence_test.min())
 confidence_test
<choose_model_class>
confidence_test = confidence_test*2-1
print(max(confidence_test),min(confidence_test))
confidence_test
<choose_model_class>
r_test = r_test.clip(-1,1)
 x_t_i = confidence_test * r_test * u_test
data = {'day' : d_test, 'x_t_i' : x_t_i}
df = pd.DataFrame(data)
 x_t = df.groupby('day' ).sum().values.flatten()
mean = np.mean(x_t)
 std = np.std(x_t)
 score_test = mean / std
print(score_test )
with strategy.scope() :
net=MobileNetV2(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 model = tf.keras.Sequential([
net,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype=tf.float32)
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()<train_model>
del X_train,X_test
gc.collect()
history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() 
)
 model.save_weights("model.h5")
 test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 preds1=model.predict(test_images_ds)
 del model
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )<import_modules>
days = env.get_prediction_days()
n_days = 0
prep_time = 0
prediction_time = 0
packaging_time = 0
total_market_obs_df = []
for(market_obs_df, news_obs_df, predictions_template_df)in days:
n_days +=1
if(n_days%50==0):
print(n_days,end=' ')
 t = time.time()
market_obs_df['time'] = market_obs_df['time'].dt.date
return_features = ['returnsClosePrevMktres10','returnsClosePrevRaw10','open','close']
total_market_obs_df.append(market_obs_df)
 if len(total_market_obs_df)==1:
history_df = total_market_obs_df[0]
else:
history_df = pd.concat(total_market_obs_df[-(np.max(n_lag)+1):])
 print(history_df)
 new_df = generate_lag_features(history_df,n_lag=[3,7,14])
 market_obs_df = pd.merge(market_obs_df,new_df,how='left',on=['time','assetCode'])
 market_obs_df = mis_impute(market_obs_df)
 market_obs_df = data_prep(market_obs_df)
 X_live = market_obs_df[fcol].values
X_live = 1 -(( maxs - X_live)/ rng)
 prep_time += time.time() - t
t = time.time()
lp =(gbm_1.predict(X_live)+ gbm_2.predict(X_live)) /2
prediction_time += time.time() -t
t = time.time()
confidence = lp
confidence =(confidence-confidence.min())/(confidence.max() -confidence.min())
 confidence = confidence * 2 - 1
preds = pd.DataFrame({'assetCode':market_obs_df['assetCode'],'confidence':confidence})
 predictions_template_df = predictions_template_df.merge(preds,how='left' ).drop('confidenceValue',axis=1 ).fillna(0 ).rename(columns={'confidence':'confidenceValue'})
 env.predict(predictions_template_df)
 packaging_time += time.time() - t
env.write_submission_file()
sub = pd.read_csv("submission.csv" )