VBA调用Python下载Yahoo数据,Excel仅生成表头无内容
问题:VBA调用Python生成的Excel仅含表头无数据
我编写了以下Python函数用于下载Yahoo Finance数据:
def download_yahoo_data(arg1,arg2,arg3): # 该函数根据起止日期下载Yahoo Finance数据 # 输入参数: # arg1 来自Yahoo Finance的ticker # arg2 开始日期 # arg3 结束日期 import yfinance as yf import os import pandas as pd df= yf.download(arg1,start=arg2,end=arg3,progress=False) path = "C:\\Users\\Gregorio\\Desktop\\" writer = pd.ExcelWriter(os.path.join(path,arg1+".xlsx"),engine='xlsxwriter') df.to_excel(writer,sheet_name='Data') writer.save() writer.close()
通过以下VBA脚本调用该函数:
Sub GetHistoricalData() Application.DisplayAlerts = True Application.ScreenUpdating = True Application.Calculation = xlAutomatic StartTime = Timer arg1 = Sheets(1).[C4] ' Yahoo finance ticker arg2 = Application.Text(Sheets(1).[D4], "yyyy-mm-dd") ' Start date arg3 = Application.Text(Sheets(1).[E4], "yyyy-mm-dd") ' End Date RunPython ("import yahoo_downloader; yahoo_downloader.download_yahoo_data('" & arg1 & "','" & arg2 & "','" & arg3 & "')") MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss") MsgBox " This code ran sucessfully in " & MinutesElapsed & " minutes", vbInformation Application.DisplayAlerts = True Application.ScreenUpdating = True Application.Calculation = xlAutomatic End Sub
运行VBA宏时提示执行成功,但生成的Excel文件仅包含表头无数据;而在Spyder或Jupyter Notebook中直接定义参数运行该Python函数,却能正常生成包含完整数据的Excel文件。请问为何会出现这种情况?
解决思路及方案
以下是可能的原因和对应的解决方法:
1. 日期参数解析异常
VBA传递的日期字符串可能在Python中未被yfinance正确识别,导致下载的DataFrame为空,最终写入Excel只有表头。
- 验证方式:在Python函数中添加打印语句,查看接收的日期参数是否符合预期:
print(f"Received start date: {arg2}, end date: {arg3}") print(f"Parsed start date: {pd.to_datetime(arg2)}, parsed end date: {pd.to_datetime(arg3)}") - 解决方法:在Python函数中强制将日期参数转换为
datetime类型,确保yfinance能正确解析:import yfinance as yf import os import pandas as pd def download_yahoo_data(arg1,arg2,arg3): # 转换日期格式 start_date = pd.to_datetime(arg2) end_date = pd.to_datetime(arg3) df= yf.download(arg1, start=start_date, end=end_date, progress=False) path = "C:\\Users\\Gregorio\\Desktop\\" file_path = os.path.join(path, f"{arg1}.xlsx") with pd.ExcelWriter(file_path, engine='xlsxwriter') as writer: df.to_excel(writer, sheet_name='Data')
2. ExcelWriter资源未正确释放
原代码中手动调用writer.save()和writer.close(),在VBA调用的环境下可能存在文件未完全写入就被关闭的情况。
- 解决方法:使用Python的上下文管理器(
with语句)创建ExcelWriter,它会自动处理文件的保存和关闭,确保数据写入完整:with pd.ExcelWriter(file_path, engine='xlsxwriter') as writer: df.to_excel(writer, sheet_name='Data') # 无需手动调用save()和close()
3. 运行上下文的权限/路径问题
VBA调用Python时,可能以不同的用户权限运行,导致桌面路径无写入权限;或者路径拼接出现异常。
- 验证方式:在Python函数中打印最终生成的文件路径,确认路径正确,同时尝试写入测试文件:
file_path = os.path.join(path, f"{arg1}.xlsx") print(f"Output file path: {file_path}") # 写入测试内容 with open(os.path.join(path, "test.txt"), "w") as f: f.write("Test write access") - 解决方法:确保目标路径有写入权限,或者更换到明确有权限的路径(比如
C:\\Temp\\)。
4. yfinance在VBA环境中未获取到数据
可能VBA调用Python时,yfinance的网络请求受环境限制(比如代理、防火墙),导致未下载到数据。
- 验证方式:在Python函数中打印DataFrame的形状,确认是否有数据:
如果输出为print(f"Downloaded data shape: {df.shape}")(0, 6),说明确实没有下载到数据,需要排查网络环境或yfinance的版本兼容性。
内容的提问来源于stack exchange,提问作者Gregorio Vargas Martinez
相关产品推荐
相关产品推荐

