Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/chart2_shares/main.py
5925 views
1
# pip install numpy matplotlib
2
import os.path, time
3
import numpy as np
4
import matplotlib.style
5
import matplotlib as mpl
6
7
mpl.style.use('classic')
8
mpl.rcParams['axes.formatter.useoffset'] = False
9
import matplotlib.pyplot as plt
10
11
dataFile = 'YNDX_210801_210823.txt'
12
13
def my_split(s, seps): # this function splits line to parts separated with given separators
14
res = [s]
15
for sep in seps:
16
s, res = res, []
17
for seq in s:
18
res += seq.split(sep)
19
i = 0
20
while i < len(res):
21
if res[i] == '':
22
res.pop(i)
23
continue
24
i += 1
25
return res
26
27
28
def loadFinamCsv(fname):
29
if not os.path.isfile(fname):
30
raise ValueError('wrong file name: %s' % fname)
31
32
counter = 0
33
34
fi = open(fname, 'r')
35
36
tickerNameIsFound = False
37
38
for line in fi: # this loop counts number of bars and reads ticker name from the first bar
39
firstSymbol = line[:1]
40
if firstSymbol == '' or firstSymbol == '<':
41
continue
42
if not tickerNameIsFound:
43
parsed = my_split(line, ',\n')
44
ticker = parsed[0]
45
period = parsed[1]
46
tickerNameIsFound = True
47
counter += 1
48
49
bars = np.zeros((counter, 6), dtype=np.float64) # create matrix for reading the whole file
50
51
print(counter)
52
53
fi.seek(0, 0) # move file pointer to the beginning
54
55
counter = 0
56
57
for line in fi:
58
firstSymbol = line[:1]
59
if firstSymbol == '' or firstSymbol == '<':
60
continue
61
62
parsed = my_split(line, ';,\n')
63
64
timeStamp = parsed[2] + parsed[3]
65
dtime = time.strptime(timeStamp + '+0300', '%Y%m%d%H%M%S%z')
66
timeEpoch = time.mktime(dtime)
67
68
bars[counter, :] = np.array((timeEpoch, np.float64(parsed[4]), np.float64(parsed[5]),
69
np.float64(parsed[6]), np.float64(parsed[7]), np.float64(parsed[8])))
70
71
counter += 1
72
if counter % 1000 == 0:
73
print(int(counter / 1000), end=' ')
74
75
fi.close()
76
print('\n')
77
78
return {'ticker': ticker, 'period': period, 'bars': bars}
79
80
81
def convertPeriodString(periodRaw):
82
try:
83
numMins = int(periodRaw)
84
if numMins % 60 != 0:
85
return 'M%d' % numMins
86
else:
87
return 'H%d' % (numMins // 60)
88
except ValueError:
89
return periodRaw
90
91
92
timeZoneDiffSecs = 3 * 3600 # we need to know in advance the time zone difference between UTC
93
pt = 0.01 # we need to know in advance the min price step (point)
94
95
data = loadFinamCsv(dataFile)
96
ticker = data['ticker']
97
period = data['period']
98
bars = data['bars']
99
100
periodFine = convertPeriodString(period)
101
102
xs = np.array(range(bars.shape[0]))
103
104
bodyCentres = 0.5 * (bars[:, 1] + bars[:, 4])
105
bodySpans = 0.5 * (bars[:, 4] - bars[:, 1])
106
totalCentres = 0.5 * (bars[:, 2] + bars[:, 3])
107
totalSpans = 0.5 * (bars[:, 2] - bars[:, 3])
108
109
blackBars = np.abs(bodySpans) < 0.25 * pt
110
greenBars = np.logical_and(np.logical_not(blackBars),
111
bodySpans >= 0.25 * pt)
112
redBars = np.logical_not(np.logical_or(blackBars, greenBars))
113
114
plt.clf()
115
116
plt.errorbar(xs[blackBars], totalCentres[blackBars], yerr=totalSpans[blackBars], ecolor='k', elinewidth=0.5, capsize=0,
117
ls='none')
118
plt.errorbar(xs[blackBars], bodyCentres[blackBars], yerr=np.abs(bodySpans[blackBars]), ecolor='k', elinewidth=0.5,
119
capsize=2, ls='none')
120
121
plt.errorbar(xs[greenBars], totalCentres[greenBars], yerr=totalSpans[greenBars], ecolor='g', elinewidth=0.5, capsize=0,
122
ls='none')
123
plt.errorbar(xs[greenBars], bodyCentres[greenBars], yerr=np.abs(bodySpans[greenBars]), ecolor='g', elinewidth=0.5,
124
capsize=2, ls='none')
125
126
plt.errorbar(xs[redBars], totalCentres[redBars], yerr=totalSpans[redBars], ecolor='r', elinewidth=0.5, capsize=0,
127
ls='none')
128
plt.errorbar(xs[redBars], bodyCentres[redBars], yerr=np.abs(bodySpans[redBars]), ecolor='r', elinewidth=0.5, capsize=2,
129
ls='none')
130
131
plt.xlabel('Bar No., %s' % periodFine)
132
plt.ylabel(ticker) # before was: fname[ : fname.find( ' ' ) ]
133
134
plt.xlim(xs[0] - 0.5, xs[-1] + 0.5)
135
136
plt.annotate('start: %s' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(bars[0, 0] + timeZoneDiffSecs))),
137
xy=(0.1, 0.95), xycoords='axes fraction',
138
fontsize=11, horizontalalignment='left', verticalalignment='top')
139
140
plt.annotate('end: %s' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(bars[-1, 0] + timeZoneDiffSecs))),
141
xy=(0.1, 0.90), xycoords='axes fraction',
142
fontsize=11, horizontalalignment='left', verticalalignment='top')
143
144
plt.savefig(dataFile[: dataFile.rfind('.')] + '.png')
145
146
plt.show()
147
148