File size: 5,846 Bytes
43235e7 | 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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | import pandas as pd
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
from tqdm import tqdm
# 定义输入输出路径
RAW_DIR = Path("data/yahoo")
HIST_DIR = Path("data/charts/hist")
FULL_DIR = Path("data/charts/full")
# 确保输出目录存在
HIST_DIR.mkdir(parents=True, exist_ok=True)
FULL_DIR.mkdir(parents=True, exist_ok=True)
# 窗口设置
L_HIST = 60 # 用过去 60 天
L_PRED = 10 # 预测未来 10 天
IMG_SIZE = (6, 6) # 图像尺寸,英寸
def render_sample(df, start_idx, ticker):
end_hist = start_idx + L_HIST
end_full = end_hist + L_PRED
# 如果数据不够长,就跳过
if end_full > len(df):
return
# 切片数据
window_hist = df.iloc[start_idx:end_hist]
window_full = df.iloc[start_idx:end_full]
# 确定统一的纵坐标范围(用完整段的最低最高价),保证两张图比例一致
price_min = window_full["Low"].min()
price_max = window_full["High"].max()
# 生成唯一文件名
date_hist_start = window_hist.index[0].strftime("%Y%m%d")
date_full_end = window_full.index[-1].strftime("%Y%m%d")
sample_id = f"{ticker}_{date_hist_start}_{date_full_end}_{start_idx}"
# --- 画图函数 ---
def plot_k_line(data, save_path, x_limit):
fig, ax = plt.subplots(figsize=IMG_SIZE)
ax.set_facecolor("white")
ax.grid(True, alpha=0.3)
# 遍历每一行数据画 K 线
for i, (idx, row) in enumerate(data.iterrows()):
# 涨跌颜色:收盘 >= 开盘 为绿,否则红
color = "green" if row["Close"] >= row["Open"] else "red"
# 画影线(最高到最低)
ax.plot([i, i], [row["Low"], row["High"]], color=color, linewidth=1)
# 画实体(开盘到收盘的矩形)
rect_height = abs(row["Close"] - row["Open"])
rect_bottom = min(row["Open"], row["Close"])
# 如果开收盘价一样(十字星),给个最小高度以便显示
if rect_height == 0:
rect_height = (price_max - price_min) * 0.002
ax.add_patch(plt.Rectangle((i - 0.3, rect_bottom),
0.6, rect_height,
color=color, alpha=0.8))
# 设置坐标轴范围
ax.set_xlim(-1, x_limit)
ax.set_ylim(price_min, price_max)
ax.axis("off") # 关掉坐标轴刻度,只留图形
plt.tight_layout()
plt.savefig(save_path, dpi=96)
plt.close(fig)
# 1. 画历史图 (0 ~ L_HIST)
plot_k_line(window_hist, HIST_DIR / f"{sample_id}.png", L_HIST)
# 2. 画完整图 (0 ~ L_HIST + L_PRED)
plot_k_line(window_full, FULL_DIR / f"{sample_id}.png", L_HIST + L_PRED)
def process_one(csv_path: Path):
try:
ticker = csv_path.name.split("_")[0]
# 1. 先整体读进来,不做 parse_dates
raw = pd.read_csv(csv_path, header=None)
# 2. 找到哪一行是真正的列名(优先找 OHLC,找不到再找 Date)
header_row_idx = None
for i in range(min(10, len(raw))):
row_str = raw.iloc[i].astype(str).tolist()
# 检查是否包含核心价格列
if all(c in row_str for c in ["Open", "High", "Low", "Close"]):
header_row_idx = i
break
if header_row_idx is None:
for i in range(min(10, len(raw))):
if "Date" in raw.iloc[i].astype(str).tolist():
header_row_idx = i
break
if header_row_idx is None:
print(f"Cannot find header in {csv_path}")
return
# 3. 用这一行作为列名
raw.columns = raw.iloc[header_row_idx]
# 丢掉表头行及其之前所有行
df = raw.iloc[header_row_idx + 1:].reset_index(drop=True)
# 4. 只保留需要的列,并重命名
df = df.dropna(axis=1, how="all")
# 有时 yfinance 会在列名前带个空格,统一 strip 一下
df.columns = [str(c).strip() for c in df.columns]
# 针对 yfinance 这种 "Price" 可能是 "Date" 的情况
if "Date" not in df.columns and "Price" in df.columns:
df.rename(columns={"Price": "Date"}, inplace=True)
required_cols = ["Date", "Open", "High", "Low", "Close"]
for c in required_cols:
if c not in df.columns:
raise ValueError(f"Column {c} not found in {csv_path}, columns={df.columns}")
# 5. 解析日期并设索引
# errors="coerce" 会把无法解析的字符串(如 "Ticker" 或 "Date" 等元数据行)变成 NaT
df["Date"] = pd.to_datetime(df["Date"], errors="coerce")
df = df.dropna(subset=["Date"])
df.set_index("Date", inplace=True)
# 6. 转换数值列为 float
for c in ["Open", "High", "Low", "Close"]:
df[c] = pd.to_numeric(df[c], errors="coerce")
# 7. 清洗
df = df.dropna(subset=["Open", "High", "Low", "Close"])
if len(df) < L_HIST + L_PRED:
print(f"Data too short for {ticker}")
return
print(f"Processing {ticker}...")
for start in tqdm(range(0, len(df) - L_HIST - L_PRED, L_PRED)):
render_sample(df, start, ticker)
except Exception as e:
print(f"Error processing {csv_path}: {e}")
if __name__ == "__main__":
# 遍历所有下载下来的 CSV
csv_files = list(RAW_DIR.glob("*.csv"))
if not csv_files:
print("No CSV files found in data/yahoo! Please run fetch_yahoo_data.py first.")
else:
for csv in csv_files:
process_one(csv)
print("Done! Charts saved in data/charts/")
|