import os
import pandas as pd


if __name__ == '__main__':
    files = []
    for r, filename_data in enumerate(os.listdir(".")):
        if filename_data.split(".")[-1] == "csv" and filename_data.split("_")[0] != "X":
            index = filename_data.split("_")[-1].split(".")[0]
            files.append([pd.read_csv("{}".format(filename_data)), index])
            print(index, filename_data)

    for argument in ["Open", "Close", "High", "Low"]:
        X = files[0][0][["Date", argument]]
        X_index = files[0][1]
        X = X.rename(columns={"Date" : "Date", argument : argument + "_{}".format(X_index)})
        print(X.head())
        X[argument + "_{}".format(X_index)] = X[argument + "_{}".format(X_index)].apply(lambda x: float(x.replace(",","")))
        for i in range(len(files) - 1):
            Y = files[i + 1][0][["Date", argument]]
            Y_index = files[i + 1][1]
            Y = Y.rename(columns={"Date" : "Date", argument : argument + "_{}".format(Y_index)})
            print(Y.head())
            Y[argument + "_{}".format(Y_index)] = Y[argument + "_{}".format(Y_index)].apply(lambda x: float(x.replace(",","")))
            X = pd.merge(X, Y, on="Date", how="inner") #considers the intersection of keys

        X = X.iloc[::-1] # reverse the order of rows so the oldest stock value is first
        X.to_csv("X_{}.csv".format(argument), index=False)

        if (argument == "Open"):
            dfOpen = X
        elif (argument == "Close"):
            dfClose = X

    df = pd.merge(dfOpen, dfClose, on="Date", how="inner")
    df.to_csv("X_OpenClose.csv", index=False)
    