Импорт Datetime в Excel - PullRequest
       19

Импорт Datetime в Excel

0 голосов
/ 30 июня 2018

Ошибка в option.py ниже, в строке (около конца):

ws.cell(row=i,column=j).value=c

Ошибка:

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

ValueError: Cannot convert [Date

2014-12-01    8555.9

Name: Close, dtype: float64] to Excel

Вот файл option.py:

#importing the necessary packages
import numpy
from nsepy import get_history 
import datetime
from nsepy.derivatives import get_expiry_date
import openpyxl

#opening the excel sheet
wb=openpyxl.load_workbook('/home/arvind/summer_sweta/financial_math/computation/option.xlsx') 
ws=wb.active

#to get the expiry date of the particular year and month when the option will expire 
xyear = int(input('Enter the expiry year(e.g. 2013)'))
xmonth = int(input('Enter the expiry month(e.g. 6,12)'))  
expiry=get_expiry_date(year=xyear,month=xmonth) 

#we want the index option price data where days of maturity will be between 40 and 60
sdate =expiry-(datetime.timedelta(days=60)) 
edate =expiry-(datetime.timedelta(days=40))     

#index for the rows of the excell sheet
i=1

#loop where we find data for all the possible days  
while(sdate!=edate):     
#underlying index price data                            
    nifty_price = get_history(symbol="NIFTY 50",
    start=sdate,
    end=sdate,
    index=True)

#condition to check if data is empty    
    if (nifty_price.empty):             
        sdate += datetime.timedelta(days=1)
        continue

#to get index option price data 
    nifty_opn = get_history(symbol="NIFTY",
    start=sdate,
    end=sdate,
    index=True,
    option_type='CE',
    strike_price=int(numpy.round(nifty_price.get('Close'),-2)), #to round off the strike price to the nearest hundred
    expiry_date=expiry)         

    if (nifty_opn.empty):
        sdate += datetime.timedelta(days=1)
        continue


    if (int(nifty_opn.get('Number of Contracts'))): #we want the data only of days when the option was traded

#we are only collecting the relevant information we need
        symbol=nifty_opn.get('Symbol')
        date=nifty_price.get('Date')
        close=nifty_price.get('Close')
        expiry=nifty_opn.get('Expiry')
        strike_price=nifty_opn.get('Strike Price')
        settle_price=nifty_opn.get('Settle Price')
        contracts_no=nifty_opn.get('Number of Contracts')    
        data= [symbol,date,close,expiry, strike_price,settle_price,
contracts_no]

        j=1
        for c in data:
            ws.cell(row=i,column=j).value=c
            j +=1
            i +=1
        sdate += datetime.timedelta(days=1)
#saving the information to the excel
wb.save('option.xlsx')

1 Ответ

0 голосов
/ 01 июля 2018

Я не использовал ни nsepy.derivatives, ни openpyxl, поэтому я не могу подтвердить или подтвердить. Но ошибка указывает вам большую часть пути:

Понимание вашей ошибки

Правильный объект Python datetime, который вы, вероятно, получаете от get_expiry_date в строке expiry=get_expiry_date(year=xyear,month=xmonth), не может быть полностью / правильно понят в Excel.

Вы можете заглянуть глубже в код openpyxl для управления датами, но, исключая это, просто преобразуйте объект datetime в строку в нужном формате, прежде чем отправлять его в Excel.

Решение

Сразу после for c in data: вы можете добавить:

if isinstance(c, datetime.datetime):
    d = d.strftime("%Y-%m-%d")

Это преобразует d в строку в формате, например, "2018-06-30" (год, месяц, день). Вы можете изменить его на любой формат, который вам нравится ... Я предпочитаю азиатский стиль, как указано здесь, поскольку он полностью однозначен.

PS. Я серьезно отредактировал ваш вопрос, чтобы сделать его более управляемым. Чем проще вопрос для чтения / понимания, тем больше / лучше ответов вы получите.

...