-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathlinearLeastSquare.py
More file actions
95 lines (82 loc) · 2.79 KB
/
linearLeastSquare.py
File metadata and controls
95 lines (82 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# mvayg.py : moving average calculation
# by: Albert Lam
# assume conditions
import os
import myfunctions as mf
def llsq(cc,dph,aph,range):
# cc: company code
#
din = dph + cc + '.csv'
inp = aph + cc + 'llsq.csv'
oup = aph + cc + 'tmp.csv'
inf = open(din, 'r')
ouf = open(inp, 'w')
l = inf.readline()
l = l[l.index('date'):l.index(',ask')]+'\n'
ouf.write(l)
t = []
for l in inf:
t = l.split(',')
l = '{0},{1},{2},{3},{4}\n'.format(t[1],t[2],t[3],t[4],t[5])
ouf.write(l)
inf.close()
ouf.close()
mvd = range['lower'] # number of data point at start fitting
inc = range['skip'] # increment of number of data points
lmt = range['upper'] # maximum of data points to be used
while mvd < lmt:
# populate list of x value wiht last date as 100
tmp = 100 - mvd + 1
x = []
while tmp <= 100:
x.append(tmp)
tmp = tmp + 1
# prepare output file with header for each iteration
inf = open(inp, 'r')
l = inf.readline() # read header
ouf = open(oup, 'w')
smvd = str(mvd)
l = l.strip()+ ',llsqh'+smvd+ ',llsql'+smvd+ ',llsqc'+smvd+'\n'
ouf.write(l) # write header
# initialize the list of high low, close value before the iteration
valh = []
vall = []
valc = []
c = 0
while c < (mvd - 1):
l = inf.readline()
ouf.write(l)
t = l.split(',')
valh.append(float(t[2]))
vall.append(float(t[3]))
valc.append(float(t[4]))
c = c + 1
# start the iteration by adding the last date's data to the list to calculate
# the least square fitting of the data set
for l in inf:
t = l.split(',')
valh.append(float(t[2]))
vall.append(float(t[3]))
valc.append(float(t[4]))
# calculat the lest square fitting and record the result
lhigh = []
llow = []
lclose = []
lhigh = mf.llsqfit(x,valh)
llow = mf.llsqfit(x,vall)
lclose = mf.llsqfit(x,valc)
llsqh = '{0[0]:.3f}/{0[1]:.3f}'.format(lhigh)
llsql = '{0[0]:.3f}/{0[1]:.3f}'.format(llow)
llsqc = '{0[0]:.3f}/{0[1]:.3f}'.format(lclose)
l = l.strip() + ',{0:s},{1:s},{2:s}\n'.format(llsqh, llsql, llsqc)
ouf.write(l)
# remove the oldest date high low close data point prepare for next iteration.
valh.pop(0)
vall.pop(0)
valc.pop(0)
ouf.close()
inf.close()
mvd = mvd + inc
os.remove(inp)
# if needed, add check to make sure inp is deleted before rename op.
os.rename(oup, inp)