day2csv

def day2csv(need_list=['sh600000']):
      '通达信日线数据转换为CSV文件,再转换为XLSX文件'
      day2csv_list = []
      if len(need_list) == 0:
            return day2csv_list
     
      for file_name in need_list:
            if file_name[0:2]  == 'sh':
                  day_path = zq_path + 'vipdoc\\sh\\lday\\'
            else:
                  day_path = zq_path + 'vipdoc\\sz\\lday\\'
                  # 以二进制方式打开源文件
            try:
                  source_file = open(day_path + file_name + '.day', 'rb')
                  buf = source_file.read()
                  source_file.close()
                  # 打开目标文件,后缀名为CSV
                  target_file = open(mypath + 'data\\' + file_name + '.csv', 'w')
                  buf_size = len(buf)
                  rec_count = int(buf_size / 32)
                  begin = 0
                  end = 32
                  header = str('日期') + ', ' + str('开盘价') + ', ' + str('最高价') + ', ' + str('最低价') + ', '+ str('收盘价') + ', ' + str('总金额') + ', ' + str('成交量') + ', ' + '\n'
                  target_file.write(header)
                  for i in range(rec_count):
                       
                        # 将字节流转换成Python数据格式
                        # I: unsigned int
                        # f: float
                        a = unpack('IIIIIfII', buf[begin:end])
                        line = str(a[0]) + ', ' + str(a[1] / 100.0) + ', ' + str(a[2] / 100.0) + ', '+ str(a[3] / 100.0) + ', ' + str(a[4] / 100.0) + ', ' + str(a[5]) + ', '  + str(a[6]) + ', '    '\n'
                        target_file.write(line)
                        begin += 32
                        end += 32
                  day2csv_list.append(file_name)
                  source_file.close()
                  target_file.close()
                 
            except:
                  print('找不到' + file_name[2:] + '的日线数据,可能是新股,或者已经退市了 @ #*¥……')
      return day2csv_list

猜你喜欢

转载自blog.csdn.net/lee2601/article/details/80280221
csv