0

Now I'm coding to get Change value (A day - A day of yesterday) and the data existing only working day so if no existing data of a day the code get KeyError. so I used Try, Except code but...so messy..I wanna combine below code.

    ydate = datetime.strptime(date, '%Y-%m-%d').date() - timedelta(days=1)
    sydate = str(ydate)
    try:
        yclose = data['Time Series (Daily)'][sydate]['4. close']
    except KeyError:
        try:
            ydate = datetime.strptime(date, '%Y-%m-%d').date() - timedelta(days=2)
            sydate = str(ydate)
            yclose = data['Time Series (Daily)'][sydate]['4. close']
        except KeyError:
            try:
                ydate = datetime.strptime(date, '%Y-%m-%d').date() - timedelta(days=3)
                sydate = str(ydate)
                yclose = data['Time Series (Daily)'][sydate]['4. close']
            except KeyError:
                    try:
                    ydate = datetime.strptime(date, '%Y-%m-%d').date() - timedelta(days=4)
                    sydate = str(ydate)
                    yclose = data['Time Series (Daily)'][sydate]['4. close']
2
  • Put your code in a function with a while True loop and return the values at the end of the try block. If the return is not hit, the loop will do an other round. Commented Apr 6, 2020 at 7:43
  • Does this answer your question? How to improve code clarity in nested try-except-else clauses? Commented Apr 6, 2020 at 7:48

1 Answer 1

2

Wrap it in a loop.

for x in range(0, 5):
    ydate = datetime.strptime(date, '%Y-%m-%d').date() - timedelta(days=x)
    sydate = str(ydate)
    try:
        yclose = data['Time Series (Daily)'][sydate]['4. close']
    except KeyError:
        continue
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.