Read a CSV file in Python and print out unique dates from a column that has date and time
Question: I need to be able to read a csv file and sum a few columns per day and then
generate a new csv file with the solutions. I am brand new to Python and I
have figured out how to read the csv but now I must figure out how to sum the
columns based on the date/time column.

CSV:

    
    
    tag,date,symbol,exch,volume,price,side,ind
    1058,20140612 13:29:59.042,BRK/B,NQBX,1000,61.25,SELL_SHORT,A
    1059,20140612 13:29:59.043,JNJ,NQBX,185,31.94,SELL_SHORT,A
    1153,20140612 13:30:00.117,AAPL,NQBX,77,43.64,SELL,A
    1201,20140612 13:30:00.190,WFC,NQBX,100,49.92,SELL,A
    1720,20140612 13:30:04.003,JPM,NQBX,100,50.16,SELL,A
    1738,20140613 13:30:04.254,PFE,NQBX,600,43.89,SELL_SHORT,A
    108167,20140613 13:30:04.809,VZ,NSDQ,2000,61.23,SELL_SHORT,R
    1799,20140613 13:30:05.252,MSFT,NQBX,11,43.76,BUY,A
    1879,20140612 13:30:06.393,CVX,NQBX,40,70.58,BUY,A
    1908,20140612 13:30:06.803,INTC,NQBX,100,56.52,SELL_SHORT,A
    1989,201406117 13:30:08.003,GE,NQBX,100,50.14,SELL,A
    2008,20140619 13:30:08.169,JNJ,NQBX,97,15.18,SELL,A
    2021,20140619 13:30:08.393,PFE,NQBX,38,43.89,SELL_SHORT,A
    2197,20140619 13:30:10.599,WFC,NQBX,100,30.34,BUY,A
    2302,20140620 13:30:12.002,GE,NQBX,100,50.14,SELL,A
    2368,20140620 13:30:12.931,INTC,NQBX,500,31.44,SELL,A
    

I need to sum the volume column per day and then create a new csv with the
summary.


Answer: You can use `csv.DictReader` with `itertools.groupby` to achieve what you
want.

    
    
    import csv
    import itertools
    
    def sum_volumes_by_date(yourcsvfile, writetocsv):
        # it will read all your data and pairing the header to values into a dictionary
        results = [line for line in csv.DictReader(open(yourcsvfile))]
    
        with open(writetocsv, 'w') as f:    
            f.write("Date,Sum(Vols)\n")
    
            # use groupby to group a sorted list of the dictionary by its 'date'
            for k, g in itertools.groupby(sorted(results, key=lambda x: x['date']), \
                                          lambda each: each['date'][:8]):
                # then sum its relative 'volume' values
                f.write("{},{}\n".format(k, sum([int(each['volume']) for each in g])))
    

Usage:

    
    
    >>> sum_volumes_by_date('in.csv', 'out.csv')
    >>> cat out.csv
    Date,Sum(Vols)
    20140611,100
    20140612,1602
    20140613,2611
    20140619,235
    20140620,600
    

