【发布时间】:2021-12-25 23:57:31
【问题描述】:
我正在尝试将 excel 数据库转换为 python。 我有一个交易数据需要以 xml 格式导入系统。
我的代码如下:
df = pd.read_excel("C:/Users/junag/Documents/XML/Portfolio2.xlsx", sheet_name="Sheet1", dtype=object)
root = ET.Element('trading-data')
root.set('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
tree = ET.ElementTree(root)
Portfolios = ET.SubElement(root, "Portfolios")
Defaults = ET.SubElement(Portfolios, "Defaults", BaseCurrency="USD")
for row in df.itertuples():
Portfolio = ET.SubElement(Portfolios, "Portfolio", Name=row.Name, BaseCurrency=row.BaseCurrency2, TradingPower=str(row.TradingPower),
ValidationProfile=row.ValidationProfile, CommissionProfile=row.CommissionProfile)
PortfolioPositions = ET.SubElement(Portfolio, "PortfolioPositions")
if row.Type == "Cash":
PortfolioPosition = ET.SubElement(PortfolioPositions, "PortfolioPosition", Type=row.Type, Volume=str(row.Volume))
Cash = ET.SubElement(PortfolioPosition, 'Cash', Currency=str(row.Currency))
else:
PortfolioPosition = ET.SubElement(PortfolioPositions, "PortfolioPosition", Type=row.Type, Volume=str(row.Volume),
Invested=str(row.Invested), BaseInvested=str(row.BaseInvested))
Instrument = ET.SubElement(PortfolioPosition, 'Instrument', Ticker=str(row.Ticker), ISIN=str(row.ISIN), Market=str(row.Market),
Currency=str(row.Currency2), CFI=str(row.CFI))
ET.indent(tree, space="\t", level=0)
tree.write("Portfolios_converted2.xml", encoding="utf-8")
输出如下所示: enter image description here
虽然我需要它看起来像这样: enter image description here
如何改进我的代码以使输出的 xml 看起来更好?请指教
【问题讨论】:
-
请定义“看起来更好”。当前输出有什么问题?
-
子标签“Portfolio”属于“Portfolios”,“PortfolioPositions”属于“Portfolio”。问题在于,对于每个投资组合头寸,“Portfolio”和“PortfolioPositions”都有一个单独的开始和结束标签,而“Portfolio”应该有一个统计和结束标签,“PortfolioPositions”应该有一个开始和结束标签,以及里面应该是职位。
-
对于minimal reproducible example,请发布示例数据。我们无法访问您的 Excel 文件。