0

背景:

  • 我有 2 个 csv 文件:c.csv、p.csv
  • 每 15 秒,一组新记录被附加到 c.csv
  • 每 15 秒,一组新记录(但不同于 c.csv 集)被附加到 p.csv
  • c.csv 包含 SPY 的看涨期权数据(列 = contract_name、strike、volume、timestamp)
  • p.csv 包含 SPY 的看跌期权数据(列 = contract_name、strike、volume、timestamp)

图表.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
.
.
.

问题/我想要实现的目标:

当新记录被附加到两个 csv 文件时,如何让 fig1 实时更新?基本上我只想用 c.csv 和 p.csv 中的最新记录替换旧的 fig1。我希望 x 轴(罢工)是静态的而不是动态的,因为罢工总是相同的(304,303,302)。也希望保持 y 轴(vol)静态。有什么办法可以做到这一点?

4

1 回答 1

1

我认为您需要的是一个以间隔作为输入运行的回调。请参阅文档中的此页面

您将在布局中有这样的组件:

        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

于 2020-06-14T00:28:29.440 回答