File size: 14,008 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
"""

Paired Dataset Generator for Multi-Modal Financial Time Series Prediction.



Generates paired (time_series_csv, kline_image_png) samples that are 

precisely aligned for LLaVA + DMMV multi-modal fusion training.



Key Guarantee:

    - Each sample has EXACTLY matched time window between CSV and PNG

    - Filename encodes the exact date range for verification

    - Sample ID enables 1:1 correspondence during training



Data Structure per Sample:

    sample_id: AAPL_20180102_20180420

    β”œβ”€β”€ timeseries/AAPL_20180102_20180420.csv  (96 days OHLCV input)

    β”œβ”€β”€ kline_img/AAPL_20180102_20180420.png   (96 days candlestick)

    └── target: next 20 days Close prices



Prediction Tasks:

    - pred5:  96d input -> 5d prediction

    - pred20: 96d input -> 20d prediction

    - pred60: 120d input -> 60d prediction

"""

import pandas as pd
from pathlib import Path
from datetime import datetime
import json
import argparse
import warnings
warnings.filterwarnings('ignore')

# Lazy import matplotlib (only when generating images)
plt = None
Rectangle = None

def _import_matplotlib():
    global plt, Rectangle
    if plt is None:
        import matplotlib.pyplot as _plt
        from matplotlib.patches import Rectangle as _Rectangle
        plt = _plt
        Rectangle = _Rectangle

# =============================================================================
# Configuration
# =============================================================================

# Input/Output directories
DATA_DIR = Path("data/yahoo")
OUTPUT_DIR = Path("data/paired_dataset")

# Image settings (LLaVA ViT-L/14-336)
FIGSIZE = (3.36, 3.36)
DPI = 100  # 336x336 pixels

# Prediction task configurations
TASKS = {
    "pred5": {"input_days": 96, "pred_days": 5},
    "pred10": {"input_days": 96, "pred_days": 10},
    "pred20": {"input_days": 96, "pred_days": 20},
    "pred60": {"input_days": 120, "pred_days": 60},
}

# Default settings
DEFAULT_TASK = "pred20"
DEFAULT_STRIDE = 5

# Chart colors
COLORS = {
    'up': '#26A69A',
    'down': '#EF5350',
    'background': 'white',
}


# =============================================================================
# Candlestick Drawing
# =============================================================================

def draw_candlestick(ax, df: pd.DataFrame):
    """Draw candlestick chart on axes."""
    _import_matplotlib()
    width = 0.6
    
    for idx in range(len(df)):
        row = df.iloc[idx]
        o, h, l, c = row['Open'], row['High'], row['Low'], row['Close']
        
        color = COLORS['up'] if c >= o else COLORS['down']
        bottom = min(o, c)
        height = abs(c - o)
        
        # Candle body
        rect = Rectangle((idx - width/2, bottom), width, height,
                         facecolor=color, edgecolor=color, linewidth=0.5)
        ax.add_patch(rect)
        
        # Wicks
        ax.plot([idx, idx], [l, h], color=color, linewidth=0.8)
    
    ax.set_xlim(-1, len(df))
    y_min, y_max = df['Low'].min(), 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) -> bool:
    """Generate candlestick image from OHLCV data."""
    _import_matplotlib()
    try:
        fig, ax = plt.subplots(1, 1, figsize=FIGSIZE)
        fig.patch.set_facecolor(COLORS['background'])
        ax.set_facecolor(COLORS['background'])
        
        draw_candlestick(ax, df)
        
        # Clean style
        ax.set_xticks([])
        ax.set_yticks([])
        for spine in ax.spines.values():
            spine.set_visible(False)
        ax.grid(True, alpha=0.2)
        
        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:
        plt.close('all')
        return False


# =============================================================================
# Paired Dataset Generation
# =============================================================================

