我编写此代码是为了在Excel上显示Apple Inc.的一系列合同,但数据不在Excel上显示

import yfinance as yf
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "Gamma"
ticker = yf.Ticker("AAPL")
info = ticker.info
industry = print("industry:",info ["industry"])
Symbol = print("symbol:",info ["symbol"])
Last = print("currentprice:",info ["currentPrice"])
Option = ticker.option_chain('2023-06-23')
ks= print(Option.calls)

ws['A1']= info ["symbol"]
ws['A2']= info ["industry"]
ws['A3']= info ["currentPrice"]
ws['A5']= Option.calls
wb.save("gamm.xlsx")

我重新保存的错误与这行ws['A5']= Option.calls有关.如果我写的代码没有它,程序将创建Excel文件,但只显示A1、A2和A3

这就是错误

raise ValueError("Cannot convert {0!r} to Excel".format(value))

ValueError: Cannot convert          contractSymbol             lastTradeDate  ...  contractSize  currency
0   AAPL230623C00070000 2023-05-30 14:09:28+00:00  ...       REGULAR       USD
1   AAPL230623C00100000 2023-06-05 19:53:22+00:00  ...       REGULAR       USD
2   AAPL230623C00110000 2023-06-16 17:45:43+00:00  ...       REGULAR       USD
3   AAPL230623C00115000 2023-06-16 17:34:41+00:00  ...       REGULAR       USD
4   AAPL230623C00120000 2023-06-16 17:38:58+00:00  ...       REGULAR       USD
5   AAPL230623C00130000 2023-06-14 14:46:51+00:00  ...       REGULAR       USD
6   AAPL230623C00135000 2023-06-16 16:11:04+00:00  ...       REGULAR       USD
7   AAPL230623C00140000 2023-06-16 16:27:40+00:00  ...       REGULAR       USD
8   AAPL230623C00145000 2023-06-16 15:50:56+00:00  ...       REGULAR       USD
9   AAPL230623C00148000 2023-06-12 16:40:01+00:00  ...       REGULAR       USD
10  AAPL230623C00149000 2023-06-12 17:29:03+00:00  ...       REGULAR       USD

[11 rows x 14 columns] to Excel

推荐答案

To display the data you want to use to_excel from Pandas to write the dataframe to the Excel sheet;

import yfinance as yf
import pandas as pd

ticker = yf.Ticker("AAPL")
info = ticker.info

print("industry:", info["industry"])
print("symbol:", info["symbol"])
print("currentprice:", info["currentPrice"])
Option = ticker.option_chain('2023-06-23')

### Dataframe for Header information. Header and infomation 
### Formatted for two rows; row1 Header, row2 Info 
symbol_df = pd.DataFrame({
    'Symbol': [info["symbol"]],
    'Market': [info["industry"]],
    'Last Price': [info["currentPrice"]]
})

### Option.calls is a dataframe
options_df = Option.calls
### Need to fix the lasttradeDate as it contains TZ information
options_df['lastTradeDate'] = options_df['lastTradeDate'].dt.tz_localize(None)

### Write the two dataframes to Excel
### Symbol Info first from row 1, then Options df from row 3
with pd.ExcelWriter("gamm.xlsx") as writer:
    symbol_df.to_excel(writer,
                       sheet_name="Gamm",
                       startrow=0,
                       index=False)
    options_df.to_excel(writer,
                        sheet_name="Gamm",
                        startrow=3,
                        index=False)

Example Output
Example


Note使用的默认引擎是'Openpyxl',因此不会为数据调整EXCEL列的大小.如果你愿意,你可以切换到xlsxwriter引擎,使用它的autofit()功能来做到这一点.将ExcelWriter部分更改为下面;

...
### Write the two dataframes to Excel
### Symbol Info first from row 1, then Options df from row 3
with pd.ExcelWriter("gamm.xlsx", engine="xlsxwriter") as writer:
    symbol_df.to_excel(writer,
                       sheet_name="Gamm",
                       startrow=0,
                       index=False)
    options_df.to_excel(writer,
                        sheet_name="Gamm",
                        startrow=3,
                        index=False)

    ### xlsxwriter workbook and sheet objects
    workbook = writer.book
    worksheet = writer.sheets['Gamm']

    ### Use autofit() function on the worksheet 
    worksheet.autofit()

Python相关问答推荐

按照行主要蛇扫描顺序对点列表进行排序

jit JAX函数中的迭代器

使用scipy. optimate.least_squares()用可变数量的参数匹配两条曲线

Locust请求中的Python和参数

Pythind 11无法弄清楚如何访问tuple元素

如何在具有重复数据的pandas中对groupby进行总和,同时保留其他列

使用mySQL的SQlalchemy过滤重叠时间段

如何将ctyles.POINTER(ctyles.c_float)转换为int?

按列分区,按另一列排序

使用@ guardlasses. guardlass和注释的Python继承

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

pandas:对多级列框架的列进行排序/重新排序

python panda ExcelWriter切换动态公式到数组公式

循环浏览每个客户记录,以获取他们来自的第一个/最后一个渠道

Polars map_使用多处理对UDF进行批处理

使用__json__的 pyramid 在客户端返回意外格式

pandas fill和bfill基于另一列中的条件

Python—在嵌套列表中添加相同索引的元素,然后计算平均值

如何在信号的FFT中获得正确的频率幅值

对数据帧进行分组,并按组间等概率抽样n行