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

Alpaca API迭代报错:list indices must be integers or slices, not Bar

解决‘list indices must be integers or slices, not Bar’错误

错误根源

使用Alpaca Markets API的get_bars接口传入多个symbol时,返回的daily_bars是MultiBars类型:

  • 直接执行for bar in daily_bars时,遍历得到的是单个Bar实体对象
  • 代码中尝试用daily_bars[bar]索引,而MultiBars仅支持整数、切片或symbol字符串作为索引,不能用Bar对象,这直接触发了报错。
  • 同时代码逻辑是要针对每个symbol的K线数据生成DataFrame并做条件判断,遍历单个Bar对象完全不符合需求。

修复后的代码

def get_tickers(api: tradeapi.REST):
    assets = api.list_assets(status="active", asset_class="us_equity")
    symbols = [asset.symbol for asset in assets if asset.tradable]
    
    '''Getting the list of symbols that can be traded'''
    start_time = (pd.to_datetime(datetime.now()) - pd.Timedelta("500000T")) 
    start_time = start_time.replace(second=0, microsecond=0).tz_localize('GMT').tz_convert('America/New_York')

    end_time = (pd.to_datetime(datetime.now()))
    end_time = end_time.replace(second=0, microsecond=0).tz_localize('GMT').tz_convert('America/New_York')
    limit = 250
    
    j = 0
    symbol_list = []
    price_list = []
    for i in tqdm(range(200, len(symbols)+1, 200)):
        get_symbols = symbols[j:i]
        daily_bars = api.get_bars(symbol=get_symbols, timeframe=TimeFrame.Day, start=start_time.isoformat(), end=end_time.isoformat(), limit=limit, adjustment='raw')
        
        # 遍历每个symbol,而非单个Bar对象
        for symbol in daily_bars:
            try:
                # 通过symbol字符串获取对应标的的所有K线数据
                bars = daily_bars[symbol]
                if not bars:
                    continue
                df = bars.df
                
                # macd_line = macd(df["close"], window_slow=26, window_fast=12, fillna=True)
                # macd_signal_line = macd_signal(df["close"], window_slow=26, window_fast=12, window_sign=9, fillna=True)
                sma200_line = sma_indicator(df["close"], window=200, fillna=True)
                
                cond_1 = df.iloc[-1]["close"] >= signal_min_share_price
                cond_2 = df.iloc[-1]["close"] <= signal_max_share_price
                cond_3 = df.iloc[-1]["close"] < round(sma200_line[-1],2)
                
                if cond_1 and cond_2 and cond_3:
                    symbol_list.append(symbol)
                    price_list.append(df.iloc[-1]["close"])
            except Exception as e:
                logging.warning(e)
                pass

        j = i
    symbols_to_trade_df = pd.DataFrame({
        "Stocks": symbol_list,
        "Price": price_list,
    })
    symbols_to_trade = symbols_to_trade_df.sort_values(['Price'], ascending=[False])
    symbols_to_trade = symbols_to_trade.reset_index(drop=True)
    print(symbols_to_trade[:20])
    print(start_time)
    print(end_time)
    return symbols_to_trade.loc[:, "Stocks"].to_list()

关键修复点

  • 遍历方式修正:将for bar in daily_bars改为for symbol in daily_bars,遍历MultiBars中的symbol键
  • 索引逻辑修正:用symbol字符串作为索引daily_bars[symbol]获取对应标的的K线集合,避免用Bar对象索引
  • 空值判断优化:将if daily_bars[bar] != []改为if not bars,更简洁判断标的是否有有效K线数据
  • 数据追加修正:条件满足时追加symbol字符串而非bar对象,符合后续生成DataFrame的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:10:19