2019实战第二期-文件格式实战打卡

题目:
1.拿到平安银行一年的股票数据 csv文件
2.里面一共244个交易日,我们读取csv文件,然后找到成交量(amount)大于1百万手的交易日的数据

3.然后把大于1百万手的那天的如下数据:
open
high
low
close
amount
写入excel文件

备注:这次作业不能用pandas,因为pandas处理大概只要3行!

import csv
from collections import OrderedDict
import xlwt

headers = ["ts_code", "trade_date", "open", "high", "low", "amount"]


def read_csv(file, max_amount=1000000):
    res = []
    with open(file, 'rt') as rf:
        csv_reader = csv.DictReader(rf)
        for each_line in list(csv_reader)[::-1]:
            sock = OrderedDict()
            amount = float(each_line.get('amount'))
            if amount > max_amount:
                sock["ts_code"] = each_line.get("ts_code", "")
                sock["trade_date"] = each_line.get("trade_date", "")
                sock["open"] = each_line.get("open", "")
                sock["high"] = each_line.get("high", "")
                sock["low"] = each_line.get("low", "")
                sock["close"] = each_line.get("close", "")
                sock["amount"] = each_line.get("amount", "")
                res.append(sock)
        return res


def write_data_to_excel(data=[]):
    excel = xlwt.Workbook()
    work_sheet = excel.add_sheet('sock')
    # write headers
    for index, header in enumerate(headers):
        work_sheet.write(0, index, label=header)

    # write data
    for index_row, each_dict in enumerate(data):
        for index_col, v in enumerate(each_dict.values()):
            work_sheet.write(index_row + 1, index_col, v)
    excel.save('Sock.xls')


def main():
    f_name = '000001.csv'
    print(f'reading file {f_name}')
    data = read_csv(file=f_name)
    print(f'writing file {f_name} to excel')
    write_data_to_excel(data)


if __name__ == '__main__':
    main()

你可能感兴趣的:(2019实战第二期-文件格式实战打卡)