-2

I have been trying to run a code which I found on github to retrieve the yahoo finance data and kept running into below error.

I have checked the Assert statement related docs but couldnt understand the use case here..

Can anyone help me understand and fix the code?

Thank you!

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

Boseong Choi
  • 2,566
  • 9
  • 22
mmmm2020
  • 11
  • 1
  • Assert will throw an error if the stated condition is false. In the last assert, for example, the number of days between today and the most_recent_day cann't be greater than 4 days, if it's greater you will have an error and the program will stop. – jjsantoso Mar 18 '20 at 05:37
  • `assert` should be used with care. It is fine for tests but not for production code. If Python is run with optimization (`-O`) all `assert` statements are ignored. Leaving you with potentially unchecked and untrusted input. – Klaus D. Mar 18 '20 at 05:38
  • @JuanJavierSantosOchoa Thank you! I am still not quite sure why the original author added this in the code but I just updated the code and it works fine now. Thank you very much for the explanation! – mmmm2020 Mar 18 '20 at 06:14
  • @KlausD. Hello - Appreciate the explanation on the actual practices! Thank you! – mmmm2020 Mar 18 '20 at 06:16
  • btw, the word "code" is a collective noun. we run "code", not "a code", or "codes". – Todd Mar 18 '20 at 06:26
  • The original author added those statements as sanity checks, presumably because the following code makes certain assumptions about the data and it confirms those assumptions before continuing. Whether those assumptions are unnecessary or not, who knows. If those assertions fail, you’re continuing at your own risk. – deceze Mar 18 '20 at 06:29

1 Answers1

0

Thanks to the above two.. Compiled their answers in case someone may find this helpful in the future and to close this thread.

Assert will throw an error if the stated condition is false. In the last assert, for example, the number of days between today and the most_recent_day cann't be greater than 4 days, if it's greater you will have an error and the program will stop.

Assert should be used with care. It is fine for tests but not for production code. If Python is run with optimization (-O) all assert statements are ignored. Leaving you with potentially unchecked and untrusted input.

mmmm2020
  • 11
  • 1