如何用Python绘制大型CSV文件数据?Quandl股票可视化求助
Fix & Optimization for Your Quandl Stock Data Plotting Code
First off, let's break down the issues in your code that are causing it to fail, then build a working version that includes the features you need: selecting Date/Close Price columns and filtering the last 100 trading days.
Key Issues in Your Original Code
- Syntax Errors:
Withshould be lowercasewith(Python is case-sensitive)- You used Chinese quotation marks
‘rb’instead of English ones'rb' print rowis Python 2 syntax; useprint(row)for Python 3- You named a variable
csv, which overwrites the built-incsvmodule—this breaks all subsequent CSV operations
- Logical Missteps:
- You're repeatedly fetching the same Quandl URL multiple times (inefficient and unnecessary)
np.loadtxtcan't directly parse remote URLs with complex date formats correctly, and you set the wrong delimiter (Quandl uses commas, not spaces)- You tried to mix
csv.readerandcsv.writeron the same file handle, which will cause conflicts - No logic to filter the last 100 trading days
Fixed Version (Using Base Python Libraries)
This version fixes all bugs, fetches the data once, extracts Date/Close columns, filters the last 100 rows, and plots the data:
import urllib.request import csv import numpy as np import matplotlib.pyplot as plt from matplotlib import style from datetime import datetime style.use('fivethirtyeight') # Fetch data once and process directly (no need to save to file unless you want to) url = 'https://www.quandl.com/api/v3/datasets/EOD/V.csv?api_key=Fa1P1yZLGnGSsXktrvzL' response = urllib.request.urlopen(url) csv_data = response.read().decode('utf-8').splitlines() # Parse CSV, skip header, extract Date and Close columns reader = csv.reader(csv_data) next(reader) # Skip the header row rows = list(reader) # Filter last 100 trading days last_100_rows = rows[-100:] # Convert data to plot-ready formats dates = [] close_prices = [] for row in last_100_rows: # Parse Quandl's date format (YYYY-MM-DD) date_obj = datetime.strptime(row[0], '%Y-%m-%d') dates.append(date_obj) close_prices.append(float(row[4])) # Close price is the 5th column (0-based index 4) # Plot the data plt.figure(figsize=(10,6)) plt.plot(dates, close_prices, label='Visa Close Price') plt.title('Visa EOD Stock Prices (Last 100 Trading Days)') plt.ylabel('Stock Price (USD)') plt.xlabel('Date') plt.xticks(rotation=45) plt.legend() plt.tight_layout() # Fixes label cutoff issues plt.show()
Optimized Version (Using Pandas)
For time-series stock data, Pandas is far more efficient and readable. It handles date parsing, column selection, and filtering in just a few lines:
import pandas as pd import matplotlib.pyplot as plt from matplotlib import style style.use('fivethirtyeight') # Fetch and parse data directly with Pandas url = 'https://www.quandl.com/api/v3/datasets/EOD/V.csv?api_key=Fa1P1yZLGnGSsXktrvzL' df = pd.read_csv(url, parse_dates=['Date'], index_col='Date') # Select Close column and filter last 100 rows last_100_days = df['Close'].tail(100) # Plot plt.figure(figsize=(10,6)) last_100_days.plot(label='Visa Close Price') plt.title('Visa EOD Stock Prices (Last 100 Trading Days)') plt.ylabel('Stock Price (USD)') plt.xlabel('Date') plt.legend() plt.tight_layout() plt.show()
Quick Notes
- In the Quandl EOD dataset, the
Closecolumn is at index 4 (0-based) in the raw CSV - Pandas automatically parses dates and handles time-series indexing, which simplifies filtering with
tail(100) - Both versions avoid overwriting built-in module names (like
csv) to prevent conflicts
内容的提问来源于stack exchange,提问作者Ross Irving
相关产品推荐
相关产品推荐

