forked from rian-dolphin/stock-embeddings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathS2V_models.py
262 lines (216 loc) · 10.9 KB
/
S2V_models.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 20 12:32:38 2021
@author: rian
"""
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
import torch.nn as nn
import torch.nn.functional as F
import torch
class CBOW_StockModeller_Single(nn.Module):
"""
Model architecture similar to CBOW Word2Vec but adapted for stock modelling
Note: Context size is inferred from the inputs and is not needed to be defined here
"""
def __init__(self, n_tickers, embedding_dim):
super(CBOW_StockModeller_Single, self).__init__() #-- This line calls the parent class nn.Module
#-- Only use one embedding matrix here
#- Seperate Input and Output embeddings not needed in this application
#- In NLP Word2Vec there is input and output matrix
self.embeddings = nn.Embedding(n_tickers, embedding_dim)
def forward(self, inputs):
#-- This extracts the relevant rows of the embedding matrix
#- Equivalent to W^T x_i in "word2vec Parameter Learning Explained"
temp = self.embeddings(inputs)#.view((len(inputs),-1))
#-- Compute the hidden layer by a simple mean
hidden = temp.mean(axis=1)
#-- Reshape to make matrix dimensions compatible
hidden = hidden.unsqueeze(dim=2)
#-- Compute dot product of hidden with embeddings
out = torch.matmul(self.embeddings.weight, hidden)
#-- Return the log softmax since we use NLLLoss loss function
return F.log_softmax(out, dim=1)
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
import numpy as np
class CBOW_StockModeller_Single_Weights(nn.Module):
"""
Model architecture similar to CBOW Word2Vec but adapted for stock modelling
Note: Context size is inferred from the inputs and is not needed to be defined here
"""
def __init__(self, n_tickers, embedding_dim):
super(CBOW_StockModeller_Single_Weights, self).__init__() #-- This line calls the parent class nn.Module
#-- Only use one embedding matrix here
#- Seperate Input and Output embeddings not needed in this application
#- In NLP Word2Vec there is input and output matrix
self.embeddings = nn.Embedding(n_tickers, embedding_dim)
def forward(self, inputs, y_batch, weights_df, idx2ticker):
"""
Parameters
----------
inputs : train_loader
The batch for training.
weights_df : DataFrame
The dataframe containing the count of how many times each stock appears
in anothers context. From this the weights will be computed.
idx2ticker : Dictionary
Dictionary to map from index value to ticker since the weights_df has tickers
as the column names and axes.
Returns
-------
Log Softmax prediction for the target stocks
"""
#-- This extracts the relevant rows of the embedding matrix
#- Equivalent to W^T x_i in "word2vec Parameter Learning Explained"
temp = self.embeddings(inputs)#.view((len(inputs),-1))
"""
This won't work unless the y_batch is given while training - is this reasonable?
Yes maybe, since we are not going to be using for predictions.
"""
#-- Get the weights for the input batch
w_list = []
for i in range(len(inputs)):
w = weights_df[idx2ticker[y_batch[i].item()]].iloc[inputs[i].tolist()].values
w = w/sum(w)
w_list.append(list(w))
#-- Store the weights for the whole batch
input_weights = torch.from_numpy(np.array(w_list))
#-- Multiply the weights in
temp = temp*input_weights[:,:,None]
#-- Compute the hidden layer
#- Since the weights are already multiplied in we just sum
hidden = temp.sum(axis=1)
cosine=True
if not cosine:
#-- Reshape to make matrix dimensions compatible
hidden = hidden.unsqueeze(dim=2)
#-- Compute dot product of hidden with embeddings
out = torch.matmul(self.embeddings.weight.double(), hidden.double())
else:
#-- Compute cosine similarity
out = sim_matrix(self.embeddings.weight, hidden) #-- sim_matrix defined below
#-- Swap rows and columns as required
#out = out.reshape(temp.shape[0],-1)
out = torch.t(out)
#-- Unsqueeze to get in correct format
out = out.unsqueeze(dim=2)
#-- Return the log softmax since we use NLLLoss loss function
return F.log_softmax(out, dim=1)
def sim_matrix(a, b, eps=1e-8):
"""
added eps for numerical stability
"""
a_n, b_n = a.norm(dim=1)[:, None], b.norm(dim=1)[:, None]
a_norm = a / torch.max(a_n, eps * torch.ones_like(a_n))
b_norm = b / torch.max(b_n, eps * torch.ones_like(b_n))
sim_mt = torch.mm(a_norm.double(), b_norm.transpose(0, 1).double())
return sim_mt
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
class CBOW_StockModeller_Single_Weights_Added_Layers(nn.Module):
"""
Model architecture similar to CBOW Word2Vec but adapted for stock modelling
Note: Context size is inferred from the inputs and is not needed to be defined here
"""
def __init__(self, n_tickers, embedding_dim):
super(CBOW_StockModeller_Single_Weights, self).__init__() #-- This line calls the parent class nn.Module
#-- Only use one embedding matrix here
#- Seperate Input and Output embeddings not needed in this application
#- In NLP Word2Vec there is input and output matrix
self.embeddings = nn.Embedding(n_tickers, embedding_dim)
#-- FOR NEW LAYERS
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
)
def forward(self, inputs, y_batch, weights_df, idx2ticker):
"""
Parameters
----------
inputs : train_loader
The batch for training.
weights_df : DataFrame
The dataframe containing the count of how many times each stock appears
in anothers context. From this the weights will be computed.
idx2ticker : Dictionary
Dictionary to map from index value to ticker since the weights_df has tickers
as the column names and axes.
Returns
-------
Log Softmax prediction for the target stocks
"""
#-- This extracts the relevant rows of the embedding matrix
#- Equivalent to W^T x_i in "word2vec Parameter Learning Explained"
temp = self.embeddings(inputs)#.view((len(inputs),-1))
"""
This won't work unless the y_batch is given while training - is this reasonable?
Yes maybe, since we are not going to be using for predictions.
"""
#-- Get the weights for the input batch
w_list = []
for i in range(len(inputs)):
w = weights_df[idx2ticker[y_batch[i].item()]].iloc[inputs[i].tolist()].values
w = w/sum(w)
w_list.append(list(w))
#-- Store the weights for the whole batch
input_weights = torch.from_numpy(np.array(w_list))
#-- Multiply the weights in
temp = temp*input_weights[:,:,None]
#-- Compute the hidden layer
#- We can use a simple mean since the weights are already multiplied in
hidden = temp.mean(axis=1)
#-- Reshape to make matrix dimensions compatible
hidden = hidden.unsqueeze(dim=2)
#-- Compute dot product of hidden with embeddings
out = torch.matmul(self.embeddings.weight.double(), hidden.double())
#-- Return the log softmax since we use NLLLoss loss function
return F.log_softmax(out, dim=1)
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
class CBOW_StockModeller_Double(nn.Module):
"""
Model architecture similar to CBOW Word2Vec but adapted for stock modelling
Note: Context size is inferred from the inputs and is not needed to be defined here
"""
def __init__(self, n_tickers, embedding_dim):
super(CBOW_StockModeller_Double, self).__init__() #-- This line calls the parent class nn.Module
#-- Only use one embedding matrix here
#- Seperate Input and Output embeddings not needed in this application
#- In NLP Word2Vec there is input and output matrix
self.embeddings_in = nn.Embedding(n_tickers, embedding_dim)
self.embeddings_out = nn.Embedding(n_tickers, embedding_dim)
def forward(self, inputs):
#-- This gets the relevant rows of the embedding matrix
#- Equivalent to (1/C) W^T (x_1+x_2+...+x_C) in "word2vec Parameter Learning Explained"
hidden = self.embeddings_in(inputs).mean(axis=1)
#-- Reshape to make matrix dimensions compatible
hidden = hidden.unsqueeze(dim=2)
#-- Compute dot product of hidden with embeddings
#- W_out * h
out = torch.matmul(self.embeddings_out.weight, hidden)
#-- Return the log softmax since we use NLLLoss loss function
return F.log_softmax(out, dim=1)
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#-- Skip gram