# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" 
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import warnings
warnings.filterwarnings('ignore')

from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, mean_absolute_error, explained_variance_score, r2_score 
from sklearn.metrics import mean_poisson_deviance, mean_gamma_deviance, accuracy_score
from xgboost import XGBRegressor
df_bitcoin = pd.read_csv('../input/all-cryptocurrencies-price-20152021/Bitcoin/BTC-USD.csv')
df_bitcoin.head()
df_bitcoin.shape
missing_values=pd.DataFrame(df_bitcoin.isna().sum().sort_values(ascending=False),columns=['Missing_values'])
missing_values['%']=(missing_values.Missing_values/2193)*100
missing_values
df_dogecoin = pd.read_csv('../input/all-cryptocurrencies-price-20152021/Dogecoin/DOGE-USD.csv')
df_dogecoin.head()
missing_values2=pd.DataFrame(df_dogecoin.isna().sum().sort_values(ascending=False),columns=['Missing_values'])
missing_values2['%']=(missing_values.Missing_values/2193)*100
missing_values2
df_ethereum = pd.read_csv('../input/all-cryptocurrencies-price-20152021/Ethereum/ETH-USD.csv')
df_ethereum.head()
missing_values3=pd.DataFrame(df_ethereum.isna().sum().sort_values(ascending=False),columns=['Missing_values'])
missing_values3['%']=(missing_values.Missing_values/2193)*100
missing_values3
df_cardano = pd.read_csv('../input/all-cryptocurrencies-price-20152021/Cardano/ADA-USD.csv')
missing_values4=pd.DataFrame(df_ethereum.isna().sum().sort_values(ascending=False),columns=['Missing_values'])
missing_values4['%']=(missing_values.Missing_values/2193)*100
missing_values4.head()
for col in df_bitcoin.columns:
    print(type(col))
"""
# Converting the Date column to datetime
"""
df_bitcoin['Date']=pd.to_datetime(df_bitcoin['Date'])
df_dogecoin['Date']=pd.to_datetime(df_dogecoin['Date'])
df_ethereum['Date']=pd.to_datetime(df_ethereum['Date'])
df_cardano['Date']=pd.to_datetime(df_cardano['Date'])
df_bitcoin.head()
"""
# Trend followed by closing price
"""
fig = plt.figure(figsize = (16,7))

plt.plot(df_bitcoin.Date,df_bitcoin.Close,color='purple')
plt.plot(df_dogecoin.Date,df_dogecoin.Close,color='red')
plt.plot(df_ethereum.Date,df_ethereum.Close,color='violet')
plt.plot(df_cardano.Date,df_cardano.Close,color='yellow')

plt.title('Closing Price Trend')
plt.legend(['Bitcoin','Dogecoin','Ethereum','Cardano'])
plt.show()
"""
# Volume Trend
"""
fig = plt.figure(figsize = (17,11))

plt.subplot(2,2,1)
plt.plot(df_bitcoin.Date,df_bitcoin.Volume,color='purple')
plt.title('Bitcoin')


plt.subplot(2,2,2)
plt.plot(df_dogecoin.Date,df_dogecoin.Volume,color='red')
plt.title('Dogecoin')

plt.subplot(2,2,3)

plt.plot(df_ethereum.Date,df_ethereum.Volume,color='blue')
plt.title('Ethereum')


plt.subplot(2,2,4)

plt.plot(df_cardano.Date,df_cardano.Volume,color='violet')
plt.title('Cardano')

fig.tight_layout()
"""
# Analysis of Closing price over the last two years
"""
two_year_bitcoin=df_bitcoin[df_bitcoin.Date>'2019-09']
two_year_dogecoin=dogecoin=df_dogecoin[df_dogecoin.Date>'2019-09']
two_year_ethereum=df_ethereum[df_ethereum.Date>'2019-09']
two_year_cardano=df_cardano[df_cardano.Date>'2019-09']
fig = plt.figure(figsize = (16,7))

plt.plot(two_year_bitcoin.Date,two_year_bitcoin.Close,color='purple')
plt.plot(two_year_dogecoin.Date,two_year_dogecoin.Close,color='red')
plt.plot(two_year_ethereum.Date,two_year_ethereum.Close,color='blue')
plt.plot(two_year_cardano.Date,two_year_cardano.Close,color='violet')
plt.title('Closing Price over 2 years')
plt.legend(['Bitcoin','Dogecoin','Ethereum','Cardano'])
plt.show()
"""
# Trend followed by Volume over the last two years
"""
fig = plt.figure(figsize = (16,7))

plt.plot(two_year_bitcoin.Date,two_year_bitcoin.Volume,color='purple')
plt.plot(two_year_dogecoin.Date,two_year_dogecoin.Volume,color='red')
plt.plot(two_year_ethereum.Date,two_year_ethereum.Volume,color='blue')
plt.plot(two_year_cardano.Date,two_year_cardano.Volume,color='violet')

plt.title('Volume over two years')
plt.legend(['Bitcoin','Dogecoin','Ethereum','Cardano'])
plt.show()
"""
# Comparion between open and closing price for Cryptocurrencies

"""
fig = plt.figure(figsize = (17,17))

