File size: 2,332 Bytes
e2a1874
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd

import re

from pathlib import Path

import yfinance as yf

from datetime import datetime

TICKERS = list(pd.read_csv("perim.csv")["symbol"].values)  # [0:50]
print("TICKERS:", TICKERS)


def map_compact(n: float, tol) -> str:

    if n > tol:
        return "U"
    elif n < -tol:
        return "D"
    else:
        return "N"


def compact(df, tol=1e-3):

    return (
        df.pct_change().dropna().map(lambda x: map_compact(x, tol=tol)).apply("".join)
    )


def find_streak(df: pd.DataFrame, direction: str, length: int) -> pd.DataFrame:

    _dir = "U" if direction == "up" else "D"

    _regexp = f"[{_dir}N]{{{length}}}"
    _compiled_regexp = re.compile(_regexp)
    _checked = df.apply(lambda r: _compiled_regexp.search(r)).dropna()

    _match = _checked.apply(lambda c: c.group())
    _span = _checked.apply(lambda c: c.span())

    _outcome = pd.concat([_match, _span], axis=1).reset_index()

    _outcome.columns = ["symbol", "match", "range"]

    return _outcome


def check_if_file_exists(ref_date):

    _file = Path(f"hist_data/{ref_date}.pq")
    if _file.is_file():
        return True
    else:
        return False


def fetch_tickers(tickers):
    # check if fresh data already available
    today = datetime.now().date().strftime("%Y-%m-%d")

    if check_if_file_exists(today):
        df = pd.read_parquet(f"hist_data/{today}.pq").dropna(axis=1)
        return df
    else:
        df = yf.download(tickers, period="1mo")["Close"].dropna(axis=1)
        df.to_parquet(f"hist_data/{today}.pq")
        return df


def lookup(direction, length, tolerance):

    # load existing data from file (in widget: drag-drop your file?)
    # df = pd.read_parquet("stock_price_small.pq").interpolate(method="linear", axis=1)

    df = fetch_tickers(TICKERS)

    print(direction, length)

    df_compact = compact(df, tolerance * 0.01)  # percent to decimal

    # print("compact:", df_compact)

    _ret = find_streak(df_compact, direction, length)

    # use actual dates instead of offsets in range

    _df_dates = df.index

    _ret["range_dates"] = _ret["range"].apply(
        lambda r: [
            _df_dates[r[0]].date().strftime("%Y-%m-%d"),
            _df_dates[r[1]].date().strftime("%Y-%m-%d"),
        ]
    )

    _ret.drop(columns=["range"], inplace=True)

    return _ret