-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBITCOIN.PY
More file actions
127 lines (107 loc) · 3.89 KB
/
Copy pathBITCOIN.PY
File metadata and controls
127 lines (107 loc) · 3.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from xgboost import XGBClassifier
from sklearn import metrics
import warnings
warnings.filterwarnings('ignore')
# Load the dataset
df = pd.read_csv('bitcoin.csv')
print(df.head())
print(df.shape)
print(df.describe())
print(df.info())
# Plotting the 'close' prices
plt.figure(figsize=(15, 5))
plt.plot(df['close'])
plt.title('Bitcoin Close Price', fontsize=15)
plt.ylabel('Price in dollars')
plt.show()
# Checking for null values
print("Check if data is null:")
print(df.isnull().sum())
# Defining the features to visualize
features = ['open', 'high', 'low', 'close']
# Plotting distributions of features
plt.figure(figsize=(20, 10))
for i, col in enumerate(features):
plt.subplot(2, 2, i+1)
sb.distplot(df[col])
plt.show()
# Plotting distributions of features with a filtered range
plt.figure(figsize=(20, 10))
for i, col in enumerate(features):
range_min = 0.0
range_max = 10000.0
filtered_data = [x for x in df[col] if range_min <= x <= range_max]
plt.subplot(2, 2, i+1)
sb.distplot(filtered_data)
plt.show()
# Plotting boxplots of features
plt.figure(figsize=(20, 10))
for i, col in enumerate(features):
plt.subplot(2, 2, i+1)
ax = sb.boxplot(df[col])
q1, median, q3 = df[col].quantile([0.25, 0.5, 0.75])
label_text = f"25%: {q1:.2f} median: {median:.2f} 75%: {q3:.2f}"
plt.text(20000, -0.35, label_text, fontsize=12)
IQR = q3 - q1
k = 1.5 # Adjust this value if needed
lower_fence = q1 - k * IQR
upper_fence = q3 + k * IQR
label_fence = f"Fence line: {upper_fence:.2f}"
plt.text(20000, -0.25, label_fence, fontsize=12)
plt.show()
# Splitting the date column and handling time separately
df['date'] = pd.to_datetime(df['date'])
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
print(df.head())
# Grouping data by year and plotting
data_grouped = df.groupby('year').mean()
plt.figure(figsize=(20, 10))
for i, col in enumerate(['open', 'high', 'low', 'close']):
plt.subplot(2, 2, i+1)
data_grouped[col].plot.bar()
dataLabel = f"{col}"
plt.text(3, 39000, dataLabel, fontsize=12)
plt.show()
# Feature engineering
df['is_quarter_end'] = np.where(df['month'] % 3 == 0, 1, 0)
print(df.head())
df['open-close'] = df['open'] - df['close']
df['low-high'] = df['low'] - df['high']
df['target'] = np.where(df['close'].shift(-1) > df['close'], 0, 1)
# Plotting target distribution
plt.figure(figsize=(10, 10))
plt.pie(df['target'].value_counts().values, labels=["Goes down", "Goes up"], autopct='%1.1f%%')
plt.show()
# Plotting heatmap of correlations
plt.figure(figsize=(10, 10))
sb.heatmap(df.corr() > 0.8, annot=True, cbar=False)
plt.show()
# Preparing features and target for model training
features = df[['open-close', 'low-high', 'is_quarter_end']]
target = df['target']
scaler = StandardScaler()
features = scaler.fit_transform(features)
X_train, X_valid, Y_train, Y_valid = train_test_split(features, target, test_size=0.1, random_state=2022)
print(X_train.shape, X_valid.shape)
# Training and evaluating models
models = [LogisticRegression(), SVC(kernel='poly', probability=True), XGBClassifier()]
for i in range(3):
models[i].fit(X_train, Y_train)
print(f'{models[i]}: ')
print('Training Accuracy:', metrics.roc_auc_score(Y_train, models[i].predict_proba(X_train)[:, 1]))
print('Validation Accuracy:', metrics.roc_auc_score(Y_valid, models[i].predict_proba(X_valid)[:, 1]))
print()
print('\n\n0 : Goes up')
print('1 : Goes down')
metrics.plot_confusion_matrix(models[0], X_valid, Y_valid)
plt.show()