File size: 12,360 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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 | """
Candlestick Chart Generator for LLaVA-Plus Multi-Modal Fusion.
Generates K-line (candlestick) charts from OHLCV time series data using
a sliding window approach. Charts are aligned with the input window of
prediction tasks.
Key Features:
- Sliding window generation with configurable stride
- Resolution: 336x336 (matches LLaVA ViT-L/14-336)
- Stride control to balance data coverage and storage
Prediction Task Alignment:
- pred5: 96 days input -> 5 days prediction
- pred20: 96 days input -> 20 days prediction
- pred60: 120 days input -> 60 days prediction
Storage Estimation (per ticker):
- stride=1: ~2,800 images Γ 75KB = ~210 MB
- stride=5: ~560 images Γ 75KB = ~42 MB (recommended)
- stride=20: ~140 images Γ 75KB = ~10.5 MB
"""
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.patches import Rectangle
from pathlib import Path
from datetime import datetime
import argparse
import warnings
warnings.filterwarnings('ignore')
# =============================================================================
# Configuration
# =============================================================================
# Directories
DATA_DIR = Path("data/yahoo")
OUTPUT_DIR = Path("data/yahoo_kline_images")
# Image settings (LLaVA ViT-L/14-336 requirement)
FIGSIZE = (3.36, 3.36) # inches
DPI = 100 # 3.36 * 100 = 336 pixels
# Prediction task configurations
TASKS = {
"pred5": {"input_days": 96, "pred_days": 5},
"pred20": {"input_days": 96, "pred_days": 20},
"pred60": {"input_days": 120, "pred_days": 60},
}
# Default stride (every N days generate one chart)
DEFAULT_STRIDE = 5 # ~5 trading days = 1 week
# Chart style
COLORS = {
'up': '#26A69A', # Green for bullish
'down': '#EF5350', # Red for bearish
'background': 'white',
'grid': '#E0E0E0',
}
# =============================================================================
# Candlestick Drawing (Custom Implementation)
# =============================================================================
def draw_candlestick(ax, df: pd.DataFrame):
"""
Draw candlestick chart on matplotlib axes.
Args:
ax: Matplotlib axes object
df: DataFrame with Open, High, Low, Close columns
"""
width = 0.6
width2 = 0.1
for idx, (i, row) in enumerate(df.iterrows()):
open_price = row['Open']
close_price = row['Close']
high_price = row['High']
low_price = row['Low']
# Determine color
if close_price >= open_price:
color = COLORS['up']
bottom = open_price
height = close_price - open_price
else:
color = COLORS['down']
bottom = close_price
height = open_price - close_price
# Draw candle body
rect = Rectangle(
(idx - width/2, bottom), width, height,
facecolor=color, edgecolor=color, linewidth=0.5
)
ax.add_patch(rect)
# Draw wicks (high-low line)
ax.plot([idx, idx], [low_price, high_price],
color=color, linewidth=0.8)
# Set x-axis limits
ax.set_xlim(-1, len(df))
# Set y-axis limits with padding
y_min = df['Low'].min()
y_max = df['High'].max()
y_range = y_max - y_min
ax.set_ylim(y_min - 0.05 * y_range, y_max + 0.05 * y_range)
def generate_kline_image(df: pd.DataFrame, output_path: Path,
show_volume: bool = False) -> bool:
"""
Generate a single candlestick chart image.
Args:
df: DataFrame with OHLCV data for the window
output_path: Path to save the image
show_volume: Whether to include volume subplot
Returns:
True if successful, False otherwise
"""
try:
if show_volume:
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=FIGSIZE,
gridspec_kw={'height_ratios': [3, 1]})
else:
fig, ax1 = plt.subplots(1, 1, figsize=FIGSIZE)
# Set background
fig.patch.set_facecolor(COLORS['background'])
ax1.set_facecolor(COLORS['background'])
# Draw candlesticks
draw_candlestick(ax1, df)
# Style the chart
ax1.grid(True, alpha=0.3, color=COLORS['grid'])
ax1.set_xticks([])
ax1.set_yticks([])
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
ax1.spines['left'].set_visible(False)
# Draw volume if requested
if show_volume:
ax2.set_facecolor(COLORS['background'])
colors = [COLORS['up'] if df.iloc[i]['Close'] >= df.iloc[i]['Open']
else COLORS['down'] for i in range(len(df))]
ax2.bar(range(len(df)), df['Volume'], color=colors, width=0.6)
ax2.set_xlim(-1, len(df))
ax2.set_xticks([])
ax2.set_yticks([])
ax2.spines['top'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
ax2.spines['left'].set_visible(False)
# Save image
plt.tight_layout(pad=0.1)
fig.savefig(output_path, dpi=DPI, bbox_inches='tight',
pad_inches=0.02, facecolor=COLORS['background'])
plt.close(fig)
return True
except Exception as e:
print(f" Error: {e}")
plt.close('all')
return False
# =============================================================================
# Sliding Window Generation
# =============================================================================
def generate_sliding_window_klines(
ticker: str,
input_days: int = 96,
stride: int = DEFAULT_STRIDE,
show_volume: bool = False
) -> int:
"""
Generate candlestick charts using sliding window.
Args:
ticker: Stock/crypto ticker symbol
input_days: Number of days in each chart (matches model input)
stride: Step size between windows (days)
show_volume: Include volume in charts
Returns:
Number of charts generated
"""
# Load data
data_path = DATA_DIR / f"{ticker}_1d.csv"
if not data_path.exists():
print(f" Data file not found: {data_path}")
return 0
df = pd.read_csv(data_path)
# Ensure required columns
required_cols = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
if not all(col in df.columns for col in required_cols):
print(f" Missing required columns in {ticker}")
return 0
# Create output directory
output_subdir = OUTPUT_DIR / ticker / f"window{input_days}_stride{stride}"
output_subdir.mkdir(parents=True, exist_ok=True)
# Generate charts with sliding window
total_windows = (len(df) - input_days) // stride + 1
generated = 0
print(f" Generating {total_windows} charts for {ticker}...")
for i in range(0, len(df) - input_days + 1, stride):
window_df = df.iloc[i:i + input_days].reset_index(drop=True)
# Create filename with date range
start_date = window_df['Date'].iloc[0]
end_date = window_df['Date'].iloc[-1]
# Clean date format for filename
start_date_str = start_date.replace('-', '')
end_date_str = end_date.replace('-', '')
filename = f"{ticker}_{start_date_str}_{end_date_str}.png"
output_path = output_subdir / filename
# Skip if already exists
if output_path.exists():
generated += 1
continue
# Generate chart
if generate_kline_image(window_df, output_path, show_volume):
generated += 1
# Progress update
if generated % 100 == 0 and generated > 0:
print(f" Progress: {generated}/{total_windows}")
return generated
def estimate_storage(tickers: list, input_days: int, stride: int) -> dict:
"""
Estimate storage requirements before generation.
Args:
tickers: List of ticker symbols
input_days: Window size
stride: Step size
Returns:
Dictionary with estimates
"""
total_charts = 0
estimates = {}
for ticker in tickers:
data_path = DATA_DIR / f"{ticker}_1d.csv"
if data_path.exists():
df = pd.read_csv(data_path)
num_charts = max(0, (len(df) - input_days) // stride + 1)
estimates[ticker] = num_charts
total_charts += num_charts
avg_size_kb = 75 # Approximate size per image
total_size_mb = (total_charts * avg_size_kb) / 1024
return {
'per_ticker': estimates,
'total_charts': total_charts,
'estimated_size_mb': total_size_mb
}
# =============================================================================
# Main Entry Point
# =============================================================================
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Generate candlestick charts for LLaVA-Plus"
)
parser.add_argument(
'--tickers', nargs='+',
default=['SPY', 'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'BTC-USD', 'ETH-USD'],
help='Ticker symbols to process'
)
parser.add_argument(
'--input-days', type=int, default=96,
help='Number of days per chart (default: 96 for pred5/pred20)'
)
parser.add_argument(
'--stride', type=int, default=DEFAULT_STRIDE,
help=f'Days between windows (default: {DEFAULT_STRIDE})'
)
parser.add_argument(
'--volume', action='store_true',
help='Include volume subplot in charts'
)
parser.add_argument(
'--estimate-only', action='store_true',
help='Only show storage estimates, do not generate'
)
args = parser.parse_args()
print("=" * 60)
print("Candlestick Chart Generator for LLaVA-Plus")
print("=" * 60)
print(f"Input window: {args.input_days} days")
print(f"Stride: {args.stride} days")
print(f"Tickers: {args.tickers}")
print(f"Include volume: {args.volume}")
print(f"Output: {OUTPUT_DIR.absolute()}")
print("=" * 60)
# Estimate storage
estimates = estimate_storage(args.tickers, args.input_days, args.stride)
print("\nStorage Estimates:")
for ticker, count in estimates['per_ticker'].items():
print(f" {ticker}: {count} charts")
print(f"\nTotal: {estimates['total_charts']} charts")
print(f"Estimated size: ~{estimates['estimated_size_mb']:.1f} MB")
print("=" * 60)
if args.estimate_only:
print("\n[Estimate only mode - no charts generated]")
exit(0)
# Confirm before proceeding
print("\nGenerating charts...")
# Generate charts
total_generated = 0
for ticker in args.tickers:
print(f"\n[{args.tickers.index(ticker)+1}/{len(args.tickers)}] {ticker}")
count = generate_sliding_window_klines(
ticker=ticker,
input_days=args.input_days,
stride=args.stride,
show_volume=args.volume
)
print(f" Generated: {count} charts")
total_generated += count
print("\n" + "=" * 60)
print("Generation Complete!")
print("=" * 60)
print(f"Total charts: {total_generated}")
print(f"Output directory: {OUTPUT_DIR.absolute()}")
print("\nDirectory structure:")
print(f" {OUTPUT_DIR}/")
print(f" βββ AAPL/window{args.input_days}_stride{args.stride}/")
print(f" βββ MSFT/window{args.input_days}_stride{args.stride}/")
print(f" βββ ...")
print("=" * 60)
|