plt.subplot(4, 1, 1)
plt.plot(two_year_bitcoin.Date,two_year_bitcoin['Close'],color='purple')
plt.plot(two_year_bitcoin.Date,two_year_bitcoin['Open'],color='red')
plt.legend(['Closing','Open'])
plt.title('Bitcoin')

plt.subplot(4, 1, 2)
plt.plot(two_year_dogecoin.Date,two_year_dogecoin['Close'],color='red')
plt.plot(two_year_dogecoin.Date,two_year_dogecoin['Open'],color='green')
plt.legend(['Closing','Open'])
plt.title('Dogecoin')

plt.subplot(4, 1, 3)
plt.plot(two_year_ethereum.Date,two_year_ethereum['Close'],color='black')
plt.plot(two_year_ethereum.Date,two_year_ethereum['Open'],color='green')
plt.legend(['Closing','Open'])
plt.title('Ethereum')

plt.subplot(4, 1, 4)
plt.plot(two_year_cardano.Date,two_year_cardano['Close'],color='green')
plt.plot(two_year_cardano.Date,two_year_cardano['Open'],color='purple')
plt.legend(['Closing','Open'])
plt.title('Cardano')


fig.tight_layout()
"""
# Daily Change of Cryptocurrency
"""
fig = plt.figure(figsize = (15,10))

plt.subplot(2, 2, 1)
plt.plot(df_bitcoin.Date,df_bitcoin['Adj Close'].pct_change(),color='purple')
plt.title('Bitcoin')

plt.subplot(2, 2, 2)
plt.plot(df_dogecoin.Date,df_dogecoin['Adj Close'].pct_change(),color='red')
plt.title('Dogecoin')

plt.subplot(2, 2, 3)
plt.plot(df_ethereum.Date,df_ethereum['Adj Close'].pct_change(),color='yellow')
plt.title('Ethereum')

plt.subplot(2, 2, 4)
plt.plot(df_cardano.Date,df_cardano['Adj Close'].pct_change(),color='green')
plt.title('Cardano')


fig.tight_layout()
"""
# Density plots for daily return
"""
fig = plt.figure(figsize = (15,10))

plt.subplot(2, 2, 1)
sns.distplot(df_bitcoin['Adj Close'].pct_change(),kde=True,color='blue')
plt.xlabel('Daily Return')
plt.ylabel('Daily Return')
plt.title('Bitcoin')

plt.subplot(2, 2, 2)
sns.distplot(df_dogecoin['Adj Close'].pct_change(),color='red')
plt.xlabel('Daily Return')
plt.ylabel('Daily Return')
plt.title('Dogecoin')

plt.subplot(2, 2, 3)
sns.distplot(df_ethereum['Adj Close'].pct_change(),color='purple')
plt.xlabel('Daily Return')
plt.ylabel('Daily Return')
plt.title('Ethereum')

plt.subplot(2, 2, 4)
sns.distplot(df_cardano['Adj Close'].pct_change(),color='green')
plt.title('Cardano')
plt.xlabel('Daily Return')
plt.ylabel('Daily Return')

fig.tight_layout()
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import LSTM

"""
# Bitcoin Predictions
"""
final_df=df_bitcoin[['Date','Close']]
final_df=final_df[final_df.Date>'2020-09']
final_df.head()
fig = plt.figure(figsize = (10,10))
plt.plot(final_df.Date,final_df.Close,color='purple')
plt.title('Close Price History')
plt.xlabel('Date',fontsize=18)
plt.xticks(rotation=90)
plt.show()
"""
# New Dataframe with only the Closed column
"""
final_df=final_df.set_index('Date')
data=final_df.filter(['Close'])
data.head()
data.isna().sum()
data=data.dropna(subset=['Close'])
data.shape
dataset=data.values
training_data_len=int(np.ceil(len(dataset)*0.8))
training_data_len
"""
# Scale the Data
"""
mms=MinMaxScaler(feature_range=(0,1))
scaled_data=mms.fit_transform(dataset)
"""
# Creating a Training dataset
"""
train_data=scaled_data[0:training_data_len ,:]
len(train_data)
X_train=[]
y_train=[]

for i in range(60,len(train_data)):
    X_train.append(train_data[i-60:i,0])
    y_train.append(train_data[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))
X_train.shape
"""
# LSTM Model
"""
model=Sequential()
model.add(LSTM(128,return_sequences=True,input_shape=(X_train.shape[1],1)))
model.add(LSTM(64,return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
model.compile(optimizer='adam',loss='mean_squared_error')
model.fit(X_train, y_train, batch_size=1, epochs=1)
"""
# Train the model

"""
"""
# Test Data set
"""
test_data=scaled_data[training_data_len-60:621:,:]

X_test=[]
y_test=dataset[training_data_len:,:]

for i in range(60,len(test_data)):
    X_test.append(test_data[i-60:i,0])
X_test=np.array(X_test)
X_test=np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))
X_test.shape
"""
# Predicted Price
"""
predictions=model.predict(X_test)
predictions=mms.inverse_transform(predictions)
train=data[:training_data_len]
valid=data[training_data_len:]
valid['Predictions']=predictions
train

plt.figure(figsize=(15,15))
plt.title('Model')

plt.xlabel('Date',fontsize=16)
plt.ylabel('Closed Price ',fontsize=16)

plt.plot(train['Close'])
plt.plot(valid[['Close','Predictions']])

plt.legend(['Train','Validation','Predictions'])
plt.show()