Matteo Morini commited on
Commit
fc78d2e
·
unverified ·
1 Parent(s): 101e7ba

New datasets

Browse files
Files changed (2) hide show
  1. app.py +10 -163
  2. stock_price.csv +0 -0
app.py CHANGED
@@ -30,131 +30,10 @@ RELEVANCE_QUANTILE = 0.05 # top 5%
30
 
31
 
32
  # load existing data from file (in widget: drag-drop your file?)
33
- df_raw = pd.read_csv('stock_price.csv').iloc[:,1:].T
34
-
35
- df_raw.columns=df_raw.loc['Ticker']
36
- df_raw.drop('Ticker', inplace=True)
37
- df_raw.index.name = 'timestamp'
38
-
39
- df = df_raw
40
-
41
-
42
- # In[3]:
43
-
44
-
45
- MAKE_NEW_DATASET = False
46
-
47
- if MAKE_NEW_DATASET:
48
- # generate fake sector mapping
49
- def make_fake_dataset():
50
-
51
- prods = [
52
- 'Equities',
53
- 'Bonds',
54
- 'ETP',
55
- 'Options'
56
- ]
57
-
58
- sec_list = [
59
- 'Commercial Services',
60
- 'Communications',
61
- 'Consumer Durables',
62
- 'Consumer Non-Durables',
63
- 'Consumer Services',
64
- 'Distribution Services',
65
- 'Electronic Technology',
66
- 'Energy Minerals',
67
- 'Finance',
68
- 'Health Services',
69
- 'Health Technology',
70
- 'Industrial Services',
71
- 'Miscellaneous',
72
- 'Non-Energy Minerals',
73
- 'Process Industries',
74
- 'Producer Manufacturing',
75
- 'Retail Trade',
76
- 'Technology Services',
77
- 'Transportation',
78
- 'Utilities'
79
- ]
80
-
81
- countries_list_raw = [
82
- '1 China 1,439,323,776 0.39 % 5,540,090 153 9,388,211 -348,399 1.7 38 61 % 18.47 %',
83
- '2 India 1,380,004,385 0.99 % 13,586,631 464 2,973,190 -532,687 2.2 28 35 % 17.70 %',
84
- '3 United States 331,002,651 0.59 % 1,937,734 36 9,147,420 954,806 1.8 38 83 % 4.25 %',
85
- '4 Indonesia 273,523,615 1.07 % 2,898,047 151 1,811,570 -98,955 2.3 30 56 % 3.51 %',
86
- '5 Pakistan 220,892,340 2.00 % 4,327,022 287 770,880 -233,379 3.6 23 35 % 2.83 %',
87
- '6 Brazil 212,559,417 0.72 % 1,509,890 25 8,358,140 21,200 1.7 33 88 % 2.73 %',
88
- '7 Nigeria 206,139,589 2.58 % 5,175,990 226 910,770 -60,000 5.4 18 52 % 2.64 %',
89
- '8 Bangladesh 164,689,383 1.01 % 1,643,222 1,265 130,170 -369,501 2.1 28 39 % 2.11 %',
90
- '9 Russia 145,934,462 0.04 % 62,206 9 16,376,870 182,456 1.8 40 74 % 1.87 %',
91
- '10 Mexico 128,932,753 1.06 % 1,357,224 66 1,943,950 -60,000 2.1 29 84 % 1.65 %',
92
- '11 Japan 126,476,461 -0.30 % -383,840 347 364,555 71,560 1.4 48 92 % 1.62 %',
93
- '12 Ethiopia 114,963,588 2.57 % 2,884,858 115 1,000,000 30,000 4.3 19 21 % 1.47 %',
94
- '13 Philippines 109,581,078 1.35 % 1,464,463 368 298,170 -67,152 2.6 26 47 % 1.41 %',
95
- '14 Egypt 102,334,404 1.94 % 1,946,331 103 995,450 -38,033 3.3 25 43 % 1.31 %',
96
- '15 Vietnam 97,338,579 0.91 % 876,473 314 310,070 -80,000 2.1 32 38 % 1.25 %',
97
- '16 DR Congo 89,561,403 3.19 % 2,770,836 40 2,267,050 23,861 6.0 17 46 % 1.15 %',
98
- '17 Turkey 84,339,067 1.09 % 909,452 110 769,630 283,922 2.1 32 76 % 1.08 %',
99
- '18 Iran 83,992,949 1.30 % 1,079,043 52 1,628,550 -55,000 2.2 32 76 % 1.08 %',
100
- '19 Germany 83,783,942 0.32 % 266,897 240 348,560 543,822 1.6 46 76 % 1.07 %',
101
- '20 Thailand 69,799,978 0.25 % 174,396 137 510,890 19,444 1.5 40 51 % 0.90 %',
102
- '21 United Kingdom 67,886,011 0.53 % 355,839 281 241,930 260,650 1.8 40 83 % 0.87 %',
103
- '22 France 65,273,511 0.22 % 143,783 119 547,557 36,527 1.9 42 82 % 0.84 %',
104
- '23 Italy 60,461,826 -0.15 % -88,249 206 294,140 148,943 1.3 47 69 % 0.78 %',
105
- '24 Tanzania 59,734,218 2.98 % 1,728,755 67 885,800 -40,076 4.9 18 37 % 0.77 %',
106
- '25 South Africa 59,308,690 1.28 % 750,420 49 1,213,090 145,405 2.4 28 67 % 0.76 %',
107
- '26 Myanmar 54,409,800 0.67 % 364,380 83 653,290 -163,313 2.2 29 31 % 0.70 %',
108
- '27 Kenya 53,771,296 2.28 % 1,197,323 94 569,140 -10,000 3.5 20 28 % 0.69 %',
109
- '28 South Korea 51,269,185 0.09 % 43,877 527 97,230 11,731 1.1 44 82 % 0.66 %',
110
- '29 Colombia 50,882,891 1.08 % 543,448 46 1,109,500 204,796 1.8 31 80 % 0.65 %',
111
- '30 Spain 46,754,778 0.04 % 18,002 94 498,800 40,000 1.3 45 80 % 0.60 %'
112
- ]
113
-
114
- countries_list = [c.split('\t')[1].strip(' ') for c in countries_list_raw]
115
- countries_list
116
-
117
- symbols_names = pd.read_csv('symbols_names.csv', sep=',')
118
-
119
- tickers = df.columns
120
- tickers_kwds = pd.DataFrame.from_dict(
121
- {k:' '.join(
122
- [random.choice(countries_list),random.choice(sec_list),random.choice(prods)]
123
- ) for k in tickers},
124
- orient='index'
125
- ).rename(columns={0: 'rndkeywords'})
126
-
127
- tickers_desc_names = tickers_kwds.merge(
128
- symbols_names,
129
- left_index=True,
130
- right_on='Symbol',
131
- how='left'
132
- ).fillna('')
133
-
134
- tickers_desc_names['keywords'] = tickers_desc_names['Name']+' '+tickers_desc_names['rndkeywords']
135
-
136
- tickers_desc = tickers_desc_names.set_index('Symbol').drop(columns=['rndkeywords','Name'])
137
- return(tickers_desc)
138
-
139
- tickers_desc = make_fake_dataset()
140
-
141
- tickers_desc.to_parquet('tickers_desc.parquet')
142
-
143
-
144
- # In[4]:
145
-
146
-
147
- tickers_desc = pd.read_parquet('tickers_desc.parquet')
148
-
149
-
150
- # In[5]:
151
-
152
-
153
- tickers_desc
154
-
155
-
156
- # In[6]:
157
 
 
 
