如何用Pandas将Python列表中的1分钟K线数据重采样为15分钟数据?
Got it, converting 1-minute K-line data to 15-minute intervals is a common task in financial data processing. Let's walk through two practical approaches—one using pandas (the most efficient, recommended method) and a manual implementation if you prefer avoiding external libraries.
Approach 1: Using Pandas (Recommended)
Pandas has built-in time-series resampling tools that make this task straightforward. Here's a step-by-step solution:
Full Code Implementation
import pandas as pd # Your raw 1-minute K-line data raw_data = [ '1606470300000,244.25,244.25,244.00,244.00,489269', '1606470360000,244.05,244.30,244.00,244.15,452854', '1606470420000,244.15,244.20,244.00,244.10,403043', '1606470480000,244.15,244.15,243.95,244.00,370182', '1606470540000,244.05,244.20,244.00,244.15,445286', '1606470600000,244.15,244.25,244.05,244.20,473342', '1606470660000,244.25,244.35,244.00,244.05,491117', '1606470720000,244.05,244.20,244.00,244.20,298261', '1606470780000,244.20,244.25,244.10,244.25,344172', '1606470840000,244.20,244.35,244.20,244.30,347080', '1606470900000,244.30,244.40,244.25,244.30,447630', '1606470960000,244.30,244.30,244.00,244.00,360666', '1606471020000,244.05,244.15,243.95,243.95,467724', '1606471080000,243.95,244.10,243.70,244.00,386080', '1606471140000,244.00,244.20,243.70,244.20,166559' ] # Parse raw strings into a structured DataFrame df = pd.DataFrame([row.split(',') for row in raw_data], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) # Convert data types to appropriate formats df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms') df[['open', 'high', 'low', 'close', 'volume']] = df[['open', 'high', 'low', 'close', 'volume']].apply(pd.to_numeric) # Set timestamp as index (required for resampling) df.set_index('timestamp', inplace=True) # Resample to 15-minute intervals and compute OHLCV values fifteen_minute_bars = df.resample('15T').agg({ 'open': 'first', # First price in the 15-minute window 'high': 'max', # Highest price in the window 'low': 'min', # Lowest price in the window 'close': 'last', # Last price in the window 'volume': 'sum' # Total volume traded in the window }) # Reset index to get timestamp back as a column, convert to ms format fifteen_minute_bars.reset_index(inplace=True) fifteen_minute_bars['timestamp'] = fifteen_minute_bars['timestamp'].astype(int) // 10**6 # Output in the original string format result = fifteen_minute_bars.to_csv(sep=',', index=False, header=False) print(result)
Key Details:
- Data Parsing: We split each raw string into columns and convert timestamps to datetime objects, while prices/volume are converted to numeric types for calculations.
- Resampling Logic:
resample('15T')groups data into 15-minute chunks. Theagg()method defines how to compute each field:open: First price of the intervalhigh: Maximum price during the intervallow: Minimum price during the intervalclose: Last price of the intervalvolume: Sum of all volumes in the interval
- Formatting: We convert the timestamp back to milliseconds to match your original data structure.
Approach 2: Manual Implementation (No Pandas)
If you want full control without relying on external libraries, here's a manual grouping solution:
import datetime raw_data = [ # Your raw data here (same as above) ] # Parse raw data into typed dictionaries parsed_entries = [] for row in raw_data: ts_str, o, h, l, c, v = row.split(',') parsed_entries.append({ 'timestamp': int(ts_str), 'open': float(o), 'high': float(h), 'low': float(l), 'close': float(c), 'volume': int(v) }) # Helper function to get the start of the 15-minute interval for a timestamp def get_interval_start(ts_ms): dt = datetime.datetime.fromtimestamp(ts_ms / 1000) # Round down to the nearest 15 minutes interval_start = dt - datetime.timedelta( minutes=dt.minute % 15, seconds=dt.second, microseconds=dt.microsecond ) return int(interval_start.timestamp() * 1000) # Group entries by their 15-minute interval interval_groups = {} for entry in parsed_entries: interval_key = get_interval_start(entry['timestamp']) if interval_key not in interval_groups: # Initialize group with first entry's values interval_groups[interval_key] = { 'open': entry['open'], 'high': entry['high'], 'low': entry['low'], 'close': entry['close'], 'volume': entry['volume'] } else: # Update group values with current entry group = interval_groups[interval_key] group['high'] = max(group['high'], entry['high']) group['low'] = min(group['low'], entry['low']) group['close'] = entry['close'] group['volume'] += entry['volume'] # Convert groups back to the original string format fifteen_minute_data = [] for ts in sorted(interval_groups.keys()): group = interval_groups[ts] line = f"{ts},{group['open']},{group['high']},{group['low']},{group['close']},{group['volume']}" fifteen_minute_data.append(line) # Print the result for line in fifteen_minute_data: print(line)
Key Details:
- Interval Calculation: The
get_interval_start()function rounds each timestamp down to the start of its 15-minute window (e.g., 10:07 becomes 10:00 for a 15-minute interval). - Group Aggregation: We iterate through each entry, updating the interval group's high, low, close, and volume values as we go.
- Output: Finally, we convert the grouped data back to your original string format.
Both methods will produce the 15-minute K-line data you need. The pandas approach is better for large datasets, while the manual method is great for learning or environments where external libraries aren't available.
内容的提问来源于stack exchange,提问作者Amit Sharma

