Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Please help me.
#11
(May-07-2023, 01:44 PM)SuchUmami Wrote: In future, I will not put too many functions in my code.
I think you misunderstand a little here.
I mean that you could make function then it will isolate code,
so can have what you have written in one function and other stuff needed in a other function.
Example.
# kr3.py
import krakenex
import pandas as pd

api = krakenex.API()

def calc_pair_price():
    # Define currency pairs and their corresponding names
    currency_pairs = [
        ('XETHXXBT', 'ETH/BTC'),('XXBTZEUR', 'BTC/EUR'),
        ('XXBTZUSD', 'BTC/USD'),('XXBTZGBP', 'BTC/GBP'),
        ('XETHZEUR', 'ETH/EUR'),('XETHZGBP', 'ETH/GBP'),
        ('XETHZUSD', 'ETH/USD'),('EURGBP', 'EURGBP'),
        ('ZEURZUSD', 'EUR/USD'),('ZGBPZUSD', 'GBP/USD'),
        ('PAXGXBT', 'PAXG/BTC'),('PAXGETH', 'PAXG/ETH'),
        ('PAXGEUR', 'PAXG/EUR'),('PAXGUSD', 'PAXG/USD'),
        ('XXRPXXBT', 'XRP/BTC'),('XRPETH', 'XRP/ETH'),
        ('XXRPZEUR', 'XRP/EUR'),('XRPGBP', 'XRP/GBP'),
        ('XXRPZUSD', 'XRP/USD'),
    ]

    time_frames = ['1', '5', '15', '30', '60', '240', '1440', '10080']
    for pair, pair_name in currency_pairs:
        for tf in time_frames:
            print(f'{tf} minute m/a ({pair_name})')

            # Fetch OHLC data for the given pair and time frame
            ohlc_data = api.query_public('OHLC', {'pair': pair, 'interval': tf})

            # Convert the data to a pandas dataframe
            df = pd.DataFrame(
                ohlc_data['result'][pair],
                columns=['time', 'open', 'high', 'low', 'close', 'vwap', 'volume', 'count',]
            )
            df['time'] = pd.to_datetime(df['time'], unit='s')
            df.set_index('time', inplace=True)

            # Calculate the moving averages
            last_20_candles = df.iloc[-21:-1]
            last_20_close_prices = last_20_candles['close'].astype(float).tolist()
            avg_last_20_close_price = sum(last_20_close_prices) / len(last_20_close_prices)
            print(f'20 period m/a: {avg_last_20_close_price}')

            last_50_candles = df.iloc[-51:-1]
            last_50_close_prices = last_50_candles['close'].astype(float).tolist()
            avg_last_50_close_price = sum(last_50_close_prices) / len(last_50_close_prices)
            print(f'50 period m/a: {avg_last_50_close_price}')

            last_200_candles = df.iloc[-201:-1]
            last_200_close_prices = (last_200_candles['close'].astype(float).tolist())
            avg_last_200_close_price = sum(last_200_close_prices) / len(last_200_close_prices)
            print(f'200 period m/a: {avg_last_200_close_price}')
            print('\n')

def calc_max():
    pair = 'BTC/USD'
    interval = 15
    # make the API request for OHLC data
    ohlc_data = api.query_public('OHLC', {'pair': pair, 'interval': interval})
    # Convert the data to a pandas dataframe
    df = pd.DataFrame(ohlc_data['result'][pair], columns=['time', 'open', 'high', 'low', 'close', 'vwap', 'volume', 'count'])
    df['time'] = pd.to_datetime(df['time'], unit='s')
    df.set_index('time', inplace=True)
    max_price = df['high'].max()
    print(f"Maximum price in the <high column>: {max_price}")

if __name__ == '__main__':
    calc_max()
    #calc_pair_price() 
