Matteo Morini commited on
Introducing LOF
Browse files- app.py +58 -40
- engines/corrinv.py +157 -0
- engines/lof.py +125 -0
- experimental/make_verbose.py +27 -0
- filters/filter_features.py +40 -0
- pipeline.py +23 -170
app.py
CHANGED
|
@@ -1,80 +1,98 @@
|
|
| 1 |
#!/usr/bin/env python
|
| 2 |
# coding: utf-8
|
| 3 |
|
| 4 |
-
# In[1]:
|
| 5 |
-
|
| 6 |
import pandas as pd
|
| 7 |
|
| 8 |
import random
|
| 9 |
|
| 10 |
-
# import Levenshtein
|
| 11 |
-
import textdistance
|
| 12 |
-
|
| 13 |
from IPython.display import display
|
|
|
|
| 14 |
# import ipywidgets as widgets
|
| 15 |
|
| 16 |
import gradio as gr
|
| 17 |
|
| 18 |
-
|
| 19 |
|
| 20 |
from dotenv import load_dotenv
|
|
|
|
| 21 |
load_dotenv()
|
| 22 |
|
| 23 |
art_descr = (
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
# load existing data from file (in widget: drag-drop your file?)
|
| 35 |
-
df = pd.read_parquet(
|
| 36 |
|
| 37 |
-
tickers_desc_all = pd.read_parquet(
|
| 38 |
tickers_desc_prefilter = tickers_desc_all.loc[df.columns]
|
| 39 |
|
| 40 |
-
sectors = list(tickers_desc_prefilter[
|
|
|
|
| 41 |
|
| 42 |
demo = gr.Interface(
|
| 43 |
css=".gradio-container {background-color: white}",
|
| 44 |
-
title=
|
| 45 |
description=art_descr,
|
| 46 |
-
fn=pipeline
|
| 47 |
-
inputs
|
| 48 |
-
gr.Textbox(lines=1, label=
|
| 49 |
-
gr.Checkbox(label=
|
| 50 |
-
gr.Dropdown(sectors),
|
| 51 |
-
gr.
|
| 52 |
-
gr.Slider(0,
|
| 53 |
-
gr.Slider(0, 1, step=0.
|
| 54 |
-
gr.
|
|
|
|
|
|
|
|
|
|
| 55 |
],
|
| 56 |
outputs=[
|
| 57 |
-
gr.DataFrame(
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
gr.Textbox(label="Matching tickers count (search space size)"),
|
| 61 |
gr.Textbox(label="Anomaly detection outcome"),
|
| 62 |
gr.Image(label="Anomaly plot"),
|
| 63 |
-
gr.Textbox(label="Human-readable description (EXPERIMENTAL)")
|
| 64 |
],
|
| 65 |
examples=[
|
| 66 |
-
[
|
| 67 |
-
[
|
| 68 |
-
[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
],
|
| 70 |
-
allow_flagging=
|
| 71 |
cache_examples=False,
|
| 72 |
-
#show_api=False
|
| 73 |
)
|
| 74 |
|
| 75 |
if __name__ == "__main__":
|
| 76 |
|
| 77 |
demo.launch()
|
| 78 |
-
#demo.launch(auth_message="Contact matteo@batonics.com to get access.")
|
| 79 |
-
#demo.launch(auth=("batonics", "batonicsdemo22"))
|
| 80 |
-
#demo.launch(share=True, auth=("batonics", "batonicsdemo22"))
|
|
|
|
| 1 |
#!/usr/bin/env python
|
| 2 |
# coding: utf-8
|
| 3 |
|
|
|
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
|
| 6 |
import random
|
| 7 |
|
|
|
|
|
|
|
|
|
|
| 8 |
from IPython.display import display
|
| 9 |
+
|
| 10 |
# import ipywidgets as widgets
|
| 11 |
|
| 12 |
import gradio as gr
|
| 13 |
|
| 14 |
+
from pipeline import getEngine
|
| 15 |
|
| 16 |
from dotenv import load_dotenv
|
| 17 |
+
|
| 18 |
load_dotenv()
|
| 19 |
|
| 20 |
art_descr = (
|
| 21 |
+
"<b>Input Fields:</b>"
|
| 22 |
+
"<ul>"
|
| 23 |
+
"<li>Keywords search: <i>Use industrial, geographical, asset class descriptors.</i></li>"
|
| 24 |
+
"<li>Sectors picker: <i>If populated, strictly stick to selected sector.</i></li>"
|
| 25 |
+
"<li>Detection engine: <i>Choose anomaly detection strategy.</i></li>"
|
| 26 |
+
"<p style=\"margin-left: 40px\">corrinv: <i>correlation inversion</i></p>"
|
| 27 |
+
"<p style=\"margin-left: 40px\">lof: <i>local outlier factor</i></p>"
|
| 28 |
+
"<li>Relevance threshold: <i>Select top <b>x%</b> matched symbols (irrelevant if using exact match).</i></li>"
|
| 29 |
+
"<li>Correlation threshold: <i>Restrict analysis to correlations at least <b>x</b> strong.</i></li>"
|
| 30 |
+
"<li>Cutoff point: <i>Select where to split the time series (before/after).</i></li>"
|
| 31 |
+
"</ul>"
|
| 32 |
+
)
|
| 33 |
|
| 34 |
# load existing data from file (in widget: drag-drop your file?)
|
| 35 |
+
df = pd.read_parquet("stock_price.parquet").interpolate(method="linear", axis=1)
|
| 36 |
|
| 37 |
+
tickers_desc_all = pd.read_parquet("tickers_desc_act.parquet")
|
| 38 |
tickers_desc_prefilter = tickers_desc_all.loc[df.columns]
|
| 39 |
|
| 40 |
+
sectors = list(tickers_desc_prefilter["sector"].unique()[0:10])
|
| 41 |
+
engines = ["corrinv", "lof"]
|
| 42 |
|
| 43 |
demo = gr.Interface(
|
| 44 |
css=".gradio-container {background-color: white}",
|
| 45 |
+
title="Batonics AB | Anomalous events detection pipeline",
|
| 46 |
description=art_descr,
|
| 47 |
+
fn=getEngine, # pick pipeline, use chosen engine
|
| 48 |
+
inputs=[
|
| 49 |
+
gr.Textbox(lines=1, label="Keywords search", placeholder="Keywords Here..."),
|
| 50 |
+
gr.Checkbox(label="Exact match", value=False),
|
| 51 |
+
gr.Dropdown(sectors, label="Sectors picker"),
|
| 52 |
+
gr.Dropdown(engines, label="Detection engine"),
|
| 53 |
+
gr.Slider(0, 100, label="Relevance threshold (percentile)", value=15),
|
| 54 |
+
gr.Slider(0, 1, step=0.01, label="Correlation threshold (0-1)", value=0.875),
|
| 55 |
+
gr.Slider(0, 1, step=0.1, label="Cutoff point (0-1)", value=0.5),
|
| 56 |
+
gr.Checkbox(
|
| 57 |
+
label="Generate natural language outcome (EXPERIMENTAL)", value=False
|
| 58 |
+
),
|
| 59 |
],
|
| 60 |
outputs=[
|
| 61 |
+
gr.DataFrame(
|
| 62 |
+
label=(
|
| 63 |
+
"Top matching tickers, sorted by descending relevance [FOR DEMO"
|
| 64 |
+
" PURPOSES ONLY]"
|
| 65 |
+
),
|
| 66 |
+
headers=["symbol", "keywords", "relevance", "industry"],
|
| 67 |
+
),
|
| 68 |
gr.Textbox(label="Matching tickers count (search space size)"),
|
| 69 |
gr.Textbox(label="Anomaly detection outcome"),
|
| 70 |
gr.Image(label="Anomaly plot"),
|
| 71 |
+
gr.Textbox(label="Human-readable description (EXPERIMENTAL)"),
|
| 72 |
],
|
| 73 |
examples=[
|
| 74 |
+
["oil gas", False, "Energy", "corrinv", 85, 0.800, 0.6, True],
|
| 75 |
+
["germany biotech", False, "Healthcare", "corrinv", 20, 0.85, 0.6, False],
|
| 76 |
+
[
|
| 77 |
+
"ireland financial services",
|
| 78 |
+
False,
|
| 79 |
+
"Financial Services",
|
| 80 |
+
"corrinv",
|
| 81 |
+
15,
|
| 82 |
+
0.875,
|
| 83 |
+
0.5,
|
| 84 |
+
False,
|
| 85 |
+
],
|
| 86 |
+
["semiconductors", False, "Technology", "lof", 1, 0.875, 0.5, False],
|
| 87 |
],
|
| 88 |
+
allow_flagging="never",
|
| 89 |
cache_examples=False,
|
| 90 |
+
# show_api=False
|
| 91 |
)
|
| 92 |
|
| 93 |
if __name__ == "__main__":
|
| 94 |
|
| 95 |
demo.launch()
|
| 96 |
+
# demo.launch(auth_message="Contact matteo@batonics.com to get access.")
|
| 97 |
+
# demo.launch(auth=("batonics", "batonicsdemo22"))
|
| 98 |
+
# demo.launch(share=True, auth=("batonics", "batonicsdemo22"))
|
engines/corrinv.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
from pandarallel import pandarallel
|
| 5 |
+
|
| 6 |
+
from itertools import combinations
|
| 7 |
+
from scipy.stats import pearsonr
|
| 8 |
+
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
| 11 |
+
|
| 12 |
+
from filters.filter_features import filterFeatures
|
| 13 |
+
from experimental.make_verbose import makeVerbose
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def check_anom(c1, c2, df_1, df_2, CORR_THRESHOLD):
|
| 17 |
+
|
| 18 |
+
stat_1, pval_1 = pearsonr(df_1[c1], df_1[c2])
|
| 19 |
+
stat_2, pval_2 = pearsonr(df_2[c1], df_2[c2])
|
| 20 |
+
|
| 21 |
+
if ((stat_1 > CORR_THRESHOLD) & (stat_2 < -CORR_THRESHOLD)) | (
|
| 22 |
+
(stat_1 < -CORR_THRESHOLD) & (stat_2 > CORR_THRESHOLD)
|
| 23 |
+
):
|
| 24 |
+
print(c1, c2, stat_1, pval_1, stat_2, pval_2)
|
| 25 |
+
return [(c1, c2), (stat_1, stat_2)]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def corrinv(
|
| 29 |
+
filter_string,
|
| 30 |
+
exact_match,
|
| 31 |
+
sector,
|
| 32 |
+
RELEVANCE_QUANTILE_100s,
|
| 33 |
+
CORR_THRESHOLD,
|
| 34 |
+
cutoff,
|
| 35 |
+
NLgen,
|
| 36 |
+
):
|
| 37 |
+
|
| 38 |
+
LOOKUP_SPACE_LIM = 50_000 # keep size sane
|
| 39 |
+
|
| 40 |
+
# ugly duplication, TOFIX
|
| 41 |
+
df = pd.read_parquet("stock_price.parquet").interpolate(method="linear", axis=1)
|
| 42 |
+
|
| 43 |
+
_log = []
|
| 44 |
+
RELEVANCE_QUANTILE = RELEVANCE_QUANTILE_100s * 0.01
|
| 45 |
+
|
| 46 |
+
filtered_columns, tickers_desc = filterFeatures(
|
| 47 |
+
df, sector, RELEVANCE_QUANTILE, filter_string, exact_match
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
top_filtered_columns = (
|
| 51 |
+
filtered_columns[["keywords", "relevance", "industry"]].iloc[0:10].reset_index()
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# limit max search space size
|
| 55 |
+
lookup_space = pd.DataFrame(
|
| 56 |
+
list(combinations(filtered_columns.index, 2))[0:LOOKUP_SPACE_LIM]
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# split
|
| 60 |
+
split_point = int(len(df) * cutoff)
|
| 61 |
+
|
| 62 |
+
df_1 = df.iloc[
|
| 63 |
+
:split_point,
|
| 64 |
+
]
|
| 65 |
+
df_2 = df.iloc[
|
| 66 |
+
split_point:,
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
split_date = df.iloc[split_point].name
|
| 70 |
+
|
| 71 |
+
_cutoff, _nobs1, _nobs2 = f"{cutoff}", f"{df_1.shape[0]}", f"{df_2.shape[0]}"
|
| 72 |
+
|
| 73 |
+
(_cutoffdate, _dmin, _dmax) = (
|
| 74 |
+
f"{split_date.strftime('%B %d, %Y')}",
|
| 75 |
+
f"{min(df.index).strftime('%B %d, %Y')}",
|
| 76 |
+
f"{max(df.index).strftime('%B %d, %Y')}",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
pandarallel.initialize(progress_bar=False, nb_workers=8)
|
| 80 |
+
|
| 81 |
+
res = lookup_space.apply( # debugging
|
| 82 |
+
# res = lookup_space.parallel_apply(
|
| 83 |
+
lambda r: check_anom(r[0], r[1], df_1, df_2, CORR_THRESHOLD),
|
| 84 |
+
axis=1,
|
| 85 |
+
).dropna()
|
| 86 |
+
|
| 87 |
+
if res.shape[0] == 0:
|
| 88 |
+
ret_string_anom = "No anomalies detected in selected data."
|
| 89 |
+
|
| 90 |
+
return (
|
| 91 |
+
top_filtered_columns,
|
| 92 |
+
(
|
| 93 |
+
f"{filtered_columns.shape[0]} ({filtered_columns.shape[0]*(filtered_columns.shape[0]-1)})"
|
| 94 |
+
),
|
| 95 |
+
ret_string_anom,
|
| 96 |
+
None,
|
| 97 |
+
"Not much to say; try and relax the detection constraints.",
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
else:
|
| 101 |
+
ret_string_anom = (
|
| 102 |
+
f"{res.shape[0]} anomalies detected in selected data (showing up to 5):\n\n"
|
| 103 |
+
+ "\n".join(
|
| 104 |
+
[
|
| 105 |
+
f"{r[0][0]}({tickers_desc.loc[r[0][0]]['keywords']}) |"
|
| 106 |
+
f" {r[0][1]} ({tickers_desc.loc[r[0][1]]['keywords']}):\n{r[1][0]:.2f} |"
|
| 107 |
+
f" {r[1][1]:.2f}\n"
|
| 108 |
+
for i, r in res.iloc[0:5].items()
|
| 109 |
+
]
|
| 110 |
+
)
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
for i, ((c1, c2), (r1, r2)) in res.head(1).items():
|
| 114 |
+
|
| 115 |
+
_tk1, _tk1desc = f"{c1}", f"{tickers_desc.loc[c1]['keywords']}"
|
| 116 |
+
_tk2, _tk2desc = f"{c2}", f"{tickers_desc.loc[c2]['keywords']}"
|
| 117 |
+
_r1, _r2 = f"{r1:.2f}", f"{r2:.2f}"
|
| 118 |
+
|
| 119 |
+
fig, ax = plt.subplots(figsize=(18, 6))
|
| 120 |
+
ax.tick_params(labelrotation=90)
|
| 121 |
+
ax_r = ax.twinx()
|
| 122 |
+
ax.plot(df[c1], c="r", label=c1)
|
| 123 |
+
ax_r.plot(df[c2], c="g", label=c2)
|
| 124 |
+
ax.axvline(split_date)
|
| 125 |
+
plt.title(f"{c1}|{c2}:{r1:.2g},{r2:.2g}")
|
| 126 |
+
ax.legend(loc="upper left")
|
| 127 |
+
ax_r.legend(loc="upper right")
|
| 128 |
+
fig.tight_layout(pad=0)
|
| 129 |
+
|
| 130 |
+
canvas = FigureCanvasAgg(fig)
|
| 131 |
+
canvas.draw()
|
| 132 |
+
s, (width, height) = canvas.print_to_buffer()
|
| 133 |
+
image_from_plot = np.frombuffer(s, np.uint8).reshape((height, width, 4))
|
| 134 |
+
|
| 135 |
+
_log = (
|
| 136 |
+
f"The relevant symbols are {_tk1} ({_tk1desc}) and {_tk2} ({_tk2desc})."
|
| 137 |
+
f" The correlation coefficient for the symbols pair {_tk1} and"
|
| 138 |
+
f" {_tk2} is initially {_r1} and inverts to {_r2} after cutoff date,"
|
| 139 |
+
f" which is {_cutoffdate}; by the way, the dataset is defined between"
|
| 140 |
+
f" {_dmin} and {_dmax}, Given a cutoff value {_cutoff}, data are split"
|
| 141 |
+
f" into {_nobs1}/{_nobs2} observations."
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
if NLgen:
|
| 145 |
+
_verbose_log = makeVerbose(_log)
|
| 146 |
+
else:
|
| 147 |
+
_verbose_log = "Natural language generation disabled."
|
| 148 |
+
|
| 149 |
+
return (
|
| 150 |
+
top_filtered_columns,
|
| 151 |
+
(
|
| 152 |
+
f"{filtered_columns.shape[0]} ({filtered_columns.shape[0]*(filtered_columns.shape[0]-1)})"
|
| 153 |
+
),
|
| 154 |
+
ret_string_anom,
|
| 155 |
+
image_from_plot,
|
| 156 |
+
_verbose_log,
|
| 157 |
+
)
|
engines/lof.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
from pandarallel import pandarallel
|
| 5 |
+
|
| 6 |
+
from itertools import combinations
|
| 7 |
+
from scipy.stats import pearsonr
|
| 8 |
+
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
| 11 |
+
|
| 12 |
+
from filters.filter_features import filterFeatures
|
| 13 |
+
from experimental.make_verbose import makeVerbose
|
| 14 |
+
|
| 15 |
+
from sklearn.neighbors import LocalOutlierFactor
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def check_anom(c1, c2, df_1, df_2, CORR_THRESHOLD):
|
| 19 |
+
|
| 20 |
+
stat_1, pval_1 = pearsonr(df_1[c1], df_1[c2])
|
| 21 |
+
stat_2, pval_2 = pearsonr(df_2[c1], df_2[c2])
|
| 22 |
+
|
| 23 |
+
if ((stat_1 > CORR_THRESHOLD) & (stat_2 < -CORR_THRESHOLD)) | (
|
| 24 |
+
(stat_1 < -CORR_THRESHOLD) & (stat_2 > CORR_THRESHOLD)
|
| 25 |
+
):
|
| 26 |
+
print(c1, c2, stat_1, pval_1, stat_2, pval_2)
|
| 27 |
+
return [(c1, c2), (stat_1, stat_2)]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def lof(
|
| 31 |
+
filter_string,
|
| 32 |
+
exact_match,
|
| 33 |
+
sector,
|
| 34 |
+
RELEVANCE_QUANTILE_100s,
|
| 35 |
+
CORR_THRESHOLD,
|
| 36 |
+
cutoff,
|
| 37 |
+
NLgen,
|
| 38 |
+
):
|
| 39 |
+
|
| 40 |
+
LOOKUP_SPACE_LIM = 50_000 # keep size sane
|
| 41 |
+
|
| 42 |
+
# ugly duplication, TOFIX
|
| 43 |
+
df = pd.read_parquet("stock_price.parquet").interpolate(method="linear", axis=1)
|
| 44 |
+
|
| 45 |
+
_log = []
|
| 46 |
+
RELEVANCE_QUANTILE = RELEVANCE_QUANTILE_100s * 0.01
|
| 47 |
+
|
| 48 |
+
filtered_columns, tickers_desc = filterFeatures(
|
| 49 |
+
df, sector, RELEVANCE_QUANTILE, filter_string, exact_match
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
top_filtered_columns = (
|
| 53 |
+
filtered_columns[["keywords", "relevance", "industry"]].iloc[0:10].reset_index()
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# limit max search space size, 3D
|
| 57 |
+
lookup_space = pd.DataFrame(
|
| 58 |
+
list(combinations(filtered_columns.index, 3))[0:LOOKUP_SPACE_LIM]
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# split irrelevant for LOF
|
| 62 |
+
# split_point = int(len(df) * cutoff)
|
| 63 |
+
|
| 64 |
+
#pandarallel.initialize(progress_bar=False, nb_workers=8)
|
| 65 |
+
|
| 66 |
+
model1 = LocalOutlierFactor(n_neighbors = 5, metric = "manhattan", contamination = 0.01)# model fitting
|
| 67 |
+
|
| 68 |
+
df_test = df[lookup_space.iloc[0]] # strategize combination by relevance TODO
|
| 69 |
+
df_test
|
| 70 |
+
|
| 71 |
+
y_pred = model1.fit_predict(df_test)# filter outlier index
|
| 72 |
+
#y_pred
|
| 73 |
+
|
| 74 |
+
outlier_index = np.where(y_pred == -1) # negative values are outliers and positives inliers# filter outlier values
|
| 75 |
+
#outlier_index
|
| 76 |
+
|
| 77 |
+
outlier_values = df_test.iloc[outlier_index]# plot data
|
| 78 |
+
outlier_values
|
| 79 |
+
|
| 80 |
+
# for plotting, pick first three columns (latent extra ones hidden from visu)
|
| 81 |
+
col1, col2, col3 = outlier_values.columns[0:3]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
ret_string_anom = (
|
| 85 |
+
f"{outlier_values.shape[0]} anomalies detected in selected data (showing up to 5):\n\n"
|
| 86 |
+
f"{outlier_values}"
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
_tk1, _tk1desc = f"{col1}", f"{tickers_desc.loc[col1]['keywords']}"
|
| 90 |
+
_tk2, _tk2desc = f"{col2}", f"{tickers_desc.loc[col2]['keywords']}"
|
| 91 |
+
_tk3, _tk3desc = f"{col3}", f"{tickers_desc.loc[col3]['keywords']}"
|
| 92 |
+
|
| 93 |
+
fig, ax = plt.subplots(figsize=(12, 12))
|
| 94 |
+
|
| 95 |
+
plt.scatter(df_test[col1], df_test[col2], color = "b", s = 65, label='inlier')# plot outlier values
|
| 96 |
+
plt.scatter(outlier_values[col1], outlier_values[col2], color = "r", label='outlier')
|
| 97 |
+
|
| 98 |
+
plt.title(f"{col1}|{col2}|{col3}")
|
| 99 |
+
ax.legend(loc="lower right")
|
| 100 |
+
fig.tight_layout(pad=0)
|
| 101 |
+
|
| 102 |
+
canvas = FigureCanvasAgg(fig)
|
| 103 |
+
canvas.draw()
|
| 104 |
+
s, (width, height) = canvas.print_to_buffer()
|
| 105 |
+
image_from_plot = np.frombuffer(s, np.uint8).reshape((height, width, 4))
|
| 106 |
+
|
| 107 |
+
_log = (
|
| 108 |
+
f"The relevant symbols are {_tk1} ({_tk1desc}), {_tk2} ({_tk2desc})"
|
| 109 |
+
f"and {_tk3} ({_tk3desc})."
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
if NLgen:
|
| 113 |
+
_verbose_log = makeVerbose(_log)
|
| 114 |
+
else:
|
| 115 |
+
_verbose_log = "Natural language generation disabled."
|
| 116 |
+
|
| 117 |
+
return (
|
| 118 |
+
top_filtered_columns,
|
| 119 |
+
(
|
| 120 |
+
f"{filtered_columns.shape[0]} ({filtered_columns.shape[0]*(filtered_columns.shape[0]-1)})"
|
| 121 |
+
),
|
| 122 |
+
ret_string_anom,
|
| 123 |
+
image_from_plot,
|
| 124 |
+
_verbose_log,
|
| 125 |
+
)
|
experimental/make_verbose.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import openai
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def makeVerbose(s):
|
| 6 |
+
|
| 7 |
+
# clean up
|
| 8 |
+
openai.api_key = os.getenv("chat_secret")
|
| 9 |
+
preamble = os.getenv("chat_prompt")
|
| 10 |
+
chat_model = os.getenv("chat_model")
|
| 11 |
+
|
| 12 |
+
# _q = ' '.join([preamble+s])
|
| 13 |
+
_q = f"{preamble} {' '.join(s)}"
|
| 14 |
+
|
| 15 |
+
response = openai.Completion.create(
|
| 16 |
+
model=chat_model,
|
| 17 |
+
prompt=_q,
|
| 18 |
+
temperature=0.70,
|
| 19 |
+
max_tokens=200,
|
| 20 |
+
top_p=1.0,
|
| 21 |
+
frequency_penalty=0.0,
|
| 22 |
+
presence_penalty=0.0,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
_a = response["choices"][0]["text"]
|
| 26 |
+
_a = _a.replace("\n", "")
|
| 27 |
+
return _a
|
filters/filter_features.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
# import Levenshtein
|
| 6 |
+
import textdistance
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def filterFeatures(df, sector, RELEVANCE_QUANTILE, filter_string, exact_match):
|
| 10 |
+
|
| 11 |
+
tickers_desc_all = pd.read_parquet("tickers_desc_act.parquet")
|
| 12 |
+
tickers_desc_prefilter = tickers_desc_all.loc[df.columns]
|
| 13 |
+
|
| 14 |
+
if sector:
|
| 15 |
+
tickers_desc = tickers_desc_prefilter[
|
| 16 |
+
tickers_desc_prefilter["sector"] == sector
|
| 17 |
+
] # all sectors included
|
| 18 |
+
else:
|
| 19 |
+
tickers_desc = tickers_desc_prefilter
|
| 20 |
+
|
| 21 |
+
tickers_desc["relevance"] = tickers_desc["keywords"].apply(
|
| 22 |
+
lambda k: textdistance.ratcliff_obershelp(k, filter_string)
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
relevant_threshold = np.quantile(
|
| 26 |
+
tickers_desc["relevance"], 1.0 - RELEVANCE_QUANTILE
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
if exact_match:
|
| 30 |
+
filtered_columns = tickers_desc[
|
| 31 |
+
tickers_desc["keywords"].str.contains(
|
| 32 |
+
filter_string, flags=re.IGNORECASE, regex=True
|
| 33 |
+
)
|
| 34 |
+
].sort_values(by="relevance", ascending=False)
|
| 35 |
+
else:
|
| 36 |
+
filtered_columns = tickers_desc[
|
| 37 |
+
tickers_desc.relevance >= relevant_threshold
|
| 38 |
+
].sort_values(by="relevance", ascending=False)
|
| 39 |
+
|
| 40 |
+
return filtered_columns, tickers_desc
|
pipeline.py
CHANGED
|
@@ -1,191 +1,44 @@
|
|
| 1 |
import pandas as pd
|
| 2 |
import numpy as np
|
| 3 |
-
from scipy.stats import pearsonr
|
| 4 |
-
from itertools import combinations
|
| 5 |
|
| 6 |
import os
|
| 7 |
import re
|
| 8 |
|
| 9 |
import openai
|
| 10 |
|
| 11 |
-
|
| 12 |
-
from
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
from pandarallel import pandarallel
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
#@dataclass
|
| 21 |
-
#class Engine:
|
| 22 |
# pipeline: function
|
| 23 |
# examples: list
|
| 24 |
|
| 25 |
-
# dummy pipeline (collelation inversion lookup)
|
| 26 |
-
|
| 27 |
-
LOOKUP_SPACE_LIM = 50_000
|
| 28 |
-
RELEVANCE_QUANTILE = 0.05 # top 5%
|
| 29 |
-
|
| 30 |
-
def check_anom(c1, c2, df_1, df_2, CORR_THRESHOLD):
|
| 31 |
-
stat_1, pval_1 = pearsonr(df_1[c1], df_1[c2])
|
| 32 |
-
stat_2, pval_2 = pearsonr(df_2[c1], df_2[c2])
|
| 33 |
-
|
| 34 |
-
if ((stat_1 > CORR_THRESHOLD) & (stat_2 < -CORR_THRESHOLD)) | ((stat_1 < -CORR_THRESHOLD) & (stat_2 > CORR_THRESHOLD)):
|
| 35 |
-
print(c1,c2, stat_1, pval_1, stat_2, pval_2)
|
| 36 |
-
return [(c1,c2), (stat_1,stat_2)]
|
| 37 |
-
|
| 38 |
-
def makeVerbose(s):
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
|
| 49 |
-
model=chat_model,
|
| 50 |
-
prompt=_q,
|
| 51 |
-
temperature=0.70,
|
| 52 |
-
max_tokens=200,
|
| 53 |
-
top_p=1.0,
|
| 54 |
-
frequency_penalty=0.0,
|
| 55 |
-
presence_penalty=0.0,
|
| 56 |
-
)
|
| 57 |
-
|
| 58 |
-
_a = response['choices'][0]['text']
|
| 59 |
-
_a = _a.replace('\n','')
|
| 60 |
-
return _a
|
| 61 |
|
| 62 |
-
|
| 63 |
filter_string,
|
| 64 |
exact_match,
|
| 65 |
sector,
|
| 66 |
-
RELEVANCE_QUANTILE_100s,
|
| 67 |
-
CORR_THRESHOLD,
|
| 68 |
cutoff,
|
| 69 |
-
NLgen
|
| 70 |
-
):
|
| 71 |
-
|
| 72 |
-
_log = []
|
| 73 |
-
RELEVANCE_QUANTILE = RELEVANCE_QUANTILE_100s * 0.01
|
| 74 |
-
|
| 75 |
-
# ugly duplication, TOFIX
|
| 76 |
-
df = pd.read_parquet('stock_price.parquet').interpolate(method='linear', axis=1)
|
| 77 |
-
|
| 78 |
-
tickers_desc_all = pd.read_parquet('tickers_desc_act.parquet')
|
| 79 |
-
tickers_desc_prefilter = tickers_desc_all.loc[df.columns]
|
| 80 |
-
|
| 81 |
-
if sector:
|
| 82 |
-
tickers_desc = tickers_desc_prefilter[
|
| 83 |
-
tickers_desc_prefilter['sector'] == sector
|
| 84 |
-
] # all sectors included
|
| 85 |
-
else:
|
| 86 |
-
tickers_desc = tickers_desc_prefilter
|
| 87 |
-
|
| 88 |
-
tickers_desc['relevance'] = tickers_desc['keywords'].apply(
|
| 89 |
-
lambda k: textdistance.ratcliff_obershelp(k, filter_string)
|
| 90 |
-
)
|
| 91 |
-
|
| 92 |
-
relevant_threshold = np.quantile(tickers_desc['relevance'], 1.0-RELEVANCE_QUANTILE)
|
| 93 |
-
|
| 94 |
-
if exact_match:
|
| 95 |
-
filtered_columns = tickers_desc[
|
| 96 |
-
tickers_desc['keywords'].str.contains(filter_string, flags=re.IGNORECASE, regex=True)
|
| 97 |
-
].sort_values(by='relevance', ascending=False)
|
| 98 |
-
else:
|
| 99 |
-
filtered_columns = tickers_desc[
|
| 100 |
-
tickers_desc.relevance >= relevant_threshold
|
| 101 |
-
].sort_values(by='relevance', ascending=False)
|
| 102 |
-
|
| 103 |
-
top_filtered_columns = filtered_columns[[
|
| 104 |
-
'keywords', 'relevance', 'industry'
|
| 105 |
-
]].iloc[0:10].reset_index()
|
| 106 |
-
|
| 107 |
-
# limit max search space size
|
| 108 |
-
lookup_space = pd.DataFrame(list(combinations(filtered_columns.index, 2))[0:LOOKUP_SPACE_LIM])
|
| 109 |
-
|
| 110 |
-
# split
|
| 111 |
-
split_point = int( len(df) * cutoff )
|
| 112 |
-
|
| 113 |
-
df_1 = df.iloc[:split_point,]
|
| 114 |
-
df_2 = df.iloc[split_point:,]
|
| 115 |
-
|
| 116 |
-
split_date = df.iloc[split_point].name
|
| 117 |
-
|
| 118 |
-
_cutoff, _nobs1, _nobs2 = f"{cutoff}", f"{df_1.shape[0]}", f"{df_2.shape[0]}"
|
| 119 |
-
|
| 120 |
-
(_cutoffdate, _dmin, _dmax) = (
|
| 121 |
-
f"{split_date.strftime('%B %d, %Y')}",
|
| 122 |
-
f"{min(df.index).strftime('%B %d, %Y')}",
|
| 123 |
-
f"{max(df.index).strftime('%B %d, %Y')}"
|
| 124 |
)
|
| 125 |
-
|
| 126 |
-
pandarallel.initialize(progress_bar=False, nb_workers=8)
|
| 127 |
-
|
| 128 |
-
res = lookup_space.apply( # debugging
|
| 129 |
-
#res = lookup_space.parallel_apply(
|
| 130 |
-
lambda r: check_anom(r[0],r[1], df_1, df_2, CORR_THRESHOLD),
|
| 131 |
-
axis=1
|
| 132 |
-
).dropna()
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
if res.shape[0]==0:
|
| 136 |
-
ret_string_anom = "No anomalies detected in selected data."
|
| 137 |
-
|
| 138 |
-
return(top_filtered_columns,
|
| 139 |
-
f"{filtered_columns.shape[0]} ({filtered_columns.shape[0]*(filtered_columns.shape[0]-1)})",
|
| 140 |
-
ret_string_anom,
|
| 141 |
-
None,
|
| 142 |
-
"Not much to say; try and relax the detection constraints.")
|
| 143 |
-
|
| 144 |
-
else:
|
| 145 |
-
ret_string_anom = f"{res.shape[0]} anomalies detected in selected data (showing up to 5):\n\n" + '\n'.join(
|
| 146 |
-
[f"{r[0][0]}({tickers_desc.loc[r[0][0]]['keywords']}) | {r[0][1]} ({tickers_desc.loc[r[0][1]]['keywords']}):\n"
|
| 147 |
-
f"{r[1][0]:.2f} | {r[1][1]:.2f}\n" for i, r in res.iloc[0:5].items()]
|
| 148 |
-
)
|
| 149 |
-
|
| 150 |
-
for i, ((c1, c2),(r1,r2)) in res.head(1).items():
|
| 151 |
-
|
| 152 |
-
_tk1, _tk1desc = f"{c1}", f"{tickers_desc.loc[c1]['keywords']}"
|
| 153 |
-
_tk2, _tk2desc = f"{c2}", f"{tickers_desc.loc[c2]['keywords']}"
|
| 154 |
-
_r1, _r2 = f"{r1:.2f}", f"{r2:.2f}"
|
| 155 |
-
|
| 156 |
-
fig, ax = plt.subplots(figsize=(18,6))
|
| 157 |
-
ax.tick_params(labelrotation=90)
|
| 158 |
-
ax_r = ax.twinx()
|
| 159 |
-
ax.plot(df[c1], c='r', label=c1)
|
| 160 |
-
ax_r.plot(df[c2], c='g', label=c2)
|
| 161 |
-
ax.axvline(split_date)
|
| 162 |
-
plt.title(f"{c1}|{c2}:{r1:.2g},{r2:.2g}")
|
| 163 |
-
ax.legend(loc='upper left')
|
| 164 |
-
ax_r.legend(loc='upper right')
|
| 165 |
-
fig.tight_layout(pad=0)
|
| 166 |
-
|
| 167 |
-
canvas = FigureCanvasAgg(fig)
|
| 168 |
-
canvas.draw()
|
| 169 |
-
s, (width, height) = canvas.print_to_buffer()
|
| 170 |
-
image_from_plot = np.frombuffer(s, np.uint8).reshape((height, width, 4))
|
| 171 |
-
|
| 172 |
-
_log = (
|
| 173 |
-
f"The relevant symbols are {_tk1} ({_tk1desc}) "
|
| 174 |
-
f"and {_tk2} ({_tk2desc}). "
|
| 175 |
-
f"The correlation coefficient for the symbols pair {_tk1} and {_tk2} is initially {_r1} and inverts to {_r2} "
|
| 176 |
-
f"after cutoff date, which is {_cutoffdate}; "
|
| 177 |
-
f"by the way, the dataset is defined between {_dmin} and {_dmax}, "
|
| 178 |
-
f"Given a cutoff value {_cutoff}, data are split into {_nobs1}/{_nobs2} observations."
|
| 179 |
-
)
|
| 180 |
-
|
| 181 |
-
if NLgen:
|
| 182 |
-
_verbose_log = makeVerbose(_log)
|
| 183 |
-
else:
|
| 184 |
-
_verbose_log = 'Natural language generation disabled.'
|
| 185 |
-
|
| 186 |
-
return(top_filtered_columns,
|
| 187 |
-
f"{filtered_columns.shape[0]} ({filtered_columns.shape[0]*(filtered_columns.shape[0]-1)})",
|
| 188 |
-
ret_string_anom,
|
| 189 |
-
image_from_plot,
|
| 190 |
-
_verbose_log
|
| 191 |
-
)
|
|
|
|
| 1 |
import pandas as pd
|
| 2 |
import numpy as np
|
|
|
|
|
|
|
| 3 |
|
| 4 |
import os
|
| 5 |
import re
|
| 6 |
|
| 7 |
import openai
|
| 8 |
|
| 9 |
+
from engines.corrinv import corrinv
|
| 10 |
+
from engines.lof import lof
|
| 11 |
|
| 12 |
+
# @dataclass
|
| 13 |
+
# class Engine:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
# pipeline: function
|
| 15 |
# examples: list
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
def getEngine(
|
| 19 |
+
filter_string,
|
| 20 |
+
exact_match,
|
| 21 |
+
sector,
|
| 22 |
+
engine, # not passed down to actual engines, oc
|
| 23 |
+
RELEVANCE_QUANTILE_100s,
|
| 24 |
+
CORR_THRESHOLD,
|
| 25 |
+
cutoff,
|
| 26 |
+
NLgen,
|
| 27 |
+
):
|
| 28 |
|
| 29 |
+
engines_factory = {
|
| 30 |
+
"corrinv": corrinv,
|
| 31 |
+
"lof": lof
|
| 32 |
+
}
|
| 33 |
|
| 34 |
+
print(f"Using engine {engine}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
return engines_factory.get(engine, None)(
|
| 37 |
filter_string,
|
| 38 |
exact_match,
|
| 39 |
sector,
|
| 40 |
+
RELEVANCE_QUANTILE_100s,
|
| 41 |
+
CORR_THRESHOLD,
|
| 42 |
cutoff,
|
| 43 |
+
NLgen,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|