158
 
159
  filter_string = 'germany automotive'
160
 
@@ -168,22 +47,6 @@ relevant_threshold = np.quantile(tickers_desc['relevance'], 1.0-RELEVANCE_QUANTI
168
  filtered_columns = tickers_desc[tickers_desc.relevance >= relevant_threshold].sort_values(by='relevance', ascending=False)
169
  filtered_columns
170
 
171
-
172
- # In[7]:
173
-
174
-
175
- #filtered_columns['relevance'].plot.kde()
176
-
177
-
178
- # In[8]:
179
-
180
-
181
- len(filtered_columns)
182
-
183
-
184
- # In[9]:
185
-
186
-
187
  # test values
188
  CORR_THRESHOLD = .875
189
  cutoff = .5
@@ -200,18 +63,11 @@ print(
200
  f"Cutoff date is {split_date} between {min(df.index)} and {max(df.index)}."
201
  )
202
 
203
-
204
- # In[10]:
205
-
206
-
207
  lookup_space = pd.DataFrame(list(combinations(filtered_columns.index, 2))[0:LOOKUP_SPACE_LIM])
208
  lookup_space
209
 
210
 
211
- # In[11]:
212
-
213
-
214
- CORR_THRESHOLD = .85
215
  # def check_anom(c1, c2): <<< then do multidimensional LOF
216
  def check_anom(c1, c2):
217
  stat_1, pval_1 = pearsonr(df_1[c1], df_1[c2])
@@ -228,19 +84,12 @@ res = lookup_space.parallel_apply(
228
  axis=1
229
  ).dropna()
230
 
231
-
232
- # In[12]:
233
-
234
-
235
  if res.shape[0]==0:
236
  print("No anomalies detected in selected data.")
237
  else:
238
  print(f"{res.shape[0]} anomalies detected in selected data.")
239
 
240
 
241
- # In[13]:
242
-
243
-
244
  for i, ((c1, c2),(r1,r2)) in res.head(5).items():
245
  print(f"Pair {c1},{c2}: {r1} {r2}")
246
 
@@ -317,10 +166,6 @@ col_1, col_2 = outlier_values.columns[0:2]
317
  plt.scatter(df_test[col_1], df_test[col_2], color = "b", s = 65)# plot outlier values
318
  plt.scatter(outlier_values[col_1], outlier_values[col_2], color = "r")
319
 
320
-
321
- # In[21]:
322
-
323
-
324
  # gradio launch
325
 
326
  def check_anom(c1, c2):
@@ -428,16 +273,18 @@ demo = gr.Interface(
428
  gr.Slider(0, 1, step=0.1, label='Cutoff point (0-1)', value=0.5)
429
  ],
430
  outputs=[
431
- gr.DataFrame(label="Top matching tickers, sorted by descending relevance [FOR DEMO PURPOSES ONLY]"),
 
 
432
  gr.Textbox(label="Matching tickers count (search space size)"),
433
  gr.Textbox(label="Anomaly detection outcome"),
434
  gr.Image(label="Anomaly plot"),
435
  gr.Textbox(label="Diagnostics")
436
  ],
437
  examples=[
438
- ['germany automotive', 5, 0.85, 0.6],
439
- ['nigeria energy', 15, 0.875, 0.5],
440
- ['vietnam transportation', 10, 0.800, 0.75]
441
  ],
442
  allow_flagging='never',
443
  #show_api=False
 
30
 
31
 
32
  # load existing data from file (in widget: drag-drop your file?)
33
+ df = pd.read_parquet('stock_price.parquet').interpolate(method='linear', axis=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ tickers_desc_all = pd.read_parquet('tickers_desc.parquet')
36
+ tickers_desc = tickers_desc_all.loc[df.columns]
37
 
38
  filter_string = 'germany automotive'
39
 
 
47
  filtered_columns = tickers_desc[tickers_desc.relevance >= relevant_threshold].sort_values(by='relevance', ascending=False)
48
  filtered_columns
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  # test values
51
  CORR_THRESHOLD = .875
52
  cutoff = .5
 
63
  f"Cutoff date is {split_date} between {min(df.index)} and {max(df.index)}."
64
  )
65
 
 
 
 
 
66
  lookup_space = pd.DataFrame(list(combinations(filtered_columns.index, 2))[0:LOOKUP_SPACE_LIM])
67
  lookup_space
68
 
69
 
70
+ CORR_THRESHOLD = .80
 
 
 
71
  # def check_anom(c1, c2): <<< then do multidimensional LOF
72
  def check_anom(c1, c2):
73
  stat_1, pval_1 = pearsonr(df_1[c1], df_1[c2])
 
84
  axis=1
85
  ).dropna()
