-
Notifications
You must be signed in to change notification settings - Fork 0
/
nifty50dnn.py
126 lines (117 loc) · 4.89 KB
/
nifty50dnn.py
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
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
import matplotlib.pyplot as plt
import keras
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
np.random.seed(1)
cols = ['Date', 'Open', 'High', 'Low', 'Close', 'Future_Close']
data = pd.read_csv('^NSEI_withoutnull.csv', header=0, names=cols)
data.dropna(axis=0, how='any')
data = data.drop(['Date'], axis=1)
arr = data.copy()
arr = arr.dropna(axis=0, how='any')
train_start=0
train_end=int(np.floor(0.8*arr.shape[0]))
test_start=train_end+1
test_end=int(arr.shape[0])
arr = arr.values
# shuffle_indices = np.random.permutation(np.arange(2466))
# arr=arr[shuffle_indices]
data_train=arr[np.arange(train_start, train_end),:]
data_test=arr[np.arange(test_start,test_end),:]
data_train=pd.DataFrame(data_train)
data_test=pd.DataFrame(data_test)
"""
for i in range(0,5):
data_train=data_train.loc[data_train[i]!='null',:]
data_test=data_test.loc[data_test[i]!='null',:]
"""
data_train=data_train.astype(float)
data_test=data_test.astype(float)
data_train.columns = cols[1:]
data_test.columns = cols[1:]
data_train['Close'] = pd.to_numeric(data_train['Close'], errors='coerce').fillna(0).astype(float)
data_train['Future_Close'] = pd.to_numeric(data_train['Future_Close'], errors='coerce').fillna(0).astype(float)
data_train['Ratio'] = data_train['Future_Close']/data_train['Close']
data_test['Close'] = pd.to_numeric(data_test['Close'], errors='coerce').fillna(0).astype(float)
data_test['Future_Close'] = pd.to_numeric(data_test['Future_Close'], errors='coerce').fillna(0).astype(float)
data_test['Ratio'] = data_test['Future_Close']/data_test['Close']
data_train['Direction'] = np.where(data_train['Future_Close'] > data_train['Close'], 1, 0)
data_test['Direction'] = np.where(data_test['Future_Close'] > data_test['Close'], 1, 0)
# scaler=MinMaxScaler()
# scaler.fit(data_train)
# data_train=scaler.transform(data_train)
# data_test=scaler.transform(data_test)
x_train=data_train.iloc[:,0:4]
y_train=data_train.iloc[:, 5]
x_test=data_test.iloc[:,0:4]
y_test=data_test.iloc[:, 5]
features = 4
X = tf.placeholder(dtype=tf.float32, shape=[None, features])
Y = tf.placeholder(dtype=tf.float32, shape=[None])
n_neurons_1 = 20
n_neurons_2 = 10
n_neurons_3 = 5
n_target = 1
sigma = 1
weight_initializer = keras.initializers.VarianceScaling(mode="fan_avg", distribution="uniform", scale=sigma)
bias_initializer = tf.constant_initializer()
W_hidden_1 = tf.Variable(weight_initializer([features, n_neurons_1]))
bias_hidden_1 = tf.Variable(bias_initializer([n_neurons_1]))
W_hidden_2 = tf.Variable(weight_initializer([n_neurons_1, n_neurons_2]))
bias_hidden_2 = tf.Variable(bias_initializer([n_neurons_2]))
W_hidden_3 = tf.Variable(weight_initializer([n_neurons_2, n_neurons_3]))
bias_hidden_3 = tf.Variable(bias_initializer([n_neurons_3]))
W_out = tf.Variable(weight_initializer([n_neurons_3, n_target]))
bias_out = tf.Variable(bias_initializer([n_target]))
hidden_1 = tf.nn.relu(tf.add(tf.matmul(X, W_hidden_1), bias_hidden_1))
hidden_2 = tf.nn.relu(tf.add(tf.matmul(hidden_1, W_hidden_2), bias_hidden_2))
hidden_3 = tf.nn.relu(tf.add(tf.matmul(hidden_2, W_hidden_3), bias_hidden_3))
out = (tf.add(tf.matmul(hidden_3, W_out), bias_out))
# mae=tf.reduce_mean(tf.abs(tf.subtract(Y,out)))
rmse=tf.sqrt(tf.reduce_mean(tf.squared_difference(out, Y)))
# mse = tf.reduce_mean(tf.squared_difference(out, Y))
opt = tf.train.AdamOptimizer(learning_rate=0.001, beta1=.99, beta2=.999).minimize(rmse)
net = tf.Session()
net.run(tf.global_variables_initializer())
# Number of epochs and batch size
epochs = 100
batch_size = 264
for e in range(epochs):
# Shuffle training data
# shuffle_indices = np.random.permutation(np.arange(len(y_train)))
# x_train = x_train.iloc[shuffle_indices,:]
# y_train = y_train.iloc[shuffle_indices]
# Minibatch training
for i in range(0, len(y_train) // batch_size):
start = i * batch_size
batch_x = x_train[start:start + batch_size]
batch_y = y_train[start:start + batch_size]
# Run optimizer with batch
net.run(opt, feed_dict={X: batch_x, Y: batch_y})
# Show progress
# if np.mod(i, 5) == 0:
# Prediction
# pred = net.run(out, feed_dict={X: x_test})
# line2, = ax1.plot(pred)
# plt.title('Epoch ' + str(e) + ', Batch ' + str(i))
# file_name = 'epoch_' + str(e) + '_batch_' + str(i)
# plt.savefig(file_name+'.jpg')
# plt.pause(0.01)
pred=net.run(out, feed_dict={X:x_test})
print(pred)
fig = plt.figure()
ax1 = fig.add_subplot(111)
line1, =ax1.plot(y_test, linewidth=0.5)
line2, = ax1.plot(pred, linewidth=0.5)
plt.savefig('nn3.jpeg')
#testing on very old 2003 data (out of range)
a=[ 1699.70 ,1728.00 ,1699.70, 1723.95 ]
pred2=net.run(out, feed_dict={X:pd.DataFrame(a).T})
print(pred2)
#printing mae
print(np.sum(np.abs(np.subtract(pred,(y_test.values.reshape(len(pred),1)))))/len(pred))
#vini vici chakra