如何理解网站数据检索用例下python中的断言?

2024-09-28 01:33:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直试图运行在github上找到的代码来检索yahoo finance数据,但一直遇到以下错误

我已经查看了与Assert语句相关的文档,但无法理解这里的用例

有人能帮我理解和修复代码吗

谢谢大家!

def get_volatility_and_performance(symbol):
    download_url = "https://query1.finance.yahoo.com/v7/finance/download/{}?period1={}&period2={}&interval=1d&events=history&crumb=a7pcO//zvcW".format(
        symbol, start_timestamp, end_timestamp)
    lines = requests.get(download_url, cookies={
        'B': 'ft62erdtd45aci&b=8&s=6a'}).text.strip().split('\n')
    assert lines[0].split(',')[0] == 'Date'
    assert lines[0].split(',')[4] == 'Close'
    prices = []
    for line in lines[1:]:
        prices.append(float(line.split(',')[4]))
    prices.reverse()
    volatilities_in_window = []

    for i in range(window_size):
        volatilities_in_window.append(math.log(prices[i] / prices[i + 1]))

    most_recent_date = datetime.strptime(lines[-1].split(',')[0],
                                         date_format).date()
    assert (
                       date.today() - most_recent_date).days <= 4, "today is {}, most recent trading day is {}".format(
        date.today(), most_recent_date)

    return np.std(volatilities_in_window, ddof=1) * np.sqrt(
        num_trading_days_per_year), prices[0] / prices[window_size] - 1.0

volatilities = []
performances = []
sum_inverse_volatility = 0.0
for symbol in symbols:
    volatility, performance = get_volatility_and_performance(symbol)
    sum_inverse_volatility += 1 / volatility
    volatilities.append(volatility)
    performances.append(performance)

print("Portfolio: {}, as of {} (window size is {} days)".format(str(symbols), date.today().strftime('%Y-%m-%d'), window_size))
for i in range(len(symbols)):
    print('{} allocation ratio: {:.2f}% (anualized volatility: {:.2f}%, performance: {:.2f}%)'.format(
            symbols[i],
            float(100 / (volatilities[i] * sum_inverse_volatility)),
            float(volatilities[i] * 100), float(performances[i] * 100)))

Error Message: Assertion Error


Tags: informatforsizedateperformancefloatwindow
1条回答
网友
1楼 · 发布于 2024-09-28 01:33:55

多亏了以上两个。。 编辑他们的答案,以防将来有人发现这有帮助,并关闭此线程

如果声明的条件为false,Assert将抛出错误。例如,在最后一个断言中,从今天到最近一天的天数不能超过4天,如果大于4天,则会出现错误,程序将停止

Assert应该小心使用。它适用于测试,但不适用于生产代码。如果Python运行时带有优化(-O),那么所有断言语句都将被忽略。给您留下潜在的未检查和不可信的输入

相关问题 更多 >

    热门问题