How to recover values from a JSON file to treat them with a sript python?

2

I have a JSON file valorMercado.js with the following values:

{"BTC":{"USD":2167.85},"ETH":{"USD":167.88},"DASH":{"USD":102.31}}
{"BTC":{"USD":2253.12},"ETH":{"USD":177.76},"DASH":{"USD":109.17}}
{"BTC":{"USD":2251.47},"ETH":{"USD":177.71},"DASH":{"USD":109.12}}
...

Each time a new line is added, I want to make the average on the last five numbers of each coin to make the simple moving average ("Simple Moving Average"). However, I do not know how to recover the values from the mercaval.js file to treat them.

import numpy as np

# leer el fichero, cada vez hay una otra valor poner las 5 ultimas en a y la ultima en lastValue

fiveLast = np.array(a[-5:])
lastValue = a[-1]

# calculemos sma
fiveLastMean = np.mean(fiveLast)

# poner en marcha una alerta si lastValue < o > nowValue

for i in a.shape[1] :
    if (fiveLastMean[1] < nowValue[1]):
        result[i] = buy
    else if(fiveLastMean[1] > nowValue[1]):
        result[i] = sell

The output should be a matrix of variables that belong to {buy, leave, sold}. For example:

[buy, buy, leave]

For "buy BTC, ETH and do nothing with DASH".

    
asked by ThePassenger 29.05.2017 в 12:48
source

1 answer

0

First of all, just as you wrote the example of a file it does not seem to be a valid JSON, I suppose you should have the [] to indicate that it is a list and , to separate each item. If you actually have it as you indicate, we should first re-format it as I mentioned it to be able to read it as Json.

Using json.loads to read from a string of characters or json.load to read directly from the file, it's all quite simple.

import json
import numpy as np

json_text = """
[
{"BTC":{"USD":2167.85},"ETH":{"USD":167.88},"DASH":{"USD":102.31}},
{"BTC":{"USD":2253.12},"ETH":{"USD":177.76},"DASH":{"USD":109.17}},
{"BTC":{"USD":2251.47},"ETH":{"USD":177.71},"DASH":{"USD":109.12}}
]
"""

a = json.loads(json_text)

values = [(each["BTC"].get("USD"), each["ETH"].get("USD"), each["DASH"].get("USD")) for each in a]

fiveLast = np.array(values[-5:])

print(fiveLast)

After reading the valid Json what we get is a list of dictionaries in the Python jargon, what we do next is to convert that list into a list of tuples where basically each column is the value of BTC.USD, ETH. USD, DASH.USD. Converting this to a numpy array is trivial.

[[ 2167.85   167.88   102.31]
 [ 2253.12   177.76   109.17]
 [ 2251.47   177.71   109.12]]
    
answered by 29.05.2017 в 17:18