如何处理Python中假期和周末引起的异常

时间:2019-12-07 16:38:09

标签: python date exception

我正在使用API查找给定公司在每个月的最后一天的历史股票市场价格。问题是最后一天有时可能会在周末或假日,在这种情况下,API返回KeyError。我尝试使用异常来解决此问题,方法是在日期上添加n号以获得下一个最接近的有效数字,但这并不是万无一失的。

这是我现有的代码:

import os
from iexfinance.stocks import get_historical_data
import iexfinance
import pandas as pd

# Set API Keys
os.environ['IEX_API_VERSION'] = 'iexcloud-sandbox'
os.environ['IEX_TOKEN'] = 'Tsk_5798c0ab124d49639bb1575b322841c4'

stocks = ['AMZN', 'FDX', 'XXXXX', 'BAC', 'COST']
date = "20191130"

for stock in stocks:

    try:
        price_df = get_historical_data(stock, date, close_only=True,output_format='pandas')
        price = price_df['close'].values[0]
        print(price)
    except KeyError:
        date = str(int(date) - 1)
        price_df = get_historical_data(stock, date, close_only=True, output_format='pandas')
        price = price_df['close'].values[0]
        print(price)
    except iexfinance.utils.exceptions.IEXQueryError:
        print(stock + " is not a valid company")

但是,如果您更改date = "20160131",则会再次获得KeyError

那么有没有一种简单的方法来处理这些异常并获取下一个有效日期?

请注意,API密钥是公开的并且用于沙箱用途,请随时使用

1 个答案:

答案 0 :(得分:0)

我认为这可能有效:

def get_prices(stocks, date):
    for stock in stocks:
        try:
            price_df = get_historical_data(stock, date, close_only=True,output_format='pandas')
            price = price_df['close'].values[0]
            print(stock + " was @ $" + str(price) + " on " + str(date))
        except KeyError:
            return get_prices(stocks, date = str(int(date) - 1))
            print(stock + " was @ $" + str(price) + " on " + str(date))
        except iexfinance.utils.exceptions.IEXQueryError:
            print(stock + " is not a valid company")