Spaces:
Sleeping
Sleeping
Delete persist.py
Browse files- persist.py +0 -151
persist.py
DELETED
|
@@ -1,151 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
import pickle
|
| 4 |
-
import pandas as pd
|
| 5 |
-
from datetime import datetime, timedelta
|
| 6 |
-
from typing import Any
|
| 7 |
-
import yfinance as yf
|
| 8 |
-
|
| 9 |
-
# ==============================
|
| 10 |
-
# Configuration
|
| 11 |
-
# ==============================
|
| 12 |
-
BASE_DIR = "./data/store"
|
| 13 |
-
os.makedirs(BASE_DIR, exist_ok=True)
|
| 14 |
-
|
| 15 |
-
# TTL validity map (per parent type)
|
| 16 |
-
VALIDITY_MAP = {
|
| 17 |
-
"result": {"days": 7},
|
| 18 |
-
"qresult": {"days": 7},
|
| 19 |
-
"bhav": {"days": 1},
|
| 20 |
-
"intraday": {"minutes": 15},
|
| 21 |
-
"eq": {"hours": 1},
|
| 22 |
-
"daily": {"days": 1},
|
| 23 |
-
}
|
| 24 |
-
|
| 25 |
-
# ==============================
|
| 26 |
-
# Helpers
|
| 27 |
-
# ==============================
|
| 28 |
-
def _ts():
|
| 29 |
-
return datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
|
| 30 |
-
|
| 31 |
-
def _path(filename: str):
|
| 32 |
-
return os.path.join(BASE_DIR, filename)
|
| 33 |
-
|
| 34 |
-
def _list_files():
|
| 35 |
-
return os.listdir(BASE_DIR)
|
| 36 |
-
|
| 37 |
-
def _latest(prefix: str, ext: str):
|
| 38 |
-
files = [
|
| 39 |
-
f for f in _list_files()
|
| 40 |
-
if f.startswith(prefix + "_") and f.endswith("." + ext)
|
| 41 |
-
]
|
| 42 |
-
return max(files) if files else None
|
| 43 |
-
|
| 44 |
-
# ==============================
|
| 45 |
-
# Save / Load / Exists
|
| 46 |
-
# ==============================
|
| 47 |
-
def save(name: str, data: Any, ftype: str) -> bool:
|
| 48 |
-
ts = _ts()
|
| 49 |
-
filename = f"{name}_{ts}.{ftype}"
|
| 50 |
-
path = _path(filename)
|
| 51 |
-
try:
|
| 52 |
-
if ftype == "csv":
|
| 53 |
-
if not isinstance(data, pd.DataFrame):
|
| 54 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [SAVE FAILED] CSV requires pandas DataFrame for {filename}")
|
| 55 |
-
return False
|
| 56 |
-
data.to_csv(path, index=False)
|
| 57 |
-
elif ftype == "json":
|
| 58 |
-
with open(path, "w", encoding="utf-8") as f:
|
| 59 |
-
json.dump(data, f, indent=2)
|
| 60 |
-
elif ftype == "html":
|
| 61 |
-
with open(path, "w", encoding="utf-8") as f:
|
| 62 |
-
f.write(str(data))
|
| 63 |
-
elif ftype == "pkl":
|
| 64 |
-
with open(path, "wb") as f:
|
| 65 |
-
pickle.dump(data, f)
|
| 66 |
-
else:
|
| 67 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [SAVE FAILED] Unsupported file type: {ftype} for {filename}")
|
| 68 |
-
return False
|
| 69 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [SAVE OK] {filename}")
|
| 70 |
-
return True
|
| 71 |
-
except Exception as e:
|
| 72 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [SAVE FAILED] {filename} - Exception: {e}")
|
| 73 |
-
return False
|
| 74 |
-
|
| 75 |
-
def load(name: str, ftype: str):
|
| 76 |
-
filename = _latest(name, ftype) if "." not in name else name
|
| 77 |
-
path = _path(filename)
|
| 78 |
-
if not os.path.exists(path):
|
| 79 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [LOAD FAILED] File does not exist: {filename}")
|
| 80 |
-
return False
|
| 81 |
-
try:
|
| 82 |
-
if filename.endswith(".csv"):
|
| 83 |
-
df = pd.read_csv(path)
|
| 84 |
-
elif filename.endswith(".json"):
|
| 85 |
-
with open(path, "r", encoding="utf-8") as f:
|
| 86 |
-
df = json.load(f)
|
| 87 |
-
elif filename.endswith(".html"):
|
| 88 |
-
with open(path, "r", encoding="utf-8") as f:
|
| 89 |
-
df = f.read()
|
| 90 |
-
elif filename.endswith(".pkl"):
|
| 91 |
-
with open(path, "rb") as f:
|
| 92 |
-
df = pickle.load(f)
|
| 93 |
-
else:
|
| 94 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [LOAD FAILED] Unsupported file type: {filename}")
|
| 95 |
-
return False
|
| 96 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [LOAD OK] {filename}")
|
| 97 |
-
return df
|
| 98 |
-
except Exception as e:
|
| 99 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [LOAD FAILED] {filename} - Exception: {e}")
|
| 100 |
-
return False
|
| 101 |
-
|
| 102 |
-
def exists(name: str, ftype: str) -> bool:
|
| 103 |
-
"""
|
| 104 |
-
Checks if a file exists AND is valid within TTL based on parent type + symbol.
|
| 105 |
-
Example:
|
| 106 |
-
name = INTRADAY_RELIANCE
|
| 107 |
-
matches any file starting with INTRADAY_RELIANCE_YYYY_MM_DD_HH_MM_SS.csv
|
| 108 |
-
TTL applied according to parent type (INTRADAY -> 15 minutes)
|
| 109 |
-
"""
|
| 110 |
-
filename = _latest(name, ftype)
|
| 111 |
-
if not filename:
|
| 112 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [EXISTS] No file found for {name}.{ftype}")
|
| 113 |
-
return False
|
| 114 |
-
|
| 115 |
-
path = _path(filename)
|
| 116 |
-
if not os.path.exists(path):
|
| 117 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [EXISTS] File not present: {filename}")
|
| 118 |
-
return False
|
| 119 |
-
|
| 120 |
-
parent_func = name.split("_")[0].lower() # INTRADAY, RESULT, etc.
|
| 121 |
-
validity = VALIDITY_MAP.get(parent_func)
|
| 122 |
-
if not validity:
|
| 123 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [EXISTS] File exists with no TTL: {filename}")
|
| 124 |
-
return True
|
| 125 |
-
|
| 126 |
-
mtime = datetime.fromtimestamp(os.path.getmtime(path))
|
| 127 |
-
now = datetime.now()
|
| 128 |
-
is_valid = True
|
| 129 |
-
if "minutes" in validity:
|
| 130 |
-
is_valid = (now - mtime) <= timedelta(minutes=validity["minutes"])
|
| 131 |
-
elif "hours" in validity:
|
| 132 |
-
is_valid = (now - mtime) <= timedelta(hours=validity["hours"])
|
| 133 |
-
elif "days" in validity:
|
| 134 |
-
is_valid = (now - mtime) <= timedelta(days=validity["days"])
|
| 135 |
-
|
| 136 |
-
if is_valid:
|
| 137 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [EXISTS] File exists and valid: {filename}")
|
| 138 |
-
else:
|
| 139 |
-
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [EXISTS] File expired: {filename}")
|
| 140 |
-
|
| 141 |
-
return is_valid
|
| 142 |
-
|
| 143 |
-
def list_files(name=None, ftype=None):
|
| 144 |
-
files = sorted(_list_files())
|
| 145 |
-
if name:
|
| 146 |
-
files = [f for f in files if f.startswith(name + "_")]
|
| 147 |
-
if ftype:
|
| 148 |
-
files = [f for f in files if f.endswith("." + ftype)]
|
| 149 |
-
return files
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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