Python遍历多只股票数据处理后仅最后一只数据写入CSV的问题求助
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
- 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.
- Use
pd.concat()to merge data: This function takes our list of DataFrames and stacks them vertically, preserving all rows from every stock. Setignore_index=Trueif you want a continuous integer index instead of keeping the original date indices. - Avoid reserved variable names: We removed the
dictvariable and directly select columns from the originaldataDataFrame, preventing conflicts with Python's built-indicttype.
Now when you run the code, your CSV will include data from all three stocks, not just the last one!
内容的提问来源于stack exchange,提问作者Dev Shah

