Download 1_candle_pattern.py from algorembrant/12_all-topological_1-candle_patterns: direct link, hf CLI and curl.
- Browser
- Download file 6.2 kB
-
https://huggingface.co/datasets/algorembrant/12_all-topological_1-candle_patterns/resolve/main/1_candle_pattern.py
- Command line
-
hf download hf://datasets/algorembrant/12_all-topological_1-candle_patterns/1_candle_pattern.py
-
curl -L -o 1_candle_pattern.py https://huggingface.co/datasets/algorembrant/12_all-topological_1-candle_patterns/resolve/main/1_candle_pattern.py
6.2 kB
| import os | |
| import time | |
| import gc | |
| import sys | |
| import numpy as np | |
| try: | |
| import psutil | |
| HAS_PSUTIL = True | |
| except ImportError: | |
| HAS_PSUTIL = False | |
| import matplotlib.pyplot as plt | |
| import matplotlib.patches as patches | |
| import torch | |
| from tqdm import tqdm | |
| from joblib import Parallel, delayed | |
| # SOTA-Tier Hardware Configuration Target N <= 2 | |
| N = 1 | |
| V = 4 * N | |
| BATCH_SIZE = max(10_000, 2_000_000 // N) if not torch.cuda.is_available() else max(20_000, 5_000_000 // N)PATTERNS_PER_IMG = 10 | |
| RAM_LIMIT_GB = 11.5 | |
| os.makedirs(f'images_1C', exist_ok=True) | |
| def draw_candle(ax, x, O, H, L, C): | |
| color = 'green' if C > O else 'red' if C < O else 'black' | |
| ax.plot([x, x], [L, H], color=color, linewidth=2) | |
| top, bottom = max(O, C), min(O, C) | |
| height = max(top - bottom, 0.2) if top == bottom else (top - bottom) | |
| rect_y = bottom if top != bottom else bottom - 0.1 | |
| ax.add_patch(patches.Rectangle((x - 0.3, rect_y), 0.6, height, linewidth=1, edgecolor=color, facecolor=color)) | |
| def get_logic_string(p): | |
| labels = [] | |
| for i in range(1, N+1): labels.extend([f'O{i}', f'H{i}', f'L{i}', f'C{i}']) | |
| groups = {} | |
| for i, val in enumerate(p): | |
| groups.setdefault(val, []).append(labels[i]) | |
| return " > ".join("(" + " = ".join(groups[val]) + ")" for val in sorted(groups.keys(), reverse=True)) | |
| def render_batch_sota(batch_idx_start, batch_patterns, images_dir): | |
| fig, axes = plt.subplots(2, 5, figsize=(20, 8)) | |
| fig.subplots_adjust(hspace=0.5, wspace=0.3) | |
| ax_array = axes.flatten() | |
| batch_results = [] | |
| img_name = f"plot_{batch_idx_start//PATTERNS_PER_IMG + 1}.png" | |
| for ax in ax_array: ax.set_visible(False) | |
| for j, p in enumerate(batch_patterns): | |
| ax = ax_array[j] | |
| ax.set_visible(True) | |
| scale = 5.0 | |
| for k in range(N): | |
| draw_candle(ax, k+1, p[k*4]*scale, p[k*4+1]*scale, p[k*4+2]*scale, p[k*4+3]*scale) | |
| ax.set_ylim(-5, V*scale + 5) | |
| ax.set_xlim(0, N+1) | |
| ax.set_xticks([]); ax.set_yticks([]) | |
| pattern_id = f"P_{batch_idx_start+j:05d}" | |
| logic_str = get_logic_string(p) | |
| ax.set_title(f"{pattern_id}", fontsize=10) | |
| ax.text(0.5, -0.1, logic_str, transform=ax.transAxes, fontsize=max(3, 10 - len(logic_str)//20), ha='center', va='top', wrap=True) | |
| batch_results.append(f"| {pattern_id} | {logic_str} | {img_name} |") | |
| img_path = os.path.join(images_dir, img_name) | |
| fig.savefig(img_path, bbox_inches='tight') | |
| plt.close(fig) | |
| return batch_results | |
| if __name__ == '__main__': | |
| print(f"--- SOTA Visual Pattern Engine (EXHAUSTIVE EXACT): 1-candle ---") | |
| start_time = time.time() | |
| valid_single_candles = [] | |
| for h in range(V): | |
| for l in range(h + 1): | |
| for o in range(l, h + 1): | |
| for c in range(l, h + 1): | |
| valid_single_candles.append((o, h, l, c)) | |
| M = len(valid_single_candles) | |
| total_permutations = M ** N | |
| print(f"Combinations: {total_permutations:,} | Initializing VRAM/RAM Context...") | |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
| base_tensor = torch.tensor(valid_single_candles, dtype=torch.int16, device=device) | |
| powers = (M ** torch.arange(N-1, -1, -1, device=device)).unsqueeze(0) | |
| global_unique_chunks = [] | |
| limit_hit = False | |
| try: | |
| with tqdm(total=total_permutations, desc="Discovery Phase") as pbar: | |
| for start_idx in range(0, total_permutations, BATCH_SIZE): | |
| end_idx = min(start_idx + BATCH_SIZE, total_permutations) | |
| curr_b = end_idx - start_idx | |
| batch_idx = torch.arange(start_idx, end_idx, device=device).unsqueeze(1) | |
| comb_idx = (batch_idx // powers) % M | |
| candles = base_tensor[comb_idx].view(curr_b, 4 * N) | |
| # Fast PyTorch Dense Ranking | |
| sorted_c, indices = torch.sort(candles, dim=1) | |
| diffs = torch.cat([torch.ones(curr_b, 1, device=device, dtype=torch.int16), (sorted_c[:, 1:] > sorted_c[:, :-1]).to(torch.int16)], dim=1) | |
| cum_ranks = torch.cumsum(diffs, dim=1) - 1 | |
| ranks = torch.empty_like(candles) | |
| ranks.scatter_(1, indices, cum_ranks.to(torch.int16)) | |
| global_unique_chunks.append(torch.unique(ranks, dim=0).cpu()) | |
| if len(global_unique_chunks) > 10: | |
| merged = torch.cat(global_unique_chunks, dim=0) | |
| global_unique_chunks = [torch.unique(merged, dim=0)] | |
| pbar.update(curr_b) | |
| if HAS_PSUTIL and psutil.virtual_memory().used / (1024**3) > RAM_LIMIT_GB: | |
| limit_hit = True; break | |
| except Exception as e: | |
| print(f"Error: {e}"); limit_hit = True | |
| final_patterns_tensor = torch.unique(torch.cat(global_unique_chunks, dim=0), dim=0) if global_unique_chunks else torch.empty((0, 4*N)) | |
| patterns = final_patterns_tensor.tolist() | |
| total_patterns = len(patterns) | |
| print(f"Found {total_patterns} exact topological patterns in {time.time()-start_time:.2f}s.") | |
| images_dir = f'images_1C' | |
| render_tasks = [(i, patterns[i:i+PATTERNS_PER_IMG], images_dir) for i in range(0, total_patterns, PATTERNS_PER_IMG)] | |
| md_rows = Parallel(n_jobs=-1, backend="loky")( | |
| delayed(render_batch_sota)(*t) for t in tqdm(render_tasks, desc="SOTA Parallel Render") | |
| ) | |
| markdown_lines = [ | |
| f"# Exhaustive Topological 1-Candle Patterns\n", | |
| f"**Total unique combinations found:** {total_patterns}\n", | |
| "| Pattern ID | Mathematical Logic | Image Reference |\n", | |
| "|---|---|---|" | |
| ] | |
| if limit_hit: markdown_lines.insert(2, "*OOM Limitation protection triggered!*\n") | |
| for row_batch in md_rows: markdown_lines.extend(row_batch) | |
| with open(f'1C_patterns.md', 'w') as f: | |
| f.write("\n".join(markdown_lines)) | |
| print(f"SUCCESS! Total Time: {time.time() - start_time:.2f}s | Results in 1C_patterns.md") | |