nardew / talipp

talipp - incremental technical analysis library for python
https://nardew.github.io/talipp
MIT License
368 stars 59 forks source link

Need to convert BB response as Json , #54

Closed rakesh433jntu closed 3 years ago

rakesh433jntu commented 3 years ago

Hi Team , I am not good at Python, so i am using talipp library in s flask rest service , and consuming in my client application.

When i am trying to conver "BollingerBand" response to Json , so i can consume in my client app. BB response returned as a list of custom class.
By default custom classes are can not serialized , if i tries to cast as "talipp.indicators.BB.BBval" but i am not able to find BBVal class BB has no BBval kind of error.

Please keep some sample code to ,convert response serialized , to i can send its as json to my client app. below is sample code to which i am trying. Thank you

@dataclass class BBVal: lb: float = None cb: float = None ub: float = None

def encode_Bbaval(val): if isinstance(val, BBVal): print('Ima coming') return {'lb': val.ub , 'cb': val.cb, 'ub': val.ub}

else:


       close = numpy.asarray(request.json['close'])
        period = request.json['period']
        # deviation = request.json['deviation']
        # print(deviation)
        bbVals = BBVal(list(BB(period,2, close)))
        print(type(bbVals))
        print(bbVals)
        #for x in bbVals:
        #    print(type(BBVal(x)))
            #jsonfields = json.dumps(x, default=encode_Bbaval)
        # print(type(bbVals))
        # jsonfields = json.dumps(bbVals,default=encode_Bbaval)
        # print(jsonfields)
        #return bbVals
        # return numpy.array(testSample).tolist()
nardew commented 3 years ago

Hi @rakesh433jntu, there are multiple options:

1/ use directly to_lists() method which returns a list of of converted dataclasses (i.e. BBVal) into a dictionary which can be dumped into json easily.

bb = BB(5, 1, list(range(0, 100, 9)))
print(bb.to_lists())

{'lb': [5.272077938642145, 14.272077938642145, 23.272077938642145, 32.27207793864214, 41.27207793864214, 50.27207793864214, 59.27207793864214, 68.27207793864214], 
'cb': [18.0, 27.0, 36.0, 45.0, 54.0, 63.0, 72.0, 81.0], 
'ub': [30.727922061357855, 39.72792206135786, 48.72792206135786, 57.72792206135786, 66.72792206135786, 75.72792206135786, 84.72792206135786, 93.72792206135786]}

2/ you can use jsonpickle package to serialize whole indicator. Serializing and deserializing of whole indicator is demonstrated in examples/serialization.py.

nardew commented 3 years ago

Closed as inactive for long period.