#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 15 13:37:35 2021

@author: manssandsjo
"""
import os
import numpy as np
import pandas as pd

os.chdir(os.path.pardir)
#import sys
## insert at 1, 0 is the script path (or '' in REPL)
#sys.path.insert(1, '/Data')

from Data import investPyData as omxs30
Rpd, N = omxs30.import_omxs30() # N number of stocks, R return between two days

T = len(Rpd)
R=Rpd.to_numpy()
print(T/252)


## Train LSTM-model
from keras.models import Sequential # init neural netW
from keras.layers import Dense # adding densly connected neural network
from keras.layers import LSTM # Long short term memory
from keras.layers import Dropout # prevent overfitting with dropout layers
from keras import backend as back

from sklearn.preprocessing import MinMaxScaler
def teachLSTM(stock):
    R1 = Rpd[stock].copy()
    predDays = 1
    #clear old session to avoid clutter from old models/layers
    back.clear_session()
    #train model on all days except last 30
    trYrs = len(R1)-30;
    df_train = R1[0:trYrs]

    #scale data for performance

    sc = MinMaxScaler(feature_range = (0, 1))
    df_train_scaled = sc.fit_transform(df_train)
    
    #creating 3D array
    x_train, y_train = [], []

    # prepare the dataset with predDay timesteps:
    for i in range(predDays, trYrs): 
        x_train.append(df_train_scaled[i-predDays:i, 0])
        y_train.append(df_train_scaled[i, 0])

    x_train, y_train = np.array(x_train), np.array(y_train)

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

    # built model
    # create and fit the LSTM network
    # Sequential– a plain stack of layers where each layer has exactly one input tensor and one output tensor
    model = Sequential()
    # units = 50 – dimensionality of output space

    # går att modda väldigt mycket här
    model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1],1)))
    model.add(Dropout(0.2))

    model.add(LSTM(units = 50, return_sequences = True))
    model.add(Dropout(0.2))

    model.add(LSTM(units = 50, return_sequences = True))
    model.add(Dropout(0.2))

    model.add(LSTM(units = 50))
    model.add(Dropout(0.2))

    model.add(Dense(units = 1))

    model.compile(loss='mean_squared_error', optimizer='adam')
    # slice data into batch size 32 for training
    # iterate over 20 periods 
    model.fit(x_train, y_train, epochs=2)
    
    return model
