Python Forum

Full Version: Create simple live plot of stock data
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The below code us just some start of learning python quicker by using a real world example and trying out different things. It's nothing that will be used later on so nothing more then learning material. Will go from raw dirty to refine using functions etc.

The below code just grabs the current price of a crypto asset and adds it to the dictionary together with the date (in datetime format). I'm trying to create a (live) plot (part not worked on) but I'm a bit stuck in how to make sure equal values in consecutive key/value pairs don't get added to the dictionary. This would result in an unreadable plot.

I have the following questions:

- Is it better to filter the value up front? How can I handle this requirement of not having two consecutive dictionary items with the same value?
- what time format would be best for plotting?

* I have not looked at plot yet
* x is in there just not to test and not have it run forever
* the file save is just there for later usage


import json
import requests
import csv
import datetime
import matplotlib.pyplot as plt
import time

last_trade = {}

for x in range (0,5):
   
    x -= 1
    uri = "https://api.kraken.com/0/public/Ticker?pair=XMREUR"
    date = datetime.datetime.now()
    r = requests.get(uri)
    result = r.json()["result"]['XXMRZEUR']["c"][0]	
    last_trade.update ({date:result})
    print (last_trade)
    time.sleep(180)

with open('ticker.csv', 'w') as csv_file:

    writer = csv.writer(csv_file)
    for key, value in last_trade.items():
    writer.writerow([key, value])


x,y = zip(*sorted(last_trade.items()))
plt.plot(x,y)
Your code does not run, so I made some changes.

#!/usr/bin/python3
import json
import requests
import csv
import datetime
import matplotlib.pyplot as plt
import time

last_trade = {}

for x in range (0,5):
    x -= 1
    uri = "https://api.kraken.com/0/public/Ticker?pair=XMREUR"
    date = datetime.datetime.now()
    r = requests.get(uri)
    result = r.json()["result"]['XXMRZEUR']["c"][0].
    last_trade.update ({date:result})
    print (last_trade)
    time.sleep(3)

with open('ticker.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    for key, value in last_trade.items():
        writer.writerow([key, value])

x,y = zip(*sorted(last_trade.items()))
plt.plot(x,y)
plt.show()
We can substitute some other value for it.we become what we behold