1

I'm scraping prices data from a website and save them to a CSV file

enter image description here

I'm using "plotly.graph_objects" to draw the chart after I finish the scraping and it's work fine, but what I want to do is to automatically update the chart every time a new row added to the CSV file without waiting until all the work finish to draw it.

this is my code

import plotly.graph_objects as go
import pandas as pd

df = pd.read_csv("30122019-062734.csv")
fig = go.Figure()

fig.add_trace(go.Scatter(
                x=df.Date,
                y=df['MACD'],
                name="MACD",
                line_color='blue',
                opacity=0.8))
fig.add_trace(go.Scatter(
                x=df.Date,
                y=df['SIGNAL'],
                name="Signal",
                line_color='red',
                opacity=0.8))

fig.update_layout(
    title="Plot Title",
    font=dict(
        family="Courier New, monospace",
        size=18,
        color="#7f7f7f"))


fig.show()

and this a review

enter image description here

is there a way to make it automatically updated every time a new row added?

B. Okba
  • 1,021
  • 12
  • 16
  • Are you wanting to [Watch a file for changes](https://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes) and then perform actions on it? – Sunny Patel Dec 30 '19 at 16:39
  • Sunny Patel, this chart has been drawn from the rows in a CSV file, so I want to update this chart every time a new row has added. – B. Okba Dec 30 '19 at 17:02
  • You'll have to create a relationship between the last row drawn and the last row captured in the CSV, and only add the new lines in the updated CSV, right? – Sunny Patel Dec 30 '19 at 17:08
  • 1
    Sunny Patel, thanks for your reply, I just found a solution, you can check it if you are also interested. – B. Okba Dec 30 '19 at 18:06

1 Answers1

4

I just found a solution, thanks to my hero Corey Schafer and his useful tutorial on YouTube : https://www.youtube.com/watch?v=Ercd-Ip5PfQ

import pandas as pd 
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

plt.style.use('fivethirtyeight')

def animate(i):
    data = pd.read_csv('data.csv')
    x  = data['x_values']
    y1 = data['y1_values']
    y2 = data['y2_values']
    plt.cla()
    plt.plot(x, y1, label='Channel 1')
    plt.plot(x, y2, label='Channel 2')

    plt.legend(loc='upper left')
    plt.tight_layout()

ani = FuncAnimation(plt.gcf(), animate, interval=1000)

plt.tight_layout()
plt.show()
B. Okba
  • 1,021
  • 12
  • 16