P
P
PashaLynx2020-10-14 11:35:11
Python
PashaLynx, 2020-10-14 11:35:11

Why doesn't python iterate over the entire dictionary?

Salute to all. There is some script that, using the API, pulls up historical data on the value of shares and enters them into the Postgre database. All stock tickers are listed in the dictionary, which I run through, but for some reason it runs only through the first element of the dictionary, and then stops. The code itself.

import psycopg2
import yfinance as yf
import datetime
from datetime import timedelta

test_arist = dict(
    AWR='AWR',  # Словарь с тикерами дивидендных аристократов.
    DOV='DOV',
    NWN='NWN',
    GPC='GPC',
    PG='PG',
    PH='PH',
    EMR='EMR',
    MMM='MMM',
    CINF='CINF',
    KO='KO'
)

date1 = datetime.date(1950, 1, 21)
date2 = datetime.date(2020, 9, 23)

def import_func(date_his):
    global dat, i

    con = psycopg2.connect(
        database='base',
        user='user',
        password='qwerty',
        host='127.0.0.1',
        port='5432'
    )
    c = (dat.loc[date_his, 'Close'])
    o = (dat.loc[date_his, 'Open'])
    h = (dat.loc[date_his, 'High'])
    l = (dat.loc[date_his, 'Low'])

    cur = con.cursor()
    cur.execute("INSERT INTO stocks(ticker, date_update, open, close, high, low)"
                "VALUES (%s, %s, %s, %s, %s, %s)",
                (key, x, o, c, h, l))
    con.commit()
    con.close()
for key in test_arist:
    tic = yf.Ticker(key)
    dat = tic.history(period="max", interval="1d")

    while date1 <= date2:
        x = date1.strftime('%Y-%m-%d')
        try:
            date1 = date1 + timedelta(1)
            import_func(x)
        except KeyError:
            date1 = date1 + timedelta(1)

What's wrong? Thank you in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
seonn, 2020-10-14
@PashaLynx

It's easier to say that it's the same with the code, because There are several anti-patterns here, but the answer to your question is simple: you didn't reset date1 after the first iteration of the loop. Those. when the iterator goes from "AWR" to "DOV" it's already date1 = date2
PS: take out the connection to the postgres from the critical one to the class, or transfer the KeyError handling to the function. Now, if you fell on a KeyError - you did not close the connection and create a new one for the next while iteration.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question