简体   繁体   中英

Putting Data into excel sheet from Python

I am trying to put the outputs from the kwargs function into an excel sheet with one column of stock symbols, one with the current price. The code works just fine with using only the stock names, but the moment I added the price it gives me back this error:

MMMTraceback (most recent call last):
  File "C:\Users\sss\Documents\Python Programs\Bot\Td\td4.py", line 52, in <module>

154.95
    get_ohlc(symbol=[row])
  File "C:\Users\sss\Documents\Python Programs\Bot\Td\td4.py", line 43, in get_ohlc
    for symbol, lastPrice in zip(data[symbol],data[lastPrice]):
KeyError: 154.95

Where 154.95 is the last price of that particular stock. I am very confused on why it is giving me the price back as the error. The relevant code is below and thank you in advance for any help!

import pandas as pd

data_sheet1 = pd.read_excel('C:\\Users\\sss\\Downloads\\companylist.xlsx', index_col=0)
data_impor = data_sheet1.head(10)

workbook = xlsxwriter.Workbook('c:\\Users\\sss\\Documents\\output.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Stock')
worksheet.write('B1', 'Price')

row_1 = 1
col = 0

def get_ohlc(**kwargs):
    data = get_quotes(symbol=kwargs.get('symbol'))
    for symbol in kwargs.get('symbol'):
        print(symbol)
        print(data[symbol]['lastPrice'])
        lastPrice = data[symbol]['lastPrice']
    for symbol, lastPrice in zip(data[symbol],data[lastPrice]):
        global row_1
        worksheet.write(row, col, symbol) 
        worksheet.write(row, col + 1, lastPrice) 
        row += 1
    workbook.close()


for row in data_impor.index:
    get_ohlc(symbol=[row])

I think the problem lies in the below for-loop ,

for symbol, lastPrice in zip(data[symbol],data[lastPrice]): #on this line data[lastprice]
        global row_1
        worksheet.write(row, col, symbol) 
        worksheet.write(row, col + 1, lastPrice) 
        row += 1

If you want to access a element from a list you cant pass it a value other than index. And if you are using data[lastPrice] each time and if lastprice is not a index then there will be an error for each access using data[lastPrice]

hope this helps you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM