You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:如何在算法交易策略中添加多证券支持

Handling Multiple Securities for Your Python Algorithmic Trading Strategy

Hey there! Making the jump from single-asset to multi-asset algo trading is a great next step—let's walk through how to adapt your existing code to handle multiple securities smoothly.


First, Recap Your Single-Asset Code

You're currently loading a single stock with:

import pandas as pd
data_p = pd.read_csv('AAPL_30m.csv', index_col=0, parse_dates=True)
data_p = data_p.drop(columns=['Adj Close'])  # Don't forget to assign the dropped result back!

(Quick note: You missed assigning the drop result back to data_p in your original code—fixed that above so the column actually gets removed.)


Method 1: Store Each Security's Data in a Dictionary

This is the most flexible approach if you want to run strategy logic on each asset individually, or access specific stocks later.

Step 1: Define Your List of Securities

You can either list tickers manually, or auto-detect CSV files in your folder:

import os
import pandas as pd

# Option 1: Manual ticker list
tickers = ['AAPL', 'MSFT', 'GOOG', 'AMZN']

# Option 2: Auto-detect all _30m.csv files in your current folder
tickers = [file.split('_')[0] for file in os.listdir('.') if file.endswith('_30m.csv')]

Step 2: Load All Data into a Dictionary

Loop through each ticker, load its CSV, clean it, and store it:

# Initialize an empty dictionary to hold each stock's DataFrame
stock_data = {}

for ticker in tickers:
    file_path = f"{ticker}_30m.csv"
    # Load data (same as your original code)
    df = pd.read_csv(file_path, index_col=0, parse_dates=True)
    # Drop Adj Close column (and assign back to df)
    df = df.drop(columns=['Adj Close'])
    # Store the cleaned DataFrame in the dictionary
    stock_data[ticker] = df

# Access individual stock data like this:
aapl_data = stock_data['AAPL']
msft_data = stock_data['MSFT']

Method 2: Combine All Data into a Single Multi-Index DataFrame

If you want to analyze or run calculations across all assets at once, merging into a single DataFrame with multi-level columns (ticker + price type) works great.

# Combine all DataFrames from the dictionary into one
combined_data = pd.concat(stock_data.values(), axis=1, keys=stock_data.keys())

# The column structure now looks like:
# (AAPL, Open), (AAPL, High), (AAPL, Low), (AAPL, Close), (AAPL, Volume),
# (MSFT, Open), (MSFT, High), ... etc.

# Access a specific stock's close price:
aapl_closes = combined_data['AAPL']['Close']

# Calculate a 20-period SMA for all stocks at once:
sma_20 = combined_data.xs('Close', level=1, axis=1).rolling(window=20).mean()

Pro Tip: Align Time Stamps

If different securities have missing time periods (e.g., one stock has data on a holiday another doesn't), use join='inner' to keep only time points present across all assets:

combined_data = pd.concat(stock_data.values(), axis=1, keys=stock_data.keys(), join='inner')

Running Strategy Logic on Multiple Securities

Once you have your data loaded (either via dictionary or combined DataFrame), you can loop through each asset to apply your strategy:

# Example: Calculate SMAs and generate signals for each stock
for ticker, df in stock_data.items():
    # Calculate 20-period and 50-period SMAs
    df['SMA_20'] = df['Close'].rolling(window=20).mean()
    df['SMA_50'] = df['Close'].rolling(window=50).mean()
    # Generate a simple crossover signal
    df['Signal'] = 0
    df.loc[df['SMA_20'] > df['SMA_50'], 'Signal'] = 1  # Buy signal
    df.loc[df['SMA_20'] < df['SMA_50'], 'Signal'] = -1 # Sell signal
    # Save the processed data if needed
    df.to_csv(f"{ticker}_strategy_data.csv")

Key Things to Check

  • Make sure all your CSV files have identical column names (Open, High, Low, Close, Volume, etc.)—otherwise merging/looping will break.
  • Double-check that the date index is parsed correctly (parse_dates=True ensures pandas treats the index as datetime objects, which is critical for time-based strategies).

内容的提问来源于stack exchange,提问作者user47409

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 23:47:31