-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstockdata.py
More file actions
267 lines (239 loc) · 9.8 KB
/
stockdata.py
File metadata and controls
267 lines (239 loc) · 9.8 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
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
263
264
265
266
267
'''
Created on 12 Feb 2020
@author: manojc
'''
from datetime import datetime
import numpy as np
import pandas as pd
import readtickers as rd
from abc import ABC, abstractmethod
from readtickers import TickerData
report_types = [ 'mktVolvsDailyVol10DayPercent',
'fiftyDayAverageChangePercent',
'twoHundredDayAverageChangePercent',
'dividendDate',
'trailingAnnualDividendRate',
'trailingPE',
'bookValue',
'priceToBook',
'askBookValueRatio',
'Ask_52WLow',
'Bid_52WHigh',
'regularMarketChangePercent' ]
class Data(ABC):
@abstractmethod
def create_data_frame(self): pass
class StockData(Data):
'''
This class holds stock information that we want to capture, pass and distribute for manipulation
'''
def __init__(self, outputDir):
'''
Constructor
'''
self.ticker_info = []
self.data = pd.DataFrame
self.tickerData = TickerData([], "")
self.strDateTimeValue = datetime.now().strftime("%Y%m%d_%H%M%S")
self.fileSuffix = self.strDateTimeValue +".csv"
self.outputDir = outputDir
self.weights = {}
def __call__(self):
print("Called StockData()")
def load_tickers_from_file(self, customFile, label):
self.tickerData.from_filename(customFile, label)
def load_tickers_from_exch_list(self, exchanges):
if len(exchanges) != 0:
if ("ALL" in exchanges):
for index in rd.indices:
self.tickerData.from_index(index)
else:
for index in exchanges:
self.tickerData.from_index(index)
def create_data_frame(self):
myData = self.tickerData.get_ticker_data()
print(myData)
self.data = pd.DataFrame.from_dict(myData)
self.data.pop('language')
self.data.pop('region')
self.data.pop('triggerable')
def rearrange_df_cols(self):
cols = list(self.data)
i = 0
cols.insert(i, cols.pop(cols.index('symbol')))
i += 1
cols.insert(i, cols.pop(cols.index('category')))
i += 1
#cols.insert(i, cols.pop(cols.index('industry')))
#i += 1
cols.insert(i, cols.pop(cols.index('longName')))
i += 1
cols.insert(i, cols.pop(cols.index('shortName')))
i += 1
cols.insert(i, cols.pop(cols.index('marketCap')))
i += 1
cols.insert(i, cols.pop(cols.index('currency')))
i += 1
cols.insert(i, cols.pop(cols.index('regularMarketChangePercent')))
i += 1
cols.insert(i, cols.pop(cols.index('regularMarketChange')))
i += 1
cols.insert(i, cols.pop(cols.index('regularMarketPreviousClose')))
i += 1
cols.insert(i, cols.pop(cols.index('ask')))
i += 1
cols.insert(i, cols.pop(cols.index('bid')))
i += 1
cols.insert(i, cols.pop(cols.index('fiftyTwoWeekLow')))
i += 1
cols.insert(i, cols.pop(cols.index('fiftyTwoWeekHigh')))
i += 1
cols.insert(i, cols.pop(cols.index('regularMarketDayRange')))
i += 1
cols.insert(i, cols.pop(cols.index('askSize')))
i += 1
cols.insert(i, cols.pop(cols.index('bidSize')))
i += 1
cols.insert(i, cols.pop(cols.index('regularMarketPrice')))
i += 1
cols.insert(i, cols.pop(cols.index('regularMarketTime')))
i += 1
cols.insert(i, cols.pop(cols.index('regularMarketOpen')))
i += 1
cols.insert(i, cols.pop(cols.index('regularMarketDayHigh')))
i += 1
cols.insert(i, cols.pop(cols.index('regularMarketDayLow')))
i += 1
cols.insert(i, cols.pop(cols.index('mktVolvsDailyVol10DayPercent')))
i += 1
cols.insert(i, cols.pop(cols.index('mktVolvsDailyVol3MPercent')))
i += 1
cols.insert(i, cols.pop(cols.index('regularMarketVolume')))
i += 1
cols.insert(i, cols.pop(cols.index('averageDailyVolume10Day')))
i += 1
cols.insert(i, cols.pop(cols.index('averageDailyVolume3Month')))
i += 1
cols.insert(i, cols.pop(cols.index('fiftyDayAverageChangePercent')))
i += 1
cols.insert(i, cols.pop(cols.index('fiftyDayAverageChange')))
i += 1
cols.insert(i, cols.pop(cols.index('fiftyDayAverage')))
i += 1
cols.insert(i, cols.pop(cols.index('twoHundredDayAverageChangePercent')))
i += 1
cols.insert(i, cols.pop(cols.index('twoHundredDayAverageChange')))
i += 1
cols.insert(i, cols.pop(cols.index('twoHundredDayAverage')))
i += 1
cols.insert(i, cols.pop(cols.index('fiftyTwoWeekLowChange')))
i += 1
cols.insert(i, cols.pop(cols.index('fiftyTwoWeekLowChangePercent')))
i += 1
cols.insert(i, cols.pop(cols.index('fiftyTwoWeekRange')))
i += 1
cols.insert(i, cols.pop(cols.index('fiftyTwoWeekHighChange')))
i += 1
cols.insert(i, cols.pop(cols.index('fiftyTwoWeekHighChangePercent')))
i += 1
cols.insert(i, cols.pop(cols.index('dividendDate')) if "dividendDate" in cols else "" )
i += 1
cols.insert(i, cols.pop(cols.index('earningsTimestamp')))
i += 1
cols.insert(i, cols.pop(cols.index('earningsTimestampStart')))
i += 1
cols.insert(i, cols.pop(cols.index('earningsTimestampEnd')))
i += 1
cols.insert(i, cols.pop(cols.index('trailingAnnualDividendRate')))
i += 1
cols.insert(i, cols.pop(cols.index('trailingPE')))
i += 1
cols.insert(i, cols.pop(cols.index('forwardPE')))
i += 1
cols.insert(i, cols.pop(cols.index('trailingAnnualDividendYield')))
i += 1
cols.insert(i, cols.pop(cols.index('epsTrailingTwelveMonths')))
i += 1
cols.insert(i, cols.pop(cols.index('epsForward')))
i += 1
cols.insert(i, cols.pop(cols.index('sharesOutstanding')))
i += 1
cols.insert(i, cols.pop(cols.index('bookValue')))
i += 1
cols.insert(i, cols.pop(cols.index('forwardPE')))
i += 1
cols.insert(i, cols.pop(cols.index('priceToBook')))
i += 1
cols.insert(i, cols.pop(cols.index('askBookValueRatio')))
i += 1
cols.insert(i, cols.pop(cols.index('Ask_52WLow')))
i += 1
cols.insert(i, cols.pop(cols.index('Bid_52WHigh')))
i += 1
cols.insert(i, cols.pop(cols.index('quoteType')))
i += 1
cols.insert(i, cols.pop(cols.index('quoteSourceName')) if "quoteSourceName" in cols else "" )
i += 1
cols.insert(i, cols.pop(cols.index('financialCurrency')))
i += 1
cols.insert(i, cols.pop(cols.index('marketState')))
#Moved WT_Total to end of list if exists
cols.insert(len(self.data.columns), cols.pop(cols.index('WT_Total')) if "WT_Total" in cols else "" )
self.data = self.data.reindex(columns=cols)
self.data = self.data.drop_duplicates(subset='symbol', keep='first')
def __output(self, filename):
if len(self.outputDir) > 0:
filename = self.outputDir + '/' + filename
print(f'FILENAME TO OUTPUT {filename}')
self.data.to_csv(filename, index=None, header=True)
def rowIndex(self, row):
return row.name
def generate_weights(self, dictWeightCols, listTotalWeightCols, sortColumn):
#if sortColumn is blank then sort by the total aggregated weight column WT_Total
df_len = len(self.data)
firstKey = True
for key in dictWeightCols:
if len(key) > 0 and key in self.data.columns:
self.data = self.data.sort_values(by=key,ascending=dictWeightCols[key])
weights = []
for i in range(df_len):
weights.append((df_len - i)/df_len)
if len(key) > 0:
self.data[f'WT_{key}'] = weights
if key in listTotalWeightCols:
if firstKey == True:
self.data['WT_Total'] = self.data[f'WT_{key}']
firstKey = False
else:
self.data['WT_Total'] *= self.data[f'WT_{key}']
if len(sortColumn) > 0:
if sortColumn in self.data:
self.data = self.data.sort_values(by=sortColumn,ascending=False)
else:
if 'WT_Total' in self.data.columns:
self.data = self.data.sort_values(by='WT_Total',ascending=False)
else:
print(f'Could not find {sortColumn}')
def gen_report(self, prefix):
strFilename = f'{prefix}_{self.fileSuffix}'
self.rearrange_df_cols()
self.__output(strFilename)
def generate_report(self, prefix, sortField, ascending, lastReport):
if len(sortField) > 0 and sortField in self.data.columns:
self.data = self.data.sort_values(by=sortField,ascending=ascending)
iWeight = []
df_len = len(self.data)
for i in range(len(self.data)):
iWeight.append((df_len-i)/df_len)
if len(sortField) > 0:
self.data[f'WT_{sortField}'] = iWeight
if lastReport == True:
self.data['WT_Total'] = self.data['WT_trailingAnnualDividendRate'] * \
self.data['WT_trailingPE'] * \
self.data['WT_bookValue'] * \
self.data['WT_priceToBook'] * \
self.data['WT_askBookValueRatio'] * \
self.data['WT_Ask_52WLow']
strFilename = f'{prefix}_{self.fileSuffix}'
self.rearrange_df_cols()
self.__output(strFilename)