Related
i have two(n) websocket messages input like this, separated by "==new msg=="
(don't know why but some of the messages are longer..)
++Rcv raw: b'\x81~\x02\xff{"data":[{"c":null,"p":20926.99,"s":"BINANCE:BTCUSDT","t":1656017217026,"v":0.0008},{"c":null,"p":20927.45,"s":"BINANCE:BTCUSDT","t":1656017217056,"v":0.0005},{"c":null,"p":20930.51,"s":"BINANCE:BTCUSDT","t":1656017217079,"v":0.001},{"c":null,"p":20930.51,"s":"BINANCE:BTCUSDT","t":1656017217079,"v":0.00061},{"c":null,"p":20930.52,"s":"BINANCE:BTCUSDT","t":1656017217079,"v":0.1},{"c":null,"p":20931.18,"s":"BINANCE:BTCUSDT","t":1656017217079,"v":0.05098},{"c":null,"p":20930.5,"s":"BINANCE:BTCUSDT","t":1656017217201,"v":0.03},{"c":null,"p":20930.5,"s":"BINANCE:BTCUSDT","t":1656017217201,"v":0.03654},{"c":null,"p":20927.9,"s":"BINANCE:BTCUSDT","t":1656017217649,"v":0.03},{"c":null,"p":20927.9,"s":"BINANCE:BTCUSDT","t":1656017217649,"v":0.01882}],"type":"trade"}'
++Rcv decoded: fin=1 opcode=1 data=b'{"data":[{"c":null,"p":20926.99,"s":"BINANCE:BTCUSDT","t":1656017217026,"v":0.0008},{"c":null,"p":20927.45,"s":"BINANCE:BTCUSDT","t":1656017217056,"v":0.0005},{"c":null,"p":20930.51,"s":"BINANCE:BTCUSDT","t":1656017217079,"v":0.001},{"c":null,"p":20930.51,"s":"BINANCE:BTCUSDT","t":1656017217079,"v":0.00061},{"c":null,"p":20930.52,"s":"BINANCE:BTCUSDT","t":1656017217079,"v":0.1},{"c":null,"p":20931.18,"s":"BINANCE:BTCUSDT","t":1656017217079,"v":0.05098},{"c":null,"p":20930.5,"s":"BINANCE:BTCUSDT","t":1656017217201,"v":0.03},{"c":null,"p":20930.5,"s":"BINANCE:BTCUSDT","t":1656017217201,"v":0.03654},{"c":null,"p":20927.9,"s":"BINANCE:BTCUSDT","t":1656017217649,"v":0.03},{"c":null,"p":20927.9,"s":"BINANCE:BTCUSDT","t":1656017217649,"v":0.01882}],"type":"trade"}'
==new msg==
++Rcv raw: b'\x81~\x03\x03{"data":[{"c":null,"p":20927.9,"s":"BINANCE:BTCUSDT","t":1656017217649,"v":0.08477},{"c":null,"p":20927.89,"s":"BINANCE:BTCUSDT","t":1656017217678,"v":0.1},{"c":null,"p":20927.89,"s":"BINANCE:BTCUSDT","t":1656017217678,"v":0.25},{"c":null,"p":20927.89,"s":"BINANCE:BTCUSDT","t":1656017217678,"v":0.07053},{"c":null,"p":20927.89,"s":"BINANCE:BTCUSDT","t":1656017217694,"v":0.08207},{"c":null,"p":20926.98,"s":"BINANCE:BTCUSDT","t":1656017217698,"v":0.05098},{"c":null,"p":20926.31,"s":"BINANCE:BTCUSDT","t":1656017217698,"v":0.1},{"c":null,"p":20925.5,"s":"BINANCE:BTCUSDT","t":1656017217698,"v":0.16424},{"c":null,"p":20927.87,"s":"BINANCE:BTCUSDT","t":1656017217711,"v":0.00052},{"c":null,"p":20923.16,"s":"BINANCE:BTCUSDT","t":1656017217927,"v":0.0155}],"type":"trade"}'
++Rcv decoded: fin=1 opcode=1 data=b'{"data":[{"c":null,"p":20927.9,"s":"BINANCE:BTCUSDT","t":1656017217649,"v":0.08477},{"c":null,"p":20927.89,"s":"BINANCE:BTCUSDT","t":1656017217678,"v":0.1},{"c":null,"p":20927.89,"s":"BINANCE:BTCUSDT","t":1656017217678,"v":0.25},{"c":null,"p":20927.89,"s":"BINANCE:BTCUSDT","t":1656017217678,"v":0.07053},{"c":null,"p":20927.89,"s":"BINANCE:BTCUSDT","t":1656017217694,"v":0.08207},{"c":null,"p":20926.98,"s":"BINANCE:BTCUSDT","t":1656017217698,"v":0.05098},{"c":null,"p":20926.31,"s":"BINANCE:BTCUSDT","t":1656017217698,"v":0.1},{"c":null,"p":20925.5,"s":"BINANCE:BTCUSDT","t":1656017217698,"v":0.16424},{"c":null,"p":20927.87,"s":"BINANCE:BTCUSDT","t":1656017217711,"v":0.00052},{"c":null,"p":20923.16,"s":"BINANCE:BTCUSDT","t":1656017217927,"v":0.0155}],"type":"trade"}'
==new msg==
and i have some code so far
import websocket
import json
from collections import ChainMap
y = []
c = []
def on_message(ws, message):
print("==new msg==")
y.append(json.loads(message))
def on_error(ws, error):
print(error)
def on_close(ws,close_status_code, close_reason):
print("==closed==")
print(len(y))
c = dict(ChainMap(*y))
print(c)
def on_open(ws):
ws.send('{"type":"subscribe","symbol":"BINANCE:BTCUSDT"}')
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://ws.finnhub.io?token=****ps2ad3iahju47mdg",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
the output is:
==closed==
2
{'data': [{'c': None, 'p': 20926.99, 's': 'BINANCE:BTCUSDT', 't': 1656017217026, 'v': 0.0008}, {'c': None, 'p': 20927.45, 's': 'BINANCE:BTCUSDT', 't': 1656017217056, 'v': 0.0005}, {'c': None, 'p': 20930.51, 's': 'BINANCE:BTCUSDT', 't': 1656017217079, 'v': 0.001}, {'c': None, 'p': 20930.51, 's': 'BINANCE:BTCUSDT', 't': 1656017217079, 'v': 0.00061}, {'c': None, 'p': 20930.52, 's': 'BINANCE:BTCUSDT', 't': 1656017217079, 'v': 0.1}, {'c': None, 'p': 20931.18, 's': 'BINANCE:BTCUSDT', 't': 1656017217079, 'v': 0.05098}, {'c': None, 'p': 20930.5, 's': 'BINANCE:BTCUSDT', 't': 1656017217201, 'v': 0.03}, {'c': None, 'p': 20930.5, 's': 'BINANCE:BTCUSDT', 't': 1656017217201, 'v': 0.03654}, {'c': None, 'p': 20927.9, 's': 'BINANCE:BTCUSDT', 't': 1656017217649, 'v': 0.03}, {'c': None, 'p': 20927.9, 's': 'BINANCE:BTCUSDT', 't': 1656017217649, 'v': 0.01882}], 'type': 'trade'}
only from the first message..?
The goal is to calculate the volume-weighted average price of trades made during a 1 min interval
output should look like this:
2022-05-04 12:22:33 price:20926.99 volume:0.0008
2022-05-04 12:23:43 price:20926.99 volume:0.0058
2022-05-04 12:24:53 price:20927.99 volume:0.0608
I am accessing an API through a get request from which I get a response.
This is my code:
import requests
import json
symbol = "AAPL"
end_point="https://api.polygon.io/v2/snapshot/locale/us/markets/stocks/tickers/"+symbol+"?apiKey=my_key"
r=requests.get(end_point).json()
print(r)
print(r['min'])
print(r) returned:
{'request_id': '2735c0be51de7719fd99460fe8696080', 'status': 'OK', 'ticker': {'day': {'c': 172.93, 'h': 175.48, 'l': 172.37, 'o': 174.14, 'v': 65575561, 'vw': 174.0984}, 'lastQuote': {'P': 172.83, 'S': 3, 'p': 172.82, 's': 1, 't': 1644524332922450142}, 'lastTrade': {'c': None, 'i': '139592', 'p': 172.8199, 's': 2014, 't': 1644524331573573011, 'x': 4}, 'min': {'av': 65559987, 'c': 172.9, 'h': 173.14, 'l': 172.89, 'o': 173.09, 'v': 107429, 'vw': 173.0138}, 'prevDay': {'c': 176.28, 'h': 176.65, 'l': 174.9, 'o': 176.05, 'v': 71204538, 'vw': 175.8287}, 'ticker': 'AAPL', 'todaysChange': -3.46, 'todaysChangePerc': -1.963, 'updated': 1644524331573573011}}
but when I try to access the key "min", I get key error:
KeyError: 'min'
This is super-simple. What am I doing wrong?
Please try:
r['ticker']['min']
the key min is inside ticker. Do this:
r['ticker']['min']
I am trying to extract information from a list within a list within a list to end up with something like this from the information below: ('h': '0.77584', 'l': '0.77292'), ('h': '0.77521', 'l': '0.77206')
print(dict)
[{'complete': True, 'volume': 2290, 'time': '2021-01-15', 'mid': {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}}, {'complete': True, 'volume': 2312, 'time': '2021-01-15', 'mid': {'o': '0.77436', 'h': '0.77521', 'l': '0.77206', 'c': '0.77206'}}]
Not sure how to go about it. I tried
something = list(list(dict.items())[0].items())[3][1]
print(something)
However, this returned {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}
How to get the requested data?
You can use the following list and dict comprehension
dict = [{'complete': True, 'volume': 2290, 'time': '2021-01-15', 'mid': {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}}, {'complete': True, 'volume': 2312, 'time': '2021-01-15', 'mid': {'o': '0.77436', 'h': '0.77521', 'l': '0.77206', 'c': '0.77206'}}]
res = [{k:v for k, v in i['mid'].items() if k in 'hl'} for i in dict]
print(res)
Output
[{'h': '0.77584', 'l': '0.77292'}, {'h': '0.77521', 'l': '0.77206'}]
First you can take the mid child from each parent dictionary in the list.
dict = [{'complete': True, 'volume': 2290, 'time': '2021-01-15', 'mid': {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}}, {'complete': True, 'volume': 2312, 'time': '2021-01-15', 'mid': {'o': '0.77436', 'h': '0.77521', 'l': '0.77206', 'c': '0.77206'}}]
old_dict = [dict[0]['mid'],dict[1]['mid']]
Then loop through those entries and filter based off the keys (i.e. remove o and c):
list_you_want = []
for i in [0,1]:
list_you_want.append({ your_key: old_dict[i][your_key] for your_key in ['h','l'] })
Which gives you:
[{'h': '0.77584', 'l': '0.77292'}, {'h': '0.77521', 'l': '0.77206'}]
This question already has an answer here:
Why does the print function return None?
(1 answer)
Closed 2 years ago.
I am all new to programming and have to develop a simple script that converts a word into NATO-language. I have figured out (through Google) how to convert the word to NATO, but it also returns 'None'? Why does it do that?
def textToNato(plainText):
d = {
'A': 'Alpha', 'B': 'Bravo', 'C': 'Charlie',
'D': 'Delta', 'E': 'Echo', 'F': 'Foxtrot',
'G': 'Golf', 'H': 'Hotel', 'I': 'India',
'J': 'Juliett','K': 'Kilo', 'L': 'Lima',
'M': 'Mike', 'N': 'November','O': 'Oscar',
'P': 'Papa', 'Q': 'Quebec', 'R': 'Romeo',
'S': 'Sierra', 'T': 'Tango', 'U': 'Uniform',
'V': 'Victor', 'W': 'Whiskey', 'X': 'X-ray',
'Y': 'Yankee', 'Z': 'Zulu'}
natoText = print('-'.join([d[x] for x in [*plainText.upper()]]))
return natoText
natoText = print(...)
Print returns None, that's the reason behind the issue. What you should do is
natoText = '-'.join([d[x] for x in plainText.upper()])
print (natoText) #if you need to print here
return natoText
I have get this txt file
A:{A:0, B:6, C:4, D:3, E:0, F:0, G:0}
B:{A:6, B:0, C:2, D:0, E:4, F:0, G:0}
C:{A:4, B:2, C:0, D:2, E:0, F:8, G:0}
D:{A:3, B:0, C:2, D:0, E:3, F:0, G:0}
E:{A:0, B:4, C:0, D:3, E:0, F:7, G:6}
F:{A:0, B:0, C:8, D:0, E:7, F:0, G:6}
G:{A:0, B:0, C:0, D:0, E:6, F:6, G:0}
titles = []
with open("graph.txt", "r") as file:
for line in file:
column=line.split(":")
title=column[0]
titles.append(title)
i need to make dictionaries for each title which i got like A,B,C
Format each line properly and you can use ast.literal_eval. I used regex to find each key and replace it with the same key surrounded by quotes.
import ast
import re
KEY_PATTERN = re.compile(r'(\w+?):')
dics = []
with open('graph.txt') as f:
for line in f:
line = line.strip()
if line:
dic_str = "{" + KEY_PATTERN.sub(r'"\g<1>":', line) + "}"
dics.append(ast.literal_eval(dic_str))
print(dics)
Can be shorter (though harder to read):
import ast
import re
KEY_PATTERN = re.compile(r'(\w+?):')
with open('graph.txt') as f:
dics = [ast.literal_eval("{" + KEY_PATTERN.sub(r'"\g<1>":', line) + "}") for line in f if line.strip()]
print(dics)
Output:
[{'A': {'A': 0, 'B': 6, 'C': 4, 'D': 3, 'E': 0, 'F': 0, 'G': 0}}, {'B': {'A': 6, 'B': 0, 'C': 2, 'D': 0, 'E': 4, 'F': 0, 'G': 0}}, {'C': {'A': 4, 'B': 2, 'C': 0, 'D': 2, 'E': 0, 'F': 8, 'G': 0}}, {'D': {'A': 3, 'B': 0, 'C': 2, 'D': 0, 'E':3, 'F': 0, 'G': 0}}, {'E': {'A': 0, 'B': 4, 'C': 0, 'D': 3, 'E': 0, 'F': 7, 'G': 6}}, {'F': {'A': 0, 'B': 0, 'C': 8, 'D': 0, 'E': 7, 'F': 0, 'G': 6}}, {'G': {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 6, 'F': 6, 'G': 0}}]
If you want the result to be just one dict than change:
dics = []
# and
dics.append(ast.literal_eval(dic_str))
to
dics = {}
# and
dics.update(ast.literal_eval(dic_str))
This can be achieved with the following sample:
import re
titles = []
with open("graph.txt", "r") as file:
for line in file:
if ':' in line:
title=re.match(r"^(.*?):", line).groups()[0]
dict_str= re.match("^.*?\{(.*?)\}", line).groups()[0]
dictionary = {key:value for (key,value) in (item.strip().split(':') for item in dict_str.split(','))}
titles.append({title: dictionary})
for item in titles:
print(item)
This will produce output like:
{'A': {'A': '0', 'C': '4', 'B': '6', 'E': '0', 'D': '3', 'G': '0', 'F': '0'}}
{'B': {'A': '6', 'C': '2', 'B': '0', 'E': '4', 'D': '0', 'G': '0', 'F': '0'}}
{'C': {'A': '4', 'C': '0', 'B': '2', 'E': '0', 'D': '2', 'G': '0', 'F': '8'}}
{'D': {'A': '3', 'C': '2', 'B': '0', 'E': '3', 'D': '0', 'G': '0', 'F': '0'}}
{'E': {'A': '0', 'C': '0', 'B': '4', 'E': '0', 'D': '3', 'G': '6', 'F': '7'}}
{'F': {'A': '0', 'C': '8', 'B': '0', 'E': '7', 'D': '0', 'G': '6', 'F': '0'}}
{'G': {'A': '0', 'C': '0', 'B': '0', 'E': '6', 'D': '0', 'G': '0', 'F': '6'}}