FinMM-MultiModal-Forecasting / fin-mm /code /generate_kline_images.py
GoldenGrapeGentleman1's picture
Upload fin-mm before machine wipe (part 2)
bc200fc verified
Raw History Blame Contribute Delete
12.4 kB
"""
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)