<jupyter_start><jupyter_text>**Euro to Inr Exchange rate prediciton using LSTM**<jupyter_code>#import necessary package
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

from sklearn.preprocessing import MinMaxScaler
from keras import optimizers
import keras
from keras.models import Sequential
from keras.layers import Dense, LSTM
import keras.backend as K

import tqdm<jupyter_output><empty_output><jupyter_text>**Dataset**The dataset was collected from https://in.investing.com/currencies/eur-inr-historical-data. Create an account and download the dataset or just go to my github repository to collect the dataset.<jupyter_code>a = pd.read_csv('euro_to_inr.csv')
df = a[['date', 'price']]
df.columns = ['date', 'price']
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
df = df.sort_values(by='date')
# df = df.reset_index(drop=True)
df.tail()
df.iloc[3500]
df.plot()
split_date = pd.Timestamp('2015-04-19')
train = df.loc[:split_date, ['price']]
test = df.loc[split_date:, ['price']]
ax = train.plot()
test.plot(ax=ax)
plt.legend(['train', 'test'])
sc = MinMaxScaler()

train_sc = sc.fit_transform(train)
test_sc = sc.transform(test)
train_sc[:4]
train[:4]
X_train = train_sc[:-1]
y_train = train_sc[1:]

X_test = test_sc[:-1]
y_test = test_sc[1:]
train_sc.shape
y_train
X_train_t = X_train[:, None]
X_test_t = X_test[:, None]
X_train_t.shape
num_units = 4
activation_function = 'sigmoid'
optimizer = 'adam'
loss_function = 'mean_squared_error'
batch_size = 60
num_epochs = 75

# Initialize the RNN
regressor = Sequential()

# Adding the input layer and the LSTM layer
regressor.add(LSTM(units = num_units, activation = activation_function, input_shape=(1, 1)))

# Adding the output layer
regressor.add(Dense(units = 1))

# Compiling the RNN
regressor.compile(optimizer = optimizer, loss = loss_function)

# Using the training set to train the model

regressor.fit(X_train_t, y_train, batch_size = batch_size, epochs = num_epochs)
y_pred = regressor.predict(X_test_t)
plt.figure()
plt.plot(y_test)
plt.plot(y_pred)
plt.legend(['real', 'predict'])
regressor.save('model.h5')

from keras.models import load_model
def predict_torrmow():
    model = load_model('model.h5')



    train = df[["price"]]
    sc = MinMaxScaler()

    train_sc = sc.fit_transform(train)
    X_train = train_sc[:-1]
    y_train = train_sc[1:]
    X_train_t = X_train[:, None]

    y_pred = model.predict(X_train_t)
    result = sc.inverse_transform(y_pred)[-2:]
    today = result[0][0]
    tomorrow =result[1][0]
    output = "flat"
    if tomorrow > today:
        output = "up"
    elif tomorrow < today:
        output = "down"
    return output, tomorrow
for i in range(30):

  sign, price = predict_torrmow()
  print(sign,price)

  x = pd.DatetimeIndex(df.iloc[-1:].index.values) + pd.DateOffset(1)
  ts = pd.to_datetime(x[0])
  tomorrow = ts.strftime('%Y-%m-%d')

  new_df = pd.DataFrame([[tomorrow,price]],columns=["date","price"])
  new_df['date'] = pd.to_datetime(new_df['date'])
  new_df = new_df.set_index('date')

  df = df.append(new_df)
  df["price"] = df["price"].astype(float)
  df.to_csv("data.csv")
  new_df_predict = pd.DataFrame([[tomorrow, sign, price]], columns=["date","trend","price"])
  df_predict = pd.read_csv("data_predicted.csv")
  check_date = pd.DatetimeIndex(df_predict.iloc[-1:]["date"].values).strftime('%Y-%m-%d')[0]
  try:
      days = df.iloc[df.index.get_loc(check_date)-1: df.index.get_loc(check_date)+1]
  except:
      days = df.iloc[-2:]
  today_price = days.iloc[1]["price"]
  yesterday_price = days.iloc[0]["price"]
  real_sign = "flat"
  if today_price > yesterday_price:
      real_sign = "up"
  elif today_price < yesterday_price:
      real_sign = "down"
  df_predict = df_predict.append(new_df_predict, ignore_index=True)
  df_predict.to_csv("data_predicted.csv", index=False)
df.tail(10)
df_predict<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14942528735632185, 'fraction_numerical': 0.012515964240102172, 'mean_word_length': 5.052550231839258, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '192132', 'license': 'Apache-2.0', 'n_tokens_mistral': 1518, 'n_tokens_neox': 1468, 'n_words': 303, 'path': 'EURO_to_INR.ipynb', 'repo_name': 'vigneshdurairaj/EURO-to-INR-exchange-rate-prediction-using-LSTM', 'size': '3915'}