如何更新每15秒将新记录追加到CSV文件的虚线图形?
问题描述
背景:
- 我有两个CSV文件:c.csv、p.csv
- 每隔15秒,就会向c.csv追加一组新记录
- 每隔15秒,一组新记录(但不同于c.csv集合)附加到p.csv
- c.csv包含SPY的看涨期权数据(列=CONTRACT_NAME、STRING、VOLUME、TIMESTAMP)
- p.csv包含SPY的看跌期权数据(列=CONTRACT_NAME、STRING、VOLUME、TIMESTAMP)
chart.py:
import pandas as pd
import numpy as np
import plotly.express as px
import dash
app = dash.Dash()
columns = ['contract', 'strike', 'vol', 'ts']
c = pd.read_csv('c.csv', header = None, names=columns)
p = pd.read_csv('p.csv', header = None, names=columns)
mode = 'lines+markers+text'
fig1 = px.scatter()
fig1.add_scatter(name='call volume', x=c['strike'], y=c['vol'], mode=mode)
fig1.add_scatter(name='put volume', x=p['strike'], y=p['vol'], mode=mode)
if __name__ == '__main__':
app.run_server()
c.csv:
# 1st 15 sec extract...
SPY200615C00304000,304.0,29507.0,,2020-06-13 13:00:00.000000
SPY200615C00303000,303.0,31638.0,2020-06-13 13:00:00.000000
SPY200615C00302000,302.0,22896.0,2020-06-13 13:00:00.000000
# 2nd 15 sec extract...
SPY200615C00304000,304.0,29777.0,,2020-06-13 13:00:15.000000
SPY200615C00303000,303.0,31987.0,2020-06-13 13:00:15.000000
SPY200615C00302000,302.0,24555.0,2020-06-13 13:00:15.000000
.
.
.
p.csv:
# 1st 15 sec extract...
SPY200615P00304000,304.0,37002.0,2020-06-13 13:00:00.000000
SPY200615P00303000,303.0,54339.0,2020-06-13 13:00:00.000000
SPY200615P00302000,302.0,43387.0,2020-06-13 13:00:00.000000
# 2nd 15 sec extract...
SPY200615P00304000,304.0,39032.0,2020-06-13 13:00:15.000000
SPY200615P00303000,303.0,67339.0,2020-06-13 13:00:15.000000
SPY200615P00302000,302.0,64342.0,2020-06-13 13:00:15.000000
.
.
.
问题/我要实现的目标:
如何才能让图1实时更新,因为两个CSV文件都追加了新记录?基本上,我只是希望用c.csv和p.csv中的最新记录替换旧的图1。我希望x轴(罢工)是静态的,而不是动态的,因为罢工总是相同的(304,303,302)。我也想保持y轴(VOL)静止。我有什么方法可以做到这一点吗?
解决方案
我认为您需要的是使用间隔作为输入运行的回调。请参阅文档中的this page。
布局中应该有这样的组件:
dcc.Interval(
id='interval-component',
interval=15*1000, # in milliseconds
n_intervals=0,
)
然后使用它作为触发器的回调,以输出到保存图表的组件:
@app.callback(Output('live-update-figure', 'children'),
[Input('interval-component', 'n_intervals')])
def update_figures(n):
columns = ['contract', 'strike', 'vol', 'ts']
c = pd.read_csv('c.csv', header = None, names=columns)
p = pd.read_csv('p.csv', header = None, names=columns)
mode = 'lines+markers+text'
fig1 = px.scatter()
fig1.add_scatter(name='call volume', x=c['strike'], y=c['vol'], mode=mode)
fig1.add_scatter(name='put volume', x=p['strike'], y=p['vol'], mode=mode)
return fig1
相关文章