Код ниже содержит две функции, которые очищают «данные контракта» и «цены» с веб-сайта. Внутри функций данные очищаются, и значение передается в функцию update (), которая извлекает данные каждые десять секунд. Когда я просто запускаю серверную печать Bokeh (source.data), функция печатает первые десять обновленных значений через равные промежутки времени. Однако, когда я хочу отобразить данные на диаграмме vbar, выдается ошибка субъекта.
Код
from urllib.request import urlopen
import requests
from bs4 import BeautifulSoup
from bokeh.models import Range1d, LinearAxis, DataRange1d
import time
from datetime import datetime
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource, DatetimeTickFormatter, ColorBar, LabelSet
from bokeh.plotting import figure, show
from math import radians
import pandas as pd
from pymongo import MongoClient
from bokeh.models import HoverTool
from bokeh.models import SingleIntervalTicker, LinearAxis
from bokeh.layouts import gridplot, row
from bokeh.models.widgets import TextInput
from flask import Flask, render_template, request
from bokeh.resources import CDN
from bs4 import BeautifulSoup
import pandas as pd
import requests
import numpy as np
from math import pi
from bokeh.models import NumeralTickFormatter
from bokeh.models.glyphs import Line as Line_glyph
p = figure()
def extract_contract():
Contracts =[]
res = requests.get('https://shared.websol.barchart.com/quotes/quote.php?
page=quote&sym=ng&x=13&y=8&domain=if&display_ice=1&enabled_ice_exchanges=&tz=0&ed=0')
soup = BeautifulSoup(res.text, 'html.parser')
soup.prettify()
data_rows = soup.findAll('tr')[2:]
for td in data_rows:
Contract = td.findAll('td')[0].text
Contracts.append(Contract)
df2 = pd.DataFrame({'Contracts' : Contracts})
month_mapper = {
'Cash':'Current',
'Jan': 'January',
'Feb': 'February',
'Mar': 'March',
'Apr': 'April',
'May': 'May',
'Jun': 'June',
'Jul': 'July',
'Aug': 'August',
'Sep': 'September',
'Oct': 'October',
'Nov': 'November',
'Dec': 'December',
}
def clean_month_string(s):
s = s.replace('\\', '')
month, year, code = s.split(' ')
month = month_mapper[month]
year = year.replace("'", "")
return ' '.join([month, year])
df2 = df2.drop(0).reset_index(drop=True)
df2['Contracts'] = df2['Contracts'].astype(str)
df2['Contracts'] = df2['Contracts'].apply(clean_month_string)
return df2.iloc[:10]
def extract_price():
Prices =[]
res = requests.get('https://shared.websol.barchart.com/quotes/quote.php?
page=quote&sym=ng&x=13&y=8&domain=if&display_ice=1&enabled_ice_exchanges=&tz=0&ed=0')
soup = BeautifulSoup(res.text, 'html.parser')
soup.prettify()
data_rows = soup.findAll('tr')[2:]
for td in data_rows:
Price = td.findAll('td')[1].text
Prices.append(Price)
df3 = pd.DataFrame(Prices)
df3.replace('s','',regex=True,inplace=True)
df3 = df3.astype(float)
return df3.iloc[:10]
source = ColumnDataSource(dict(x=[],y=[]))
def update():
new_data = dict(x= [extract_contract()], y = [extract_price()])
source.stream(new_data,rollover=200000000)
print(source.data)
p = figure(x_range= 'x', plot_height=1000, title="Monthly Natural Gas
Cost impact based on realtime futures contract",
toolbar_location=None, plot_width=1600)
p.vbar(x='x', top='y', width=0.2)
p.yaxis.formatter=NumeralTickFormatter(format="$00")
curdoc().add_root(p)
curdoc().add_periodic_callback(update,1000)
Вывод extract_contract ()
Contracts
0 March 20
1 April 20
2 May 20
3 June 20
4 July 20
5 August 20
6 September 20
7 October 20
8 November 20
9 December 20
Вывод extract_price ()
0 1.871
1 1.867
2 1.894
3 1.943
4 2.001
5 2.068
6 2.099
7 2.098
8 2.133
9 2.238