4
4
"""
5
5
6
6
import numpy as np
7
+ import pandas as pd
7
8
import matplotlib .dates as mdates
8
9
import datetime
9
10
10
11
from matplotlib import colors as mcolors
11
- from matplotlib .patches import Rectangle
12
- from matplotlib . collections import LineCollection , PolyCollection , PatchCollection
12
+ from matplotlib .collections import LineCollection , PolyCollection
13
+ from mplfinance . _arg_validators import _process_kwargs , _validate_vkwargs_dict
13
14
14
15
from six .moves import zip
15
16
@@ -89,6 +90,10 @@ def _calculate_atr(atr_length, highs, lows, closes):
89
90
all_lows : list of lows
90
91
all_closes : list of closes
91
92
"""
93
+ if atr_length < 0 :
94
+ raise ValueError ("Specified atr_length may not be less than 0" )
95
+ elif atr_length > len (closes ):
96
+ raise ValueError ("Specified atr_length is larger than the length of the dataset: " + str (len (closes )))
92
97
atr = 0
93
98
for i in range (len (highs )- atr_length , len (highs )):
94
99
high = highs [i ]
@@ -103,7 +108,7 @@ def renko_reformat_ydata(ydata, dates, old_dates):
103
108
outputs for the user as the xaxis does not scale evenly with dates.
104
109
Missing dates ydata is averaged into the next date and dates that appear
105
110
more than once have the same ydata
106
- ydata : y data
111
+ ydata : y data likely coming from addplot
107
112
dates : x-axis dates for the renko chart
108
113
old_dates : original dates in the data set
109
114
"""
@@ -132,6 +137,29 @@ def _updown_colors(upcolor,downcolor,opens,closes,use_prev_close=False):
132
137
_list = [ cmap [pre < cls ] for cls ,pre in zip (closes [1 :], closes ) ]
133
138
return [first ] + _list
134
139
140
+ def _valid_renko_kwargs ():
141
+ '''
142
+ Construct and return the "valid renko kwargs table" for the mplfinance.plot(type='renko') function.
143
+ A valid kwargs table is a `dict` of `dict`s. The keys of the outer dict are the
144
+ valid key-words for the function. The value for each key is a dict containing
145
+ 2 specific keys: "Default", and "Validator" with the following values:
146
+ "Default" - The default value for the kwarg if none is specified.
147
+ "Validator" - A function that takes the caller specified value for the kwarg,
148
+ and validates that it is the correct type, and (for kwargs with
149
+ a limited set of allowed values) may also validate that the
150
+ kwarg value is one of the allowed values.
151
+ '''
152
+ vkwargs = {
153
+ 'brick_size' : { 'Default' : 2.0 ,
154
+ 'Validator' : lambda value : isinstance (value ,float ) or isinstance (value ,int ) or value == 'atr' },
155
+ 'atr_length' : { 'Default' : 14 ,
156
+ 'Validator' : lambda value : isinstance (value ,int ) },
157
+ }
158
+
159
+ _validate_vkwargs_dict (vkwargs )
160
+
161
+ return vkwargs
162
+
135
163
def _construct_ohlc_collections (dates , opens , highs , lows , closes , marketcolors = None ):
136
164
"""Represent the time, open, high, low, close as a vertical line
137
165
ranging from low to high. The left tick is the open and the right
@@ -302,7 +330,7 @@ def _construct_candlestick_collections(dates, opens, highs, lows, closes, market
302
330
303
331
return rangeCollection , barCollection
304
332
305
- def _construct_renko_collections (dates , highs , lows , volumes , renko_params , closes , marketcolors = None ):
333
+ def _construct_renko_collections (dates , highs , lows , volumes , config_renko_params , closes , marketcolors = None ):
306
334
"""Represent the price change with bricks
307
335
308
336
Parameters
@@ -326,15 +354,14 @@ def _construct_renko_collections(dates, highs, lows, volumes, renko_params, clos
326
354
ret : tuple
327
355
rectCollection
328
356
"""
357
+ renko_params = _process_kwargs (config_renko_params , _valid_renko_kwargs ())
329
358
if marketcolors is None :
330
359
marketcolors = _get_mpfstyle ('classic' )['marketcolors' ]
331
360
print ('default market colors:' ,marketcolors )
332
361
333
362
brick_size = renko_params ['brick_size' ]
334
363
atr_length = renko_params ['atr_length' ]
335
-
336
- if atr_length > len (closes ):
337
- raise ValueError ("Specified atr_length is larger than the length of the dataset: " + str (len (closes )))
364
+
338
365
339
366
if brick_size == 'atr' :
340
367
brick_size = _calculate_atr (atr_length , highs , lows , closes )
@@ -363,6 +390,8 @@ def _construct_renko_collections(dates, highs, lows, volumes, renko_params, clos
363
390
364
391
if num_bricks != 0 :
365
392
new_dates .extend ([dates [i ]]* num_bricks )
393
+ if volumes [i ] is None : # No values passed in for volume and volume=True
394
+ volumes [i ] = 0
366
395
new_volumes .extend ([volumes [i ] + volume_cache ]* num_bricks )
367
396
volume_cache = 0
368
397
else :
@@ -376,6 +405,7 @@ def _construct_renko_collections(dates, highs, lows, volumes, renko_params, clos
376
405
verts = []
377
406
colors = []
378
407
edge_colors = []
408
+ brick_values = []
379
409
for index , number in enumerate (bricks ):
380
410
if number == 1 : # up brick
381
411
colors .append (uc )
@@ -385,7 +415,9 @@ def _construct_renko_collections(dates, highs, lows, volumes, renko_params, clos
385
415
edge_colors .append (edc )
386
416
387
417
prev_num += number
388
- x , y = index , start_price + (prev_num * brick_size )
418
+ brick_y = start_price + (prev_num * brick_size )
419
+ brick_values .append (brick_y )
420
+ x , y = index , brick_y
389
421
390
422
verts .append ((
391
423
(x , y ),
@@ -394,6 +426,8 @@ def _construct_renko_collections(dates, highs, lows, volumes, renko_params, clos
394
426
(x + 1 , y )))
395
427
396
428
429
+ bricks_df = pd .DataFrame (brick_values ) # turn brick_values into a dataframe to be able to call .rolling to calculate mav
430
+
397
431
useAA = 0 , # use tuple here
398
432
lw = None
399
433
rectCollection = PolyCollection (verts ,
@@ -403,7 +437,7 @@ def _construct_renko_collections(dates, highs, lows, volumes, renko_params, clos
403
437
linewidths = lw
404
438
)
405
439
406
- return (rectCollection , ), new_dates , new_volumes
440
+ return (rectCollection , ), new_dates , new_volumes , bricks_df
407
441
408
442
from matplotlib .ticker import Formatter
409
443
class IntegerIndexDateTimeFormatter (Formatter ):
0 commit comments