英文:
Running Excel Via Python to Fetch Blommberg data
问题
尝试通过使用Python以编程方式驱动Excel从Bloomberg终端获取数据,以下是我正在使用的代码。
import win32com.client
import xlsxwriter
import xlwings as xl
import datetime
path = 'mypath/TempData.xlsx'
work_sheet_name = "Data"
Excelworkbook = xlsxwriter.Workbook(path)
worksheet = Excelworkbook.add_worksheet(work_sheet_name)
# 列表中的券商代码
Tickers = ['1124Z MK EQUITY', 'TD CN EQUITY', 'MIZC JP EQUITY', 'N91 LN EQUITY',
'COST US EQUITY', '6857Z LN EQUITY', 'DZBK GR EQUITY', '55601Z US EQUITY', 'BMO CN EQUITY']
worksheet.write(0, 0, '券商代码')
row = 1
col = 0
for ticker in Tickers:
worksheet.write(row, col, ticker)
row += 1
Excelworkbook.close()
# 连接到Excel。
bb = 'C:/blp/API/Office Tools/BloombergUI.xla'
xl = win32com.client.DispatchEx("Excel.Application")
xl.Workbooks.Open(bb)
xl.AddIns("Bloomberg Excel Tools").Installed = False
wb = xl.Workbooks.Open(Filename=path)
data_Sheet = wb.Worksheets(work_sheet_name)
xl.Visible = False
xl.EnableEvents = False
xl.DisplayAlerts = False
# 打开Excel文件并从第一列读取券商代码
wb = xl.Workbooks.Open(Filename=path)
data_Sheet = wb.Worksheets(work_sheet_name)
max_row = data_Sheet.UsedRange.Rows.Count
券商代码 = []
for row in range(2, max_row+1):
券商代码 = data_Sheet.Cells(row, 1).Value
券商代码.append(券商代码)
# 使用Bloomberg公式为每个券商代码获取数据
for i, ticker in enumerate(券商代码):
# 检索票息
yield_cell = f'B{i+1}'
coupon_yield = xl.Run("=@BDP(\"" + ticker + "\",\"CPN\")")
data_Sheet.Range(yield_cell).Value = coupon_yield
# 检索到期日
maturity_cell = f'C{i+1}'
maturity_raw = xl.Run("=@BDP(\"" + ticker + "\",\"MATURITY\")")
maturity_date = datetime.strptime(maturity_raw, '%m/%d/%Y').date()
data_Sheet.Range(maturity_cell).Value = maturity_date
# 保存并关闭Excel文件
wb.Save()
wb.Close()
xl.Quit()
这是我一直收到的错误。尝试启用宏仍然发生这种情况。
英文:
Trying to Fetch some data from Bloomberg terminal by driving excel programmatically via python here is the code I'm working with.
I have a list of Bloomberg Ticker Codes already so I want to use this tickers to fetch the various fixed income fields.
I begin by creating a create the workbook and then adding the tickers to the first column.
When I proceed to run the excel programmatically using win32com I get an error regarding macros what am I missing?
import win32com.client
import xlsxwriter
import xlwings as xl
import datetime
path = 'mypath/TempData.xlsx'
work_sheet_name = "Data"
Excelworkbook = xlsxwriter.Workbook(path)
worksheet = Excelworkbook.add_worksheet(work_sheet_name)
#List of tickers
Tickers = ['1124Z MK EQUITY','TD CN EQUITY','MIZC JP EQUITY','N91 LN EQUITY',
'COST US EQUITY','6857Z LN EQUITY','DZBK GR EQUITY','55601Z US EQUITY','BMO CN EQUITY']
worksheet.write(0, 0, 'Tickers')
row = 1
col = 0
for ticker in Tickers:
worksheet.write(row, col,ticker)
row += 1
Excelworkbook.close()
#Connect to Excel.
bb = 'C:/blp/API/Office Tools/BloombergUI.xla'
xl = win32com.client.DispatchEx("Excel.Application")
xl.Workbooks.Open(bb)
xl.AddIns("Bloomberg Excel Tools").Installed = False
wb = xl.Workbooks.Open(Filename=path)
data_Sheet = wb.Worksheets(work_sheet_name)
xl.Visible = False
xl.EnableEvents = False
xl.DisplayAlerts = False
# Open the Excel file and read the tickers from the first column
wb = xl.Workbooks.Open(Filename=path)
data_Sheet = wb.Worksheets(work_sheet_name)
max_row = data_Sheet.UsedRange.Rows.Count
tickers = []
for row in range(2, max_row+1):
ticker = data_Sheet.Cells(row, 1).Value
tickers.append(ticker)
# Fetch data for each ticker using Bloomberg formulas
for i, ticker in enumerate(tickers):
# Retrieve the coupon yield
yield_cell = f'B{i+1}'
coupon_yield = xl.Run("=@BDP(\"" + ticker + "\",\"CPN\")")
data_Sheet.Range(yield_cell).Value = coupon_yield
# Retrieve the maturity date
maturity_cell = f'C{i+1}'
maturity_raw = xl.Run("=@BDP(\"" + ticker + "\",\"MATURITY\")")
maturity_date = datetime.strptime(maturity_raw, '%m/%d/%Y').date()
data_Sheet.Range(maturity_cell).Value = maturity_date
# Save and close the Excel file
wb.Save()
wb.Close()
xl.Quit()
this is the error i keep getting.
Tried enabling macros but this still happens.
line 44668, in Run
return self._ApplyTypes_(259, 1, (12, 0), ((12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Cannot run the macro \'=@BDP("1124Z MK EQUITY","CPN")\'. The macro may not be available in this workbook or all macros may be disabled.', 'xlmain11.chm', 0, -2146827284), None)
答案1
得分: 1
OP正在用重拳砸核桃。
将Bloomberg数据快速导入Python(例如使用xbbg
包),然后使用pandas
DataFrame写入.xlsx
文件更容易更快。
from xbbg import blp
import pandas as pd
tickers = ['CT2 Govt','CT5 Govt','CT10 Govt','CT30 Govt']
fields = ['CPN','MATURITY']
filePath = 'c:\\temp\\myfile.xlsx'
#This stops the writer formatting the output
from pandas.io.formats import excel
excel.ExcelFormatter.header_style = None
writer = pd.ExcelWriter(filePath,mode='a',engine='openpyxl',
if_sheet_exists='overlay',date_format='DD/MM/YYY')
df = blp.bdp(tickers,fields)
df.sort_values(by='maturity').to_excel(writer,sheet_name='Data')
writer.close()
在Excel中的输出图:
不使用win32com
自动化Excel的主要原因之一是Bloomberg函数是异步的。这意味着Excel调用会立即返回,实际数据稍后到达。因此,你可能最终得到一组N/A Requesting Data ...
结果而不是数值。解决方案通常需要循环以检查数据是否已到达。
英文:
The OP is using something of a sledgehammer to crack a nut.
It is easier and faster to pull the Bloomberg data into Python (eg using the xbbg
package) and then use the pandas
DataFrame to write to the .xlsx
file.
from xbbg import blp
import pandas as pd
tickers = ['CT2 Govt','CT5 Govt','CT10 Govt','CT30 Govt']
fields = ['CPN','MATURITY']
filePath = 'c:\\temp\\myfile.xlsx'
#This stops the writer formatting the output
from pandas.io.formats import excel
excel.ExcelFormatter.header_style = None
writer = pd.ExcelWriter(filePath,mode='a',engine='openpyxl',
if_sheet_exists='overlay',date_format='DD/MM/YYY')
df = blp.bdp(tickers,fields)
df.sort_values(by='maturity').to_excel(writer,sheet_name='Data')
writer.close()
With the output in Excel:
One of the main reasons not to use win32com
to automate Excel is that the Bloomberg functions are asynchronous. This means that the Excel call returns immediately, and the actual data arrives later. Thus you will likely end up with a set of N/A Requesting Data ...
results rather than values. Solutions then usually have to resort to looping in order to check the data has arrived.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论