-
Notifications
You must be signed in to change notification settings - Fork 0
/
dash_setup.py
149 lines (131 loc) · 5.16 KB
/
dash_setup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import plotly.graph_objs as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from datetime import datetime
import pandas as pd
import psycopg2
import textwrap
import json
from textwrap import dedent as d
from scipy import signal
app = dash.Dash()
conn = psycopg2.connect(user="faunam",
password="stupidpassword97!",
host="tone-db.ccg3nx1k7it5.us-west-2.rds.amazonaws.com",
port=5432,
database="postgres")
# https://help.plot.ly/database-connectors/query-from-plotly/
app.layout = html.Div(children=[
html.Div(children='''
We are graphing
'''),
dcc.Dropdown(
id='entity-dropdown',
options=[ # automate this maybe?
{'label': 'Donald Trump', 'value': 'donald trump'},
{'label': 'Jeff Bezos', 'value': 'jeff bezos'},
{'label': 'Facebook', 'value': 'facebook'},
{'label': 'Bernie Sanders', 'value': 'bernie sanders'},
{'label': 'Amazon', 'value': 'amazon'}
],
value='donald trump'
),
html.Div(id='graph-options', children=[
dcc.Checklist(id="media-legend",
options=[
{'label': 'News', 'value': 'news'},
{'label': 'Twitter', 'value': 'twitter'},
],
value=['twitter']
),
dcc.DatePickerRange(id="date-range",
month_format='MM/DD/YY', # ?? check datepicker plotly page if issues
end_date_placeholder_text='MM/DD/YY',
start_date=datetime(2015, 2, 19).strftime(
"%m-%d-%Y"),
end_date=datetime(2020, 2, 20).strftime(
"%m-%d-%Y")
)
]),
html.Div(id="graph", children=[
dcc.Graph(
id='ex-graph',
figure={
'data': [],
'layout': {
'title': "hehe",
'clickmode': 'event+select'
}
}
)
]),
html.Div([
dcc.Markdown(d("""
**Instance info** - Mouse over values in the graph.
""")),
html.Pre(id='hover-data')
])
])
# pd.read_sql_query() - use to transform sql into dataframe
# sql = "select count(*) from table;"
# dat = pd.read_sql_query(sql, conn)
# set conn = None at end
def wrap_helper(text, width):
return "\n".join(textwrap.wrap(text, width=width))
@app.callback(
Output('hover-data', 'children'),
[Input('ex-graph', 'hoverData')])
def display_hover_data(hoverData):
if hoverData is None:
return "None"
return wrap_helper(hoverData["points"][0]['text'], 100)
@app.callback(
Output(component_id='graph', component_property='children'),
[Input(component_id='entity-dropdown', component_property='value'),
Input(component_id='media-legend', component_property='value'),
Input(component_id='date-range', component_property='start_date'),
Input(component_id='date-range', component_property='end_date')])
def update_value(entity, media_types, start_date, end_date):
data = []
for media in media_types:
print(media)
# sql_str = "select tone, date, text from full_sample where entity='{}' and media='{}'".format(entity, media)
sql_str = "select tone, date, text from full_sample where entity='{}' and media='{}' and date between '{}' and '{}'".format(
entity, media, start_date, end_date)
media_df = pd.read_sql_query(sql_str, conn)
media_df["tone"] = pd.to_numeric(media_df["tone"])
media_df = media_df.groupby(["date"]).agg(
{"tone": "mean", "text": "first", "date": "first"})
# tone_avg = media_df["tone"].mean()
# tone_sd = media_df["tone"].std()
# # standardize values
# media_df["tone"] = (media_df["tone"] - tone_avg)//tone_sd
fig = go.Figure(data=[go.Scatter(x=media_df.date, y=media_df.tone)])
window_length = media_df.tone.size if media_df.tone.size % 2 == 1 else media_df.tone.size - 1
data.append({
"x": media_df.date,
"y": signal.savgol_filter(media_df.tone, window_length, 7) if media_df.tone.size > 3 else media_df.tone,
"text": media_df.text,
"type": "line",
"name": media,
"mode": 'lines', # lines+markers
'marker': {'size': 5}
# "hovertemplate": wrap_helper('<b>{}</b><br>%{text}'.format(
# media), 30),
})
title_string = "Sentiment towards " + \
" ".join([word.capitalize() for word in entity.split(" ")])
return dcc.Graph(
id='ex-graph',
figure={
'data': data,
'layout': {
'title': title_string,
'clickmode': 'event+select'
}
}
)
if __name__ == '__main__':
app.run_server(debug=True, host="0.0.0.0", port=8080)