-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalysis.py
235 lines (156 loc) · 6.49 KB
/
analysis.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
import os
import sys
import nltk
import json
import re
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import math
import yfinance as yf
from nltk.stem.wordnet import WordNetLemmatizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import jaccard_score
from sklearn.metrics.pairwise import cosine_similarity as cs
def main():
sentiment_scores_test('fb', 'tokenized_words.json')
pass
def sentiment_scores_test(ticker, input_filename):
sentiments = pd.read_csv('supporting_data/sentiment_dataframe.csv')
with open(input_filename, 'r') as f:
tokens = json.loads(f.read())
documents = reformat_documents(ticker, tokens)
sbow = sentiment_bag_of_words(documents, sentiments)
scores = sentiment_scores(sbow)
print(scores)
plot_sentiment_scores(ticker, scores)
def sentiment_scores(sbow):
scores = {}
for year in sbow['positive']:
scores[year] = 0
scores[year] += sum(sbow['positive'][year]) / len(sbow['positive'][year])
for year in sbow['superfluous']:
scores[year] += sum(sbow['superfluous'][year]) / len(sbow['superfluous'][year])
for year in sbow['interesting']:
scores[year] += sum(sbow['interesting'][year]) / len(sbow['interesting'][year])
for year in sbow['negative']:
scores[year] -= sum(sbow['negative'][year]) / len(sbow['negative'][year])
for year in sbow['litigious']:
scores[year] -= sum(sbow['litigious'][year]) / len(sbow['litigious'][year])
for year in sbow['uncertainty']:
scores[year] -= sum(sbow['uncertainty'][year]) / len(sbow['uncertainty'][year])
for year in sbow['constraining']:
scores[year] -= sum(sbow['constraining'][year]) / len(sbow['constraining'][year])
for item in scores:
scores[item] = math.tanh(scores[item])
return dict(sorted(scores.items()))
def plot_sentiment_scores(ticker, scores):
m = min(scores.keys())
M = max(scores.keys())
df = yf.download(ticker, start = f'20{m}-01-01', end = f'20{M}-03-01', interval = '3mo')
df.to_csv(f'price_time_series/{ticker}.csv')
df = pd.read_csv(f'price_time_series/{ticker}.csv')
price = {}
for year in scores.keys():
price[year] = 0
for index, row in df.iterrows():
if row['Date'][2:4] == year and row['High'] > price[year]:
price[year] = row['High']
try:
price.pop('99')
scores.pop('99')
except:
pass
figure, (ax1, ax2) = plt.subplots(2)#, sharex = True
ax1.plot(price.keys(), price.values())
ax1.set(title = f'{ticker}', xlabel = 'years', ylabel = 'stock price')
ax2.plot(scores.keys(), scores.values())
ax2.set(xlabel = 'years', ylabel = 'sentiment score')
#plt.savefig('sample', dpi=300)
plt.show()
def similarity_test(input_filename, ticker):
sentiments = pd.read_csv('supporting_data/sentiment_dataframe.csv')
with open(input_filename, 'r') as f:
tokens = json.loads(f.read())
documents = reformat_documents(ticker, tokens)
sbow = sentiment_bag_of_words(documents, sentiments)
similarities = jaccard_similarity(sbow)
with open('supporting_data/jaccard_similarities.json', 'w') as f:
json.dump(similarities, f)
stfidf = sentiment_tfidf(documents, sentiments)
similarities = cosine_similarity(stfidf)
with open('supporting_data/cosine_similarities.json', 'w') as f:
json.dump(similarities, f)
def create_sentiment_dataframe():
df = pd.read_csv('supporting_data/LoughranMcDonald_MasterDictionary_2018.csv')
# Set column names and words to lower case
df.columns = df.columns.str.lower()
df['word'] = [str(word).lower() for word in df['word']]
# Select sentiment word and word columns
sentiment_words = list(df.columns[7:14])
df = df[['word'] + sentiment_words]
# Remove words with 0 occurences
df[sentiment_words] = df[sentiment_words].astype(bool)
df = df[(df[sentiment_words]).any(1)]
# Stem words and remove duplicates
wnl = WordNetLemmatizer()
#df['word'] = WordNetLemmatizer().lemmatize(df['word'])
df['word'] = [wnl.lemmatize(str(word)) for word in df['word']]
df = df.drop_duplicates('word')
return df
def reformat_documents(ticker, tokens):
documents = {}
for year in tokens[ticker]:
documents[year] = ' '.join([item for sublist in tokens[ticker][year] for item in sublist])
return documents
# Analysis
def sentiment_bag_of_words(documents, sentiments):
sentiment_words = list(sentiments.columns[2:9])
sbow = {}
for word in sentiment_words:
sbow[word] = {}
vectorizer = CountVectorizer(vocabulary = sentiments[sentiments[word]]['word'],
analyzer = 'word',
lowercase = False,
dtype = np.int8)
model = vectorizer.fit(documents.values())
for year in documents.keys():
sbow[word][year] = model.transform([documents[year]]).toarray()[0]
return sbow
def sentiment_tfidf(documents, sentiments):
sentiment_words = list(sentiments.columns[2:9])
stfidf = {}
for word in sentiment_words:
stfidf[word] = {}
vectorizer = TfidfVectorizer(vocabulary = sentiments[sentiments[word]]['word'],
analyzer = 'word',
lowercase = False,
dtype = np.int8)
model = vectorizer.fit(documents.values())
for year in documents.keys():
stfidf[word][year] = vectorizer.transform([documents[year]]).toarray()[0]
return stfidf
def jaccard_similarity(sbow):
similarities = {}
for word in sbow:
similarities[word] = {}
years = sorted(sbow[word].keys())
for i in range(len(years)-1):
x = sbow[word][years[i]].astype(bool)
y = sbow[word][years[i + 1]].astype(bool)
similarities[word][years[i]] = jaccard_score(x, y)
return similarities
def cosine_similarity(stfidf):
similarities = {}
for word in stfidf:
similarities[word] = {}
years = sorted(stfidf[word].keys())
for i in range(len(years)-1):
x = stfidf[word][years[i]].reshape(1, -1)
y = stfidf[word][years[i+1]].reshape(1, -1)
sim = cs(x, y)[0,0]
similarities[word][years[i]] = cs(x, y)[0,0]
return similarities
if __name__ == '__main__':
main()