lundi 22 juillet 2019

I want to do better code. Actually its working long

Can you give some advice about this code guys? I want to do better it. What can i do? Where i didnt use pythonic way for example


import csv
import datetime

if __name__ == '__main__':
    window = datetime.timedelta(minutes=1)
    exchange_top = {}

    with open("trades.csv") as f:
        reader = csv.reader(f)
        window_exchange = {}
        try:
            time_, _, _, exchange = next(reader)
            time_ = datetime.datetime.strptime(time_, "%H:%M:%S.%f")
            prev_time = datetime.timedelta(hours=time_.hour,
                                           minutes=time_.minute,
                                           seconds=time_.second,
                                           microseconds=time_.microsecond)
            window_exchange[exchange] = 1

            for time_, _, _, exchange in reader:
                time_ = datetime.datetime.strptime(time_, "%H:%M:%S.%f")
                next_time = datetime.timedelta(hours=time_.hour,
                                               minutes=time_.minute,
                                               seconds=time_.second,
                                               microseconds=time_.microsecond)
                if next_time - prev_time < window:
                    count = window_exchange.get(exchange, 0)
                    window_exchange[exchange] = count + 1
                else:
                    for exchange, count in window_exchange.items():
                        max_count = exchange_top.setdefault(exchange, count)
                        if count > max_count:
                            exchange_top[exchange] = count
                    window_exchange.clear()
                    prev_time = next_time
        except StopIteration:
            print('StopIteration Error')
        else:
            for _, count in sorted(exchange_top.items(), key=lambda exchange: exchange[0]):
                print(count)

So i cant test this code. I dont know where is the trouble

Aucun commentaire:

Enregistrer un commentaire