Improve Alpha Vantage indicator column parsing with robust mapping

- Replace hardcoded column indices with column name lookup
- Add mapping for all supported indicators to their expected CSV column names
- Handle missing columns gracefully with descriptive error messages
- Strip whitespace from header parsing for reliability

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
luohy15
2025-09-26 23:36:36 +08:00
parent 8b04ec307f
commit 6211b1132a

View File

@@ -155,26 +155,30 @@ def get_indicator(
return f"Error: No data returned for {indicator}" return f"Error: No data returned for {indicator}"
# Parse header and data # Parse header and data
header = lines[0].split(',') header = [col.strip() for col in lines[0].split(',')]
date_col_idx = 0 # Assuming first column is date try:
value_col_idx = 1 # Default to second column date_col_idx = header.index('time')
except ValueError:
return f"Error: 'time' column not found in data for {indicator}. Available columns: {header}"
# Handle specific indicator column mappings # Map internal indicator names to expected CSV column names from Alpha Vantage
if indicator == "macds": col_name_map = {
# MACD Signal is typically in the third column "macd": "MACD", "macds": "MACD_Signal", "macdh": "MACD_Hist",
value_col_idx = 2 if len(header) > 2 else 1 "boll": "Real Middle Band", "boll_ub": "Real Upper Band", "boll_lb": "Real Lower Band",
elif indicator == "macdh": "rsi": "RSI", "atr": "ATR", "close_10_ema": "EMA",
# MACD Histogram is typically in the fourth column "close_50_sma": "SMA", "close_200_sma": "SMA"
value_col_idx = 3 if len(header) > 3 else 1 }
elif indicator == "boll_ub":
# Bollinger Upper Band is typically in the second column target_col_name = col_name_map.get(indicator)
if not target_col_name:
# Default to the second column if no specific mapping exists
value_col_idx = 1 value_col_idx = 1
elif indicator == "boll": else:
# Bollinger Middle is typically in the third column try:
value_col_idx = 2 if len(header) > 2 else 1 value_col_idx = header.index(target_col_name)
elif indicator == "boll_lb": except ValueError:
# Bollinger Lower Band is typically in the fourth column return f"Error: Column '{target_col_name}' not found for indicator '{indicator}'. Available columns: {header}"
value_col_idx = 3 if len(header) > 3 else 1
result_data = [] result_data = []
for line in lines[1:]: for line in lines[1:]: