行业知识
python:如何生成画基金净值 月K线图所需要的数据
2026-11-06 19:46:52
来源:互联网转载
���篇没有用 pandas,自己编程生成画基金净值 月K线图所需要的数据。
()编写 month_data.py 如下
# coding=utf-8import os, sysif len(sys.argv) ==2: fcode = sys.argv[1]else: print('usage: month_data.py fcode ') sys.exit(1)path ='./data/'f1 = fcode +'.csv'if not os.path.exists(path+f1): print("Error: %s not found." % f1) sys.exit(1)fn,ext = os.path.splitext(f1)if len(fn) !=6: print('Error: len(%s) !=6' % fn) sys.exit(1)if ext !='.csv': print('Error: %s is not .csv' % f1) sys.exit(1)def average(nlist): """ 计算平均数 """ nsum = 0.0 for i in range(len(nlist)): nsum += nlist[i] return round(nsum / len(nlist), 4)fr = open(path+f1,'r')fr.readline()f2 = 'M' + f1fp = open(path+f2,'w')fp.write("ym,open,close,low,high,mavg\n")i =0alist =[]for line in fr: a = line.strip().split(',') i +=1 if i==1: ym = a[0][0:7] begin = a[1] end = a[1] low = a[1] high = a[1] if ym == a[0][0:7]: end = a[1] if a[1] high: high = a[1] if ym != a[0][0:7]: mavg = average(alist) ss = "%s,%s,%s,%s,%s,%s\n" % (ym.replace('-',''),begin,end,low,high,mavg) fp.write(ss) alist =[] ym = a[0][0:7] begin = a[1] end = a[1] low = a[1] high = a[1] i =1 alist.append(float(a[1]))#mavg = average(alist)ss = "%s,%s,%s,%s,%s,%s\n" % (ym.replace('-',''),begin,end,low,high,mavg)fp.write(ss)fp.close()fr.close() 运行 python month_data.py 660008
()生成 M660008.csv