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

Python遍历多只股票数据处理后仅最后一只数据写入CSV的问题求助

Fix: Only Last Stock Data Saves to CSV When Processing Multiple Stocks

Hey there! Let's figure out why only your last stock's data is ending up in the CSV, and fix it right away.

What's Causing the Problem?

The issue lies in how you're storing your data with appended_data.update(dict).

You're creating a dictionary where keys are column names (like 'Stock Name', 'Open') and values are the columns from each stock's data. When you use update() on the appended_data dictionary, each subsequent stock's columns overwrite the existing keys (since dictionary keys must be unique). By the end of the loop, all keys point to the last stock's data, so your final DataFrame only has that one stock's info.

Also, using dict as a variable name isn't great—it's a built-in Python type, and reusing it can cause unexpected issues later.

Corrected Code

Here's the fixed version that preserves all stock data:

from numpy import array
import talib
import yfinance as yf
from tabulate import tabulate
import pandas as pd

stock_list=['ICICIBANK.NS','COALINDIA.NS','RELIANCE.NS']
appended_data = []  # Use a list to store individual stock DataFrames

for stock in stock_list:
    # Download stock data
    data = yf.download(stock, period='1y', interval='1d')
    
    # Calculate candlestick patterns
    morning_star = talib.CDLMORNINGSTAR(data['Open'], data['High'], data['Low'], data['Close'])
    two_crows = talib.CDL2CROWS(data['Open'], data['High'], data['Low'], data['Close'])
    three_crows = talib.CDL3BLACKCROWS(data['Open'], data['High'], data['Low'], data['Close'])
    
    # Add metadata and indicators to the DataFrame
    data['Stock Name'] = stock
    data['Morning Star'] = morning_star
    data['Two Crows'] = two_crows
    data['Three Black Crows'] = three_crows
    
    # Select only the columns we need (optional but keeps things clean)
    selected_columns = [
        'Stock Name', 'Open', 'High', 'Low', 'Close',
        'Morning Star', 'Two Crows', 'Three Black Crows'
    ]
    appended_data.append(data[selected_columns])  # Add the processed DataFrame to our list

# Combine all individual DataFrames into one
df = pd.concat(appended_data, ignore_index=False)

# Save the latest 5 rows to CSV
df_latest = df.tail(5)
df_latest.to_csv('Candlestick Screener Data.csv')

Key Changes Explained

  1. Switch from dictionary to list: Instead of overwriting keys, we store each stock's full processed DataFrame in a list. Lists let us keep multiple independent datasets without conflict.
  2. Use pd.concat() to merge data: This function takes our list of DataFrames and stacks them vertically, preserving all rows from every stock. Set ignore_index=True if you want a continuous integer index instead of keeping the original date indices.
  3. Avoid reserved variable names: We removed the dict variable and directly select columns from the original data DataFrame, preventing conflicts with Python's built-in dict type.

Now when you run the code, your CSV will include data from all three stocks, not just the last one!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 18:44:08