def generate_paired_samples(

    ticker: str,

    task: str = DEFAULT_TASK,

    stride: int = DEFAULT_STRIDE,

    split_ratios: dict = None

) -> dict:
    """

    Generate paired (CSV, PNG) samples for a ticker.

    

    Args:

        ticker: Stock/crypto symbol

        task: Prediction task name (pred5, pred20, pred60)

        stride: Days between samples

        split_ratios: Train/val/test split dates

        

    Returns:

        Dictionary with sample counts per split

    """
    if split_ratios is None:
        split_ratios = {
            'train': ('2018-01-01', '2022-12-31'),
            'val': ('2023-01-01', '2023-12-31'),
            'test': ('2024-01-01', '2026-12-31'),
        }
    
    # Load data
    data_path = DATA_DIR / f"{ticker}_1d.csv"
    if not data_path.exists():
        print(f"  [ERROR] Data not found: {data_path}")
        return {}
    
    df = pd.read_csv(data_path)
    df['Date'] = pd.to_datetime(df['Date'])
    
    # Get task config
    task_config = TASKS.get(task, TASKS[DEFAULT_TASK])
    input_days = task_config['input_days']
    pred_days = task_config['pred_days']
    window_size = input_days + pred_days
    
    # Create output directories
    for split in ['train', 'val', 'test']:
        (OUTPUT_DIR / split / "timeseries").mkdir(parents=True, exist_ok=True)
        (OUTPUT_DIR / split / "kline_img").mkdir(parents=True, exist_ok=True)
    
    # Track samples
    sample_counts = {'train': 0, 'val': 0, 'test': 0}
    sample_index = []  # For manifest file
    
    # Generate samples with sliding window
    for i in range(0, len(df) - window_size + 1, stride):
        # Extract window
        input_df = df.iloc[i:i + input_days].copy()
        target_df = df.iloc[i + input_days:i + window_size].copy()
        
        # Get date range
        start_date = input_df['Date'].iloc[0]
        end_date = input_df['Date'].iloc[-1]
        
        # Determine split based on END date of input window
        split = None
        for split_name, (split_start, split_end) in split_ratios.items():
            if pd.to_datetime(split_start) <= end_date <= pd.to_datetime(split_end):
                split = split_name
                break
        
        if split is None:
            continue
        
        # Create sample ID
        start_str = start_date.strftime('%Y%m%d')
        end_str = end_date.strftime('%Y%m%d')
        sample_id = f"{ticker}_{start_str}_{end_str}"
        
        # Output paths
        csv_path = OUTPUT_DIR / split / "timeseries" / f"{sample_id}.csv"
        png_path = OUTPUT_DIR / split / "kline_img" / f"{sample_id}.png"
        
        # Check if already exists
        already_exists = csv_path.exists() and png_path.exists()
        
        if not already_exists:
            # Save time series CSV (input window only)
            input_df_save = input_df[['Date', 'Open', 'High', 'Low', 'Close', 'Volume']].copy()
            input_df_save['Date'] = input_df_save['Date'].dt.strftime('%Y-%m-%d')
            input_df_save.to_csv(csv_path, index=False)
            
            # Generate K-line image
            if not generate_kline_image(input_df, png_path):
                continue
        
        # Record sample info (always, even if files existed)
        sample_info = {
            'sample_id': sample_id,
            'ticker': ticker,
            'split': split,
            'input_start': start_date.strftime('%Y-%m-%d'),
            'input_end': end_date.strftime('%Y-%m-%d'),
            'input_days': input_days,
            'target_start': target_df['Date'].iloc[0].strftime('%Y-%m-%d'),
            'target_end': target_df['Date'].iloc[-1].strftime('%Y-%m-%d'),
            'target_days': pred_days,
            'target_close': target_df['Close'].tolist(),
            'csv_path': str(csv_path.relative_to(OUTPUT_DIR)),
            'png_path': str(png_path.relative_to(OUTPUT_DIR)),
        }
        sample_index.append(sample_info)
        sample_counts[split] += 1
    
    return sample_counts, sample_index


def save_manifest(all_samples: list, task: str):
    """Save manifest file with all sample information."""
    manifest = {
        'task': task,
        'task_config': TASKS[task],
        'created': datetime.now().isoformat(),
        'total_samples': len(all_samples),
        'splits': {
            'train': [s for s in all_samples if s['split'] == 'train'],
            'val': [s for s in all_samples if s['split'] == 'val'],
            'test': [s for s in all_samples if s['split'] == 'test'],
        }
    }
    
    # Save full manifest
    manifest_path = OUTPUT_DIR / f"manifest_{task}.json"
    with open(manifest_path, 'w') as f:
        json.dump(manifest, f, indent=2)
    
    # Save split-specific files for easy loading
    for split in ['train', 'val', 'test']:
        split_samples = manifest['splits'][split]
        split_path = OUTPUT_DIR / split / f"samples_{task}.json"
        with open(split_path, 'w') as f:
            json.dump(split_samples, f, indent=2)
    
    print(f"\nManifest saved: {manifest_path}")
    return manifest


