如何运行脚本按指定股票代码和日期计算VWAP?
VWAP脚本指定股票代码和日期问题解决指导
问题描述
我使用某Stack Overflow回答中的脚本计算VWAP,已完成Python、pip及requests、pandas模块的安装,脚本可正常运行并输出数据,但存在以下问题:
- 无法指定特定股票代码(如
SPY)和日期(如12/06/2022); - 无论是否传入股票代码参数,输出结果完全一致。
运行python3 vwap.py SPY的输出如下:
python3 vwap.py SPY Open High Low Close volume Date vwap Time 2022-12-07 06:46:00 16975.0 16975.1 16975.0 16975.1 0.091722 2022-12-07 16975.066667 2022-12-07 06:47:00 16975.1 16975.1 16970.1 16970.1 0.356965 2022-12-07 16972.441261 2022-12-07 06:48:00 16970.1 16970.2 16970.1 16970.2 0.506126 2022-12-07 16971.235547 2022-12-07 06:49:00 16970.1 16970.2 16970.1 16970.2 0.019041 2022-12-07 16971.214648 2022-12-07 06:50:00 16970.2 16970.2 16955.4 16957.5 3.832814 2022-12-07 16963.096116 ... ... ... ... ... ... ... ... 2022-12-07 18:41:00 16804.4 16804.4 16804.4 16804.4 0.471748 2022-12-07 16812.490887 2022-12-07 18:42:00 16804.4 16810.4 16804.4 16807.3 6.735564 2022-12-07 16812.464360 2022-12-07 18:43:00 16808.7 16812.1 16805.5 16805.5 3.790436 2022-12-07 16812.450520 2022-12-07 18:44:00 16805.6 16808.7 16803.0 16803.0 0.827792 2022-12-07 16812.445734 2022-12-07 18:45:00 16803.0 16803.0 16803.0 16803.0 0.000000 2022-12-07 16812.445734 [720 rows x 7 columns]
问题根源
原脚本未读取命令行传入的股票代码参数,也未添加日期筛选逻辑,始终使用固定数据源进行计算,导致输出结果不受参数影响。
修复方案
1. 核心修改思路
- 读取命令行参数获取股票代码和目标日期;
- 动态请求对应股票的数据源;
- 筛选目标日期的分钟级数据后计算VWAP。
2. 修改后的完整脚本
import sys import pandas as pd import requests def calculate_vwap(ticker, target_date): # 将输入日期转换为YYYY-MM-DD格式 target_date_obj = pd.to_datetime(target_date, format='%m/%d/%Y') target_date_str = target_date_obj.strftime('%Y-%m-%d') # 示例:使用公开API获取分钟级数据(可替换为你实际使用的数据源) url = f'https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?interval=1m&range=1d&period1={int(target_date_obj.timestamp())}&period2={int(target_date_obj.timestamp()) + 86400}' response = requests.get(url) if response.status_code != 200: print(f"获取{ticker}数据失败,请检查股票代码或网络连接") sys.exit(1) data = response.json() if not data['chart']['result']: print(f"{ticker}在{target_date}无分钟级数据") sys.exit(1) # 解析API返回的数据 timestamps = data['chart']['result'][0]['timestamp'] indicators = data['chart']['result'][0]['indicators']['quote'][0] df = pd.DataFrame({ 'Time': pd.to_datetime(timestamps, unit='s'), 'Open': indicators['open'], 'High': indicators['high'], 'Low': indicators['low'], 'Close': indicators['close'], 'volume': indicators['volume'] }) # 筛选目标日期的数据 df = df[df['Time'].dt.date == target_date_obj.date()] # 计算VWAP df['Date'] = df['Time'].dt.date df['typical_price'] = (df['High'] + df['Low'] + df['Close']) / 3 df['tp_volume'] = df['typical_price'] * df['volume'] df['vwap'] = df.groupby('Date')['tp_volume'].cumsum() / df.groupby('Date')['volume'].cumsum() return df if __name__ == '__main__': # 校验命令行参数数量 if len(sys.argv) != 3: print("用法:python3 vwap.py <股票代码> <日期(MM/DD/YYYY)>") print("示例:python3 vwap.py SPY 12/06/2022") sys.exit(1) ticker = sys.argv[1] target_date = sys.argv[2] # 计算并输出VWAP数据 vwap_result = calculate_vwap(ticker, target_date) print(vwap_result)
3. 关键修改说明
- 使用
sys.argv读取命令行传入的股票代码和日期参数,确保脚本可动态接收输入; - 增加日期格式转换和数据筛选逻辑,仅计算指定日期的VWAP;
- 替换为可动态指定股票的数据源API(示例用公开财经API,可根据实际需求更换);
- 添加数据获取失败的异常提示,提升脚本易用性。
4. 使用说明
运行脚本时需传入两个参数:股票代码和目标日期(格式为MM/DD/YYYY),示例命令:
python3 vwap.py SPY 12/06/2022
内容的提问来源于stack exchange,提问作者MrRandom
相关产品推荐
相关产品推荐

