Use previous row value to calculate current row value with python and sqlite

Viewed 35

I need to subtract an sqlite db's previous row wallet_balance value from today's wallet_balance value to get a new value for a column which is going to be "change".

I run this:

import keys
from model import Account
from pybit import usdt_perpetual

session_auth = usdt_perpetual.HTTP(
    endpoint='https://api.bybit.com',
    api_key=keys.api_key,
    api_secret=keys.api_secret
)

response = session_auth.get_wallet_balance(coin="USDT")
today = datetime.today().strftime('%Y-%m-%d')
wb = round((response["result"]["USDT"]["wallet_balance"]), 2)
pm = round((response["result"]["USDT"]["position_margin"]), 2)
om = round((response["result"]["USDT"]["order_margin"]), 2)
ex = round((pm + om) / wb, 2)

db = Account()

"""
date DATE,
wallet_balance REAL,
position_margin REAL,
order_margin REAL,
exposure REAL"""

value = (
    today,
    wb,
    pm,
    om,
    ex,
)

db.insert(value)

for value in db.read():
    print(value)

This uses model:

import sqlite3

class Account:
    def __init__(self):
        self.con = sqlite3.connect("account_data.db")
        self.cur = self.con.cursor()
        self.create_table()

    def create_table(self):
        self.cur.execute("""CREATE TABLE IF NOT EXISTS account(
        date DATE PRIMARY KEY,
        wallet_balance REAL,
        position_margin REAL,
        order_margin REAL,
        exposure REAL)""")

    def insert(self, value):
        self.cur.execute("""INSERT OR IGNORE INTO account VALUES(?,?,?,?,?)""",
                         value)
        self.con.commit()

    def read(self):
        self.cur.execute("""SELECT * FROM account""")
        rows = self.cur.fetchall()
        return rows

To get the output values from each day which are stored in my database.

But I want to hopefully add a new column with the header "change" which contains a value gained by subtracting today's wallet_balance value with yesterday's value and inserts it into this new column which is then stored in the db. If I get the method right I can make more calculations with additional data but I don't know how to get over this bump!

0 Answers
Related