-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathichimoku-viewer.py
executable file
·255 lines (220 loc) · 8.22 KB
/
ichimoku-viewer.py
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#!/usr/bin/env python3
# append to a dataframe a.append(pd.DataFrame({'close':99.99},index=[datetime.datetime.now()])
import matplotlib.pyplot as plt
from matplotlib import gridspec
import sys
import os
import argparse
import datetime
from core.CountryInfo import CountryInfo
from helpers.DataOperations import *
from core.ReportSignals import *
from core.TimeInterval import *
from core.assets import StockAssets
from indicators.StockData import StockData
from indicators.ichimoku import Ichimoku
from indicators.ichimokuPhase import IchimokuPhase
from indicators.candlestickpatterns import CandlestickPatterns
from indicators.zigzag import ZigZag
# Create plot figures file
def PlotSave(fig):
global graphsCreated
# emf, eps, pdf, png, ps, raw, rgba, svg, svgz
# for ext in [ ".png", ".jpeg", ".svg", ".eps", ".raw"]:
# filePath = outputFilepath + str(fig.number) + ext
# plt.figure(fig.number)
# plt.savefig(filePath)
filePath = outputFilepath + str(fig.number) + outputExtension
plt.figure(fig.number)
plt.savefig(filePath)
graphsCreated.append(filePath)
print('Created plot %s.' % (filePath))
# remove all created plots
def PlotsRemove():
global graphsCreated
for filepath in graphsCreated:
os.system('rm -rf %s' % (filepath))
print('Removed %s.' % (filepath))
def ReportGraphs(f):
# Insert all created graphs
f.write('## Graphs\n\n')
for path in graphsCreated:
f.write('![Graph](%s)\n\n' % (os.path.basename(path)))
f.write('\n')
# Const objects
# #####################################################
lockTimeout = 5 * 60
executionIntervals = ['monthly', 'weekly', 'daily']
reportFile = 'output/report.md'
plotsPath = 'output/'
outputExtension = '.svg'
# Varaables
# #####################################################
# Arguments and config
# #####################################################
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--stockCode', type=str,
required=True, help='Stock name code')
parser.add_argument('-d', '--beginDate', type=str,
required=False, help='Begin date')
parser.add_argument('-Y', '--lastYear', action='store_true',
required=False, help='Last Year')
parser.add_argument('-9M', '--last9Months', action='store_true',
required=False, help='Last 9 Months')
parser.add_argument('-6M', '--last6Months', action='store_true',
required=False, help='Last 6 Months')
parser.add_argument('-3M', '--last3Months', action='store_true',
required=False, help='Last 3 Months')
parser.add_argument('-M', '--lastMonth', action='store_true',
required=False, help='Last Month')
parser.add_argument('-W', '--lastWeek', action='store_true',
required=False, help='Last Week')
parser.add_argument('-p', '--patterns', action='store_true',
required=False, help='Find price action patterns')
parser.add_argument('-g', '--plotToFile', action='store_true',
required=False, help='Plot to file')
parser.add_argument('-r', '--reports', action='store_true',
required=False, help='Generate extra reports')
parser.add_argument('-ri', '--reportsInterval', type=str,
required=False, help='Interval of extra reports')
args = parser.parse_args()
# Assert
if (not args.stockCode):
print('No stockCode!')
sys.exit(1)
# Assert
if (args.reportsInterval is not None):
if (args.reportsInterval not in executionIntervals):
print('Wrong execution interval!')
sys.exit(1)
# Create Country Info
info = CountryInfo(args.stockCode)
# Use non-interactive backend when plot to file used
if (args.plotToFile):
import matplotlib
matplotlib.use('Agg')
# Dates
today = datetime.datetime.now()
# End date
end_date = today.strftime('%Y-%m-%d')
# Start date
if (args.beginDate):
start_date = args.beginDate
else:
start_date = '2010-01-01'
# Check last year
if (args.lastYear):
tmpDate = datetime.datetime.now() - datetime.timedelta(days=365)
start_date = tmpDate.strftime('%Y-%m-%d')
# Check last 9 month
if (args.last9Months):
tmpDate = datetime.datetime.now() - datetime.timedelta(days=30 * 9)
start_date = tmpDate.strftime('%Y-%m-%d')
# Check last 6 month
if (args.last6Months):
tmpDate = datetime.datetime.now() - datetime.timedelta(days=30 * 6)
start_date = tmpDate.strftime('%Y-%m-%d')
# Check last 3 month
if (args.last3Months):
tmpDate = datetime.datetime.now() - datetime.timedelta(days=30 * 3)
start_date = tmpDate.strftime('%Y-%m-%d')
# Check last month
if (args.lastMonth):
tmpDate = datetime.datetime.now() - datetime.timedelta(days=30)
start_date = tmpDate.strftime('%Y-%m-%d')
# Check last Week
if (args.lastWeek):
tmpDate = datetime.datetime.now() - datetime.timedelta(days=7)
start_date = tmpDate.strftime('%Y-%m-%d')
# Dynamic variables
# #####################################################
outputFilename = args.stockCode + '_' + end_date + '_'
outputFilepath = plotsPath + outputFilename
graphsCreated = []
reportSignals = CreateReportSignals()
executionInterval = 'weekly'
# Update - execution Interval
if (args.reportsInterval is not None):
executionInterval = args.reportsInterval
reportSignals.SetBeginTimestamp(GetIntervalBegin(executionInterval))
reportSignals.SetStockCode(args.stockCode)
# Get stock data
# #####################################################
stockAssets = StockAssets()
stockData = StockData(args.stockCode, start_date, end_date)
stockData.SetAssets(stockAssets)
stockData.SetCurrencySymbol(info.GetCurrency())
# Create oscillators/indicators
# #####################################################
closePriceTotal = stockData.GetAllData('Close')
closePrice = stockData.GetData('Close')
ichimoku = Ichimoku(stockData.GetData('Open'),
stockData.GetData('High'),
stockData.GetData('Low'),
stockData.GetData('Close')
)
ichimokuPhase = IchimokuPhase(ichimoku,
stockData.GetData('Close')
)
zigzag = ZigZag(stockData.GetData('Open'),
stockData.GetData('High'),
stockData.GetData('Low'),
stockData.GetData('Close')
)
if (args.patterns):
candlepatterns = CandlestickPatterns(stockData.GetData())
# PLOT 5
# #####################################################
# #####################################################
fig = plt.figure(figsize=(16.0, 9.0))
# Main ichimoku plot
Rows = 6
gs = gridspec.GridSpec(Rows, 1)
plot9 = plt.subplot(gs[0:5])
stockData.PlotAssets()
ichimoku.Plot(plot9)
stockData.PlotCandle(plot9)
if (args.patterns):
candlepatterns.Plot(plot9)
plt.grid(b=True, which='major', axis='both', color='k')
# Labels
plt.ylabel('Price (%s)' % (info.GetCurrency()))
plt.title('Ichimoku %s' % stockData.GetStockCode())
plt.legend(loc='upper left')
# Bottom ichimoku phase indicator
plot10 = plt.subplot(gs[Rows - 1], sharex=plot9)
ichimokuPhase.Plot(plot10)
# Add return rates axle
# stockData.AddReturnRatesAxle(plot9)
# Plot to file or show
if (args.plotToFile):
PlotSave(fig)
# Create reports
if (args.reports):
reportAllSignalTypes = False
# If there are opened assets then report all signals
if (len(stockAssets.GetAssetsForStockCode(args.stockCode, onlyOpened=True)) != 0):
reportAllSignalTypes = True
# Daily report
if (executionInterval == 'daily'):
reportSignals.Report(reportFile, reportAllSignalTypes)
# If signals reported
if (reportSignals.reportedAnything is True) or (True):
with open(reportFile, 'a+') as f:
stockData.Report(f, executionInterval)
stockData.ReportAssets(f)
ReportGraphs(f)
# remove plots if nothing reported
else:
PlotsRemove()
# Weekly report
else:
with open(reportFile, 'a+') as f:
stockData.Report(f, executionInterval)
reportSignals.Report(reportFile, reportAllSignalTypes)
with open(reportFile, 'a+') as f:
stockData.ReportAssets(f)
ReportGraphs(f)
# Show all plots
if (not args.plotToFile):
plt.show()