streaks / libs /funcs.py
matteom's picture
hide range, redundant
2d988bd unverified
Raw History Blame Contribute Delete
2.43 kB
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"
print("DF:::", df.iloc[2])
_regexp = f"[{_dir}N]{{{length}}}"
_compiled_regexp = re.compile(_regexp)
_checked = df.apply(lambda r: _compiled_regexp.search(r[-length:])).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[["symbol", "match"]]
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="15d")["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.tail(length+1).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