86
 
 
 
 
 
87
  if res.shape[0]==0:
88
  print("No anomalies detected in selected data.")
89
  else:
90
  print(f"{res.shape[0]} anomalies detected in selected data.")
91
 
92
 
 
 
 
93
  for i, ((c1, c2),(r1,r2)) in res.head(5).items():
94
  print(f"Pair {c1},{c2}: {r1} {r2}")
95
 
 
166
  plt.scatter(df_test[col_1], df_test[col_2], color = "b", s = 65)# plot outlier values
167
  plt.scatter(outlier_values[col_1], outlier_values[col_2], color = "r")
168
 
 
 
 
 
169
  # gradio launch
170
 
171
  def check_anom(c1, c2):
 
273
  gr.Slider(0, 1, step=0.1, label='Cutoff point (0-1)', value=0.5)
274
  ],
275
  outputs=[
276
+ gr.DataFrame(label="Top matching tickers, sorted by descending relevance [FOR DEMO PURPOSES ONLY]",
277
+ headers=['symbol', 'keywords', 'relevance']
278
+ ),
279
  gr.Textbox(label="Matching tickers count (search space size)"),
280
  gr.Textbox(label="Anomaly detection outcome"),
281
  gr.Image(label="Anomaly plot"),
282
  gr.Textbox(label="Diagnostics")
283
  ],
284
  examples=[
285
+ ['germany biotech', 5, 0.85, 0.6],
286
+ ['ireland financial services', 15, 0.875, 0.5],
287
+ ['oil gas energy', 10, 0.800, 0.75]
288
  ],
289
  allow_flagging='never',
290
  #show_api=False
stock_price.csv DELETED
The diff for this file is too large to render. See raw diff