Как получить последние вставленные записи из PostgreSQL с Python - PullRequest
0 голосов
/ 03 апреля 2020

Я новичок и не могу найти правильный способ сделать это. У меня более 60 миллионов строк в таблице PostgreSQL с каждым днем ​​становится все больше, информация с (2019). Есть информация о тик-запросах / ставках для EUR / USD, которую я обновляю с помощью истории и загружаю ее на большой стол или напрямую обновляю из Oanda live.

Теперь я пытаюсь сделать следующее: вытащить другое Тиковые числа размера чанка, такие как 5, 34, 144 и c (каждая строка представляет значение тика во времени для спроса / предложения), это означает, что мне нужно проанализировать таблицу с 5 строками, 34 строками, 144 строками и c Из всего этого создайте OHL C и сохраните его в другой таблице, чтобы иметь возможность выполнять различные математические операции с ним.

Ниже я вставил последнюю, но logi c не является подходящим вариантом , но в настоящее время мой ум застрял.

Как я могу l oop Pg SQL, чтобы получить последнюю обновленную информацию, не занимая все строки 60M + и запрашивать БД до nr. тиков было достигнуто, и можно создать OHL C (открытие, максимум, минимум, закрытие) для этого количества тиков, если не ждать и повторять, но всегда запрашивать последнюю информацию из предыдущего.

with conn.cursor(name='custom_cursor1') as cursor:
     query = "SELECT ending FROM tick" + str (interval) + " ORDER BY date desc limit 1"
     cursor.execute(query)
     last_row_in_interval = cursor.fetchone()

    with conn.cursor(name='custom_cursor2') as cursor:     
         query1 = 'SELECT date, ask FROM eurusd WHERE date >' + "'" + str( last_row_in_interval[0]) + "'"
         cursor.execute(query1)
         next_row_in_data = cursor.fetchone()

    while next_row_in_data > last_row_in_interval:
        with conn.cursor(name='custom_cursor3') as cursor:
            cursor.itersize = interval # chunk size
            query = "SELECT date, ask FROM eurusd WHERE date > " + "'" + str(next_row_in_data[0]) + "'" + " ORDER BY date ASC"
            cursor.execute(query)
            for value in cursor:
                lst.append(value)
                if len(lst) == 233:
                    #print(row)
                    c = c+ 1

                    #create an empty dataframe
                    #create a dataframe so the information can be better sorted and extracted
                    df = pd.DataFrame(lst, columns = ("Date","Ask"))
                    df.set_index('Date', inplace = True)

                    #create the dataframe based on the interval and upload it in the db with the interval name
                    di['v1'] = di['v1'].append(pd.Series([
                         df.index[0],
                         df.loc[df.index[0],'Ask'],
                         df.max()[0], 
                         df.min()[0],
                         df.loc[df.index[-1],'Ask'],
                         df.index[-1],
                         (df.index[-1] - df.index[0]).total_seconds()
                         ], index = di['v1'].columns), ignore_index = True)

                    #extracting the numbers from dataframe and populte it with the table created for this nr of ticks for later use
                    for idx in di['v1'].index:
                        qu = """ INSERT INTO tick233(Date, Open, High, Low, Close, Ending, Build_Durration) values ('%s','%s','%s','%s','%s','%s','%s') """ %(
                            di['v1'].loc[idx,'Date'],
                            di['v1'].loc[idx,'Open'],
                            di['v1'].loc[idx,'High'],
                            di['v1'].loc[idx,'Low'],
                            di['v1'].loc[idx,'Close'],
                            di['v1'].loc[idx,'Ending'],
                            di['v1'].loc[idx,'Build_Durration']
                            )
                        connection = psycopg2.connect(**connection_details)
                        cursor = connection.cursor()
                        cursor.execute(qu)
                        connection.commit()

                        cursor.close()
                        connection.close()

                    #refreshing the dataframe so we can have always the last one and avoid having duplicates in DB
                    di['v1'].drop(index = 0, inplace = True)
                    #refreshing the list
                    lst.clear()
                else:
                    with conn.cursor(name='custom_cursor1') as cursor:
                        query = "SELECT ending FROM tick" + str (interval) + " ORDER BY date desc limit 1"
                        cursor.execute(query)
                        last_row_in_interval = cursor.fetchone()

                    with conn.cursor(name='custom_cursor2') as cursor:     
                         query1 = 'SELECT date, ask FROM eurusd WHERE date >' + "'" + str( last_row_in_interval[0]) + "'"
                         cursor.execute(query1)
                         next_row_in_data = cursor.fetchone()
...