Your code is almost perfect. Very good!
I decided to test your code with the following dates:
startdate = '20170130'
enddate = '20170207'
When testing with a shorter period, I could notice the following:
- this error only appears when no deals occurred on the day (Sáb, gift or holidays), that is, the file doesn’t really exist!
- you can use a Try/except structure to get around this error
Code Example:
from io import BytesIO
from urllib.request import urlopen
from zipfile import ZipFile
import pandas as pd
startdate = '20170130'
enddate = '20170207'
extension = '.zip'
daterange = pd.date_range(start=startdate, end=enddate)
for single_date in daterange:
zipurl = 'ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_' + single_date.strftime('%Y%m%d') + extension
try:
with urlopen(zipurl) as zipresp:
with ZipFile(BytesIO(zipresp.read())) as zfile:
zfile.extractall()
print("OK: {}".format(zipurl))
except:
print('ERRO: {}'.format(zipurl))
print("="*5)
Output:
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170130.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170131.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170201.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170202.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170203.zip
=====
ERRO: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170204.zip
=====
ERRO: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170205.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170206.zip
=====
OK: ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_20170207.zip
=====
Checking the calendar, we can see that 04/02/2017
was a sábado
and 05/02/2017
one domingo
.
And when entering the folder with the supposed downloads, surprise:
Note that I have removed the output path from the extraction p/test purposes. You can reinclude it in your code (zfile.extractall('C:/Users/.../.../...')
)
Thank you very much!
– Maverick13