File size: 5,610 Bytes
8346b41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Convert 1-minute data to higher timeframes (5m, 15m, 1h, 4h, daily).



This allows testing the same strategy on different timeframes to find

the optimal trading interval.

"""

import pandas as pd
import os
import sys

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import config


def resample_to_timeframe(df, timeframe):
    """

    Resample 1-minute OHLCV data to a higher timeframe.

    

    Parameters

    ----------

    df : pd.DataFrame

        1-minute OHLCV data with DatetimeIndex

    timeframe : str

        Pandas resample frequency: '5min', '15min', '1H', '4H', '1D'

        

    Returns

    -------

    pd.DataFrame

        Resampled OHLCV data

    """
    # Ensure index is datetime
    if not isinstance(df.index, pd.DatetimeIndex):
        df = df.set_index('timestamp')
    
    # Resample OHLCV data
    resampled = df.resample(timeframe).agg({
        'open': 'first',
        'high': 'max',
        'low': 'min',
        'close': 'last',
        'volume': 'sum'
    }).dropna()
    
    return resampled


def create_all_timeframes(source_file):
    """

    Create datasets for all timeframes from 1-minute source data.

    

    Parameters

    ----------

    source_file : str

        Path to 1-minute CSV file

        

    Returns

    -------

    dict

        Dictionary of {timeframe: output_file_path}

    """
    print("\n" + "="*70)
    print("CREATING MULTI-TIMEFRAME DATASETS")
    print("="*70)
    
    # Load source data
    print(f"\n๐Ÿ“ฅ Loading source data: {source_file}")
    df = pd.read_csv(source_file)
    df['timestamp'] = pd.to_datetime(df['timestamp'])
    df = df.set_index('timestamp')
    
    print(f"   Loaded {len(df):,} 1-minute candles")
    print(f"   Period: {df.index[0]} to {df.index[-1]}")
    
    # Define timeframes to create
    timeframes = {
        '5min': '5-minute',
        '15min': '15-minute',
        '30min': '30-minute',
        '1H': '1-hour',
        '4H': '4-hour',
        '1D': 'daily'
    }
    
    output_files = {}
    
    for tf_code, tf_name in timeframes.items():
        print(f"\n๐Ÿ”„ Creating {tf_name} dataset...")
        
        # Resample
        resampled = resample_to_timeframe(df, tf_code)
        
        # Save
        output_file = os.path.join(
            config.DATA_DIR, 
            f"btc_{tf_code.lower()}_binance.csv"
        )
        
        # Reset index to have timestamp as column
        resampled = resampled.reset_index()
        resampled.to_csv(output_file, index=False)
        
        output_files[tf_name] = output_file
        
        print(f"   โœ“ Created {len(resampled):,} {tf_name} candles")
        print(f"   โœ“ Saved to: {output_file}")
    
    return output_files


def estimate_trades_per_timeframe():
    """Display estimated trades per day for each timeframe."""
    print("\n" + "="*70)
    print("ESTIMATED TRADING CHARACTERISTICS BY TIMEFRAME")
    print("="*70)
    
    print("\nBased on current parameters (MA 15/60, ~2 trades/day on 1-min):\n")
    
    timeframes = [
        ("1-minute", 1, "~2 trades/day", "High frequency, many signals"),
        ("5-minute", 5, "~8-12 trades/week", "Active intraday"),
        ("15-minute", 15, "~2-4 trades/week", "Swing trading"),
        ("30-minute", 30, "~1-2 trades/week", "Position trading"),
        ("1-hour", 60, "~5-10 trades/month", "Low frequency"),
        ("4-hour", 240, "~1-3 trades/month", "Very selective"),
        ("Daily", 1440, "~2-6 trades/year", "Long-term holds")
    ]
    
    print(f"{'Timeframe':<15} {'Candle (min)':<15} {'Frequency':<20} {'Style'}")
    print("-" * 70)
    for tf, mins, freq, style in timeframes:
        print(f"{tf:<15} {mins:<15} {freq:<20} {style}")
    
    print("\n๐Ÿ’ก Hypothesis:")
    print("   - Longer timeframes = Less noise, fewer false signals")
    print("   - Better win rate but fewer opportunities")
    print("   - May need to adjust MA periods (15/60 โ†’ 10/30 or 20/80)")


def main():
    """Main execution."""
    print("\n๐ŸŒ MULTI-TIMEFRAME DATA CREATOR")
    
    # Use the 2-year Binance data as source
    source_file = os.path.join(config.DATA_DIR, "btc_1m_binance_730d.csv")
    
    if not os.path.exists(source_file):
        print(f"\nโœ— Source file not found: {source_file}")
        print(f"   Please ensure you have 1-minute data available.")
        return
    
    # Create all timeframes
    output_files = create_all_timeframes(source_file)
    
    # Show characteristics
    estimate_trades_per_timeframe()
    
    print("\n" + "="*70)
    print("โœ… MULTI-TIMEFRAME DATASETS CREATED")
    print("="*70)
    
    print("\n๐Ÿ“ Created files:")
    for tf_name, filepath in output_files.items():
        print(f"   - {tf_name}: {filepath}")
    
    print("\n๐Ÿ’ก Next steps:")
    print("  1. Test current parameters on each timeframe:")
    print("     - Update config.py to use each timeframe file")
    print("     - Run: python run_backtest.py")
    print("     - Compare results")
    print("\n  2. Optimize parameters per timeframe:")
    print("     - Run: python optimize_parameters.py (for each TF)")
    print("     - Find best settings for each interval")
    print("\n  3. Compare performance:")
    print("     - Which timeframe gives best Sharpe ratio?")
    print("     - Which has best win rate?")
    print("     - Which has lowest drawdown?")
    
    print("="*70 + "\n")


if __name__ == "__main__":
    main()