本篇没有用 pandas,自己编程生成画基金净值 月K线图所需要的数据。
编写 month_data.py 如下
# coding=utf-8
import os, sys
if 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' + f1
fp = open(path+f2,'w')
fp.write("ym,open,close,low,high,mavg\n")
i =0
alist =[]
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]< low: low = 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
本文介绍了一个名为`month_data.py`的Python脚本,用于读取CSV文件中的基金净值数据,计算每个月的平均值并生成新的月K线图数据文件,如M660008.csv。
2588

被折叠的 条评论
为什么被折叠?