(dl_env) G:\div_code\dl_env
λ python kr3.py
Maximum price in the <high column>: 29975.0
So now have added a function as eg calculate Maximum price in high high column(as i don't understand what you want to add).
If uncomment calc_pair_price() it will run your code,so a way organize code that make it easier to add stuff.
Also is normal that a function return code for further processing,then can to smaller task and code get easier to read.
Reply
#12
What I don't quite understand is if I just use this part of the code you wrote:

def calc_max():
    pair = 'BTC/USD'
    interval = 15
    # make the API request for OHLC data
    ohlc_data = api.query_public('OHLC', {'pair': pair, 'interval': interval})
    # Convert the data to a pandas dataframe
    df = pd.DataFrame(ohlc_data['result'][pair], columns=['time', 'open', 'high', 'low', 'close', 'vwap', 'volume', 'count'])
    df['time'] = pd.to_datetime(df['time'], unit='s')
    df.set_index('time', inplace=True)
    max_price = df['high'].max()
    print(f"Maximum price in the <high column>: {max_price}")
 
if __name__ == '__main__':
    calc_max()
    #calc_pair_price() 
That I get the very same number without any of my code. I'm sorry if this is a dumb observation.
Reply
#13
Not sure what you try do.
It was just a quick function demo.
Can write it more useful like this,now is much flexible and can take different argument in.
import krakenex
import pandas as pd

api = krakenex.API()

def calc_max(pair: str, interval: int, col_index: str) -> None:
    # make the API request for OHLC data
    ohlc_data = api.query_public('OHLC', {'pair': pair, 'interval': interval})
    # Convert the data to a pandas dataframe
    df = pd.DataFrame(ohlc_data['result'][pair], columns=['time', 'open', 'high', 'low', 'close', 'vwap', 'volume', 'count'])
    df['time'] = pd.to_datetime(df['time'], unit='s')
    df.set_index('time', inplace=True)
    print(f'{df.head()}\n')
    max_price = df[col_index].max()
    print(f"Maximum price in the <{col_index}>: {max_price}")

if __name__ == '__main__':
    pair = 'XRPGBP'
    interval = 60
    col_index = 'open'
    calc_max(pair, interval, col_index)
Output:
(dl_env) G:\div_code\dl_env λ python calc_max.py open high low close vwap volume count time 2023-04-08 14:00:00 0.41009 0.41067 0.41003 0.41049 0.41031 2498.49848700 17 2023-04-08 15:00:00 0.41087 0.41087 0.41001 0.41002 0.41035 2470.63201500 19 2023-04-08 16:00:00 0.40983 0.40992 0.40913 0.40950 0.40945 5611.68209685 19 2023-04-08 17:00:00 0.40953 0.41037 0.40767 0.40767 0.40918 2416.04309153 15 2023-04-08 18:00:00 0.40755 0.40811 0.40507 0.40585 0.40658 5555.67721549 33 Maximum price in the <open>: 0.42970
Now it check max in XRPGBP open column.
Let say now want to check max in BTC/USD high column with interval 15.
import krakenex
import pandas as pd

api = krakenex.API()

def calc_max(pair: str, interval: int, col_index: str) -> None:
    # make the API request for OHLC data
    ohlc_data = api.query_public('OHLC', {'pair': pair, 'interval': interval})
    # Convert the data to a pandas dataframe
    df = pd.DataFrame(ohlc_data['result'][pair], columns=['time', 'open', 'high', 'low', 'close', 'vwap', 'volume', 'count'])
    df['time'] = pd.to_datetime(df['time'], unit='s')
    df.set_index('time', inplace=True)
    print(f'{df.head()}\n')
    max_price = df[col_index].max()
    print(f"Maximum price in the <{col_index}>: {max_price}")

if __name__ == '__main__':
    pair = 'BTC/USD'
    interval = 15
    col_index = 'high'
    calc_max(pair, interval, col_index)
Output:
G:\div_code\dl_env λ python calc_max.py open high low close vwap volume count time 2023-05-01 02:15:00 28650.2 28678.1 28568.0 28600.0 28635.1 74.45265240 541 2023-05-01 02:30:00 28599.9 28652.7 28586.8 28589.4 28615.1 30.90120898 432 2023-05-01 02:45:00 28598.0 28623.1 28536.0 28555.3 28580.7 20.00984895 350 2023-05-01 03:00:00 28564.2 28565.1 28477.4 28491.9 28537.1 41.99185887 436 2023-05-01 03:15:00 28489.1 28605.7 28450.0 28595.8 28537.2 42.52158371 402 Maximum price in the <high>: 29868.1
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020