# =============================================================================
# Main Entry Point
# =============================================================================

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Generate paired (CSV, PNG) dataset for multi-modal training"
    )
    parser.add_argument(
        '--tickers', nargs='+',
        default=['SPY', 'AAPL', 'MSFT', 'GOOGL', 'AMZN', 'BTC-USD', 'ETH-USD'],
        help='Ticker symbols to process'
    )
    parser.add_argument(
        '--task', choices=['pred5', 'pred10', 'pred20', 'pred60'], default=DEFAULT_TASK,
        help=f'Prediction task (default: {DEFAULT_TASK})'
    )
    parser.add_argument(
        '--stride', type=int, default=DEFAULT_STRIDE,
        help=f'Days between samples (default: {DEFAULT_STRIDE})'
    )
    parser.add_argument(
        '--estimate-only', action='store_true',
        help='Only estimate, do not generate'
    )
    
    args = parser.parse_args()
    
    task_config = TASKS[args.task]
    
    print("=" * 70)
    print("Paired Dataset Generator (Time Series CSV + K-line PNG)")
    print("=" * 70)
    print(f"Task: {args.task}")
    print(f"  - Input window: {task_config['input_days']} days")
    print(f"  - Prediction: {task_config['pred_days']} days")
    print(f"Stride: {args.stride} days")
    print(f"Tickers: {args.tickers}")
    print(f"Output: {OUTPUT_DIR.absolute()}")
    print("=" * 70)
    
    # Estimate storage
    print("\nEstimated samples per ticker:")
    total_estimate = 0
    for ticker in args.tickers:
        data_path = DATA_DIR / f"{ticker}_1d.csv"
        if data_path.exists():
            df = pd.read_csv(data_path)
            window = task_config['input_days'] + task_config['pred_days']
            samples = max(0, (len(df) - window) // args.stride + 1)
            print(f"  {ticker}: ~{samples} samples")
            total_estimate += samples
    
    csv_size = 5  # KB per CSV
    png_size = 75  # KB per PNG
    total_size_mb = total_estimate * (csv_size + png_size) / 1024
    
    print(f"\nTotal: ~{total_estimate} samples")
    print(f"Estimated size: ~{total_size_mb:.1f} MB")
    print("  - CSV files: ~{:.1f} MB".format(total_estimate * csv_size / 1024))
    print("  - PNG files: ~{:.1f} MB".format(total_estimate * png_size / 1024))
    print("=" * 70)
    
    if args.estimate_only:
        print("\n[Estimate only - no files generated]")
        exit(0)
    
    # Generate paired samples
    print("\nGenerating paired samples...")
    all_samples = []
    total_counts = {'train': 0, 'val': 0, 'test': 0}
    
    for idx, ticker in enumerate(args.tickers):
        print(f"\n[{idx+1}/{len(args.tickers)}] Processing {ticker}...")
        counts, samples = generate_paired_samples(
            ticker=ticker,
            task=args.task,
            stride=args.stride
        )
        
        if counts:
            for split, count in counts.items():
                total_counts[split] += count
            all_samples.extend(samples)
            print(f"  Train: {counts.get('train', 0)}, "
                  f"Val: {counts.get('val', 0)}, "
                  f"Test: {counts.get('test', 0)}")
    
    # Save manifest
    manifest = save_manifest(all_samples, args.task)
    
    # Summary
    print("\n" + "=" * 70)
    print("Generation Complete!")
    print("=" * 70)
    print(f"\nSample counts:")
    print(f"  Train: {total_counts['train']}")
    print(f"  Val:   {total_counts['val']}")
    print(f"  Test:  {total_counts['test']}")
    print(f"  Total: {sum(total_counts.values())}")
    
    print(f"\nOutput structure:")
    print(f"  {OUTPUT_DIR}/")
    print(f"  +-- train/")
    print(f"  |   +-- timeseries/  (*.csv)")
    print(f"  |   +-- kline_img/   (*.png)")
    print(f"  |   +-- samples_{args.task}.json")
    print(f"  +-- val/")
    print(f"  |   +-- ...")
    print(f"  +-- test/")
    print(f"  |   +-- ...")
    print(f"  +-- manifest_{args.task}.json")
    
    print("\n" + "=" * 70)
    print("ALIGNMENT GUARANTEE:")
    print("  Each sample_id (e.g., AAPL_20180102_20180420) has:")
    print("    - timeseries/AAPL_20180102_20180420.csv (96 days OHLCV)")
    print("    - kline_img/AAPL_20180102_20180420.png  (same 96 days chart)")
    print("  [OK] Time windows are EXACTLY matched!")
    print("=" * 70)