<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dayal Chand Aichara on Medium]]></title>
        <description><![CDATA[Stories by Dayal Chand Aichara on Medium]]></description>
        <link>https://medium.com/@dcaichara?source=rss-c6c6dcd9f4ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*9UuZvIa3NCacpsZ01Dph8A.jpeg</url>
            <title>Stories by Dayal Chand Aichara on Medium</title>
            <link>https://medium.com/@dcaichara?source=rss-c6c6dcd9f4ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:11:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dcaichara/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Dashboard App using Plotly’s Dash: Favicon, Google analytics, Custom CSS]]></title>
            <link>https://medium.com/game-of-data/building-a-dashboard-app-using-plotlys-dash-favicon-google-analytics-custom-css-75f7a1e95a88?source=rss-c6c6dcd9f4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/75f7a1e95a88</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[google-analytics]]></category>
            <dc:creator><![CDATA[Dayal Chand Aichara]]></dc:creator>
            <pubDate>Sun, 15 Nov 2020 12:02:50 GMT</pubDate>
            <atom:updated>2020-11-15T12:11:21.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ve__8lMBlyo7aJhG3KPN9w.jpeg" /><figcaption>A beautiful view of mountains and beaches from <a href="http://www.mt-nokogiri.co.jp/pc/p130000.php">Mount Nokogiri </a>(Chiba, Japan).</figcaption></figure><p>Part 3: How to add App favicon, App title, App description, Google Analytics, and custom CSS file to Dash App?</p><p>In last two articles we have learned how to build a dashboard with Dash. In this article, I will explain how to customized your dashboard and add Google Analytics tracking to it.</p><blockquote>If you haven’t read <a href="https://medium.com/analytics-vidhya/building-a-dashboard-app-using-plotlys-dash-a-complete-guide-from-beginner-to-pro-61e890bdc423">part 1</a> and <a href="https://medium.com/analytics-vidhya/building-a-dashboard-app-using-plotlys-dash-a-complete-guide-from-beginner-to-pro-e7657a4eb707">part 2</a>, please read them.</blockquote><ul><li><a href="https://medium.com/analytics-vidhya/building-a-dashboard-app-using-plotlys-dash-a-complete-guide-from-beginner-to-pro-61e890bdc423">Building a Dashboard App using Plotly’s Dash: A Complete Guide from Beginner to Pro</a></li><li><a href="https://medium.com/analytics-vidhya/building-a-dashboard-app-using-plotlys-dash-a-complete-guide-from-beginner-to-pro-e7657a4eb707">Building a Dashboard App using Plotly’s Dash: A Complete Guide from Beginner to Pro</a></li></ul><h4><strong>1. App title, App description, and App favicon:</strong></h4><p>Write app title and description as follow in app.py .</p><pre>app.title = &quot;Your App Title&quot;<br>app.description = &quot;Your App&#39;s Description&quot;</pre><p>To add your own favicon, create a new folder named assets . Save favicon image as favicon.ico and put it in assets folder. Dash will automatically detect and load your favicon from assets folder. Check <a href="https://github.com/dc-aichara/DS-ML-Public/commit/f1c82a930730337131763699c6754d42225c1303"><strong>this</strong></a><strong> </strong>commit for the code reference.</p><h4>2. Adding Google Analytics tracking code</h4><ol><li>Create an account on <a href="https://analytics.google.com/analytics/web">Google analytics</a> if you don’t have one, and create a property for your app.</li><li>Click on Admin then select account and property you have created. Click on Data Streams .</li><li>Click on Add stream then select web .</li><li>Click on Global Site Tag (gtag.js) &amp; copy code.</li><li>Add following code to app.py, and replace line 4–12 with code you copied in step 4. Also replace your app links in following code.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d6e2dfc27928fad946ed7a9c7b564a7/href">https://medium.com/media/0d6e2dfc27928fad946ed7a9c7b564a7/href</a></iframe><p>Example code is available on <a href="https://github.com/dc-aichara/DS-ML-Public/blob/f5c688bef51faff3aa94a12d4a1a373248be83ac/Medium_Files/dashboard_demo/app.py"><strong>GitHub</strong></a>.</p><h4>3. Add custom CSS file</h4><p>A custom CSS file can be very helpful to improve App’s appearance. It is a just three step process to add custom CSS file to your Dash App.</p><ol><li>Create a new directory static/css.</li><li>Add custom CSS file to static/css .</li><li>Add new CSS file to app.py as follow.</li></ol><pre>external_stylesheets = [<br>    &quot;static/css/my_style.css&quot;, # custom CSS file<br>    &quot;https://codepen.io/chriddyp/pen/bWLwgP.css&quot;,<br>]</pre><p>Check <a href="https://github.com/dc-aichara/DS-ML-Public/commit/4813dcf29d2b682b898dda9b40cbbf0b6f986360"><strong>this</strong></a> commit on GitHub for your reference.</p><p>App’s appearance looks better after adding custom CSS file. Feel free to play with CSS file and App’s code.</p><p>You can see, how does above changes improve overall App, if you visit App on Heroku web or ran code on your machine.</p><p><a href="https://crypto-indicators-dashboard.herokuapp.com/">Cryptocurrency Indicators Dashboard</a></p><p>Complete code is available on <a href="https://github.com/dc-aichara/DS-ML-Public/tree/master/Medium_Files/dashboard_demo">GitHub</a>. I hope, this helps you. This is the end of plotly’s Dash App tutorial series.</p><p>Thank you for reading!!🙇‍♂️</p><p>I am always available to answer your queries, please reach out to me on <a href="https://www.linkedin.com/in/dcaichara/"><strong>LinkedIn</strong></a> or <a href="https://twitter.com/dc_aichara"><strong>Twitter</strong>.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75f7a1e95a88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-of-data/building-a-dashboard-app-using-plotlys-dash-favicon-google-analytics-custom-css-75f7a1e95a88">Building a Dashboard App using Plotly’s Dash: Favicon, Google analytics, Custom CSS</a> was originally published in <a href="https://medium.com/game-of-data">Game of Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Dashboard App using Plotly’s Dash: A Complete Guide from Beginner to Pro]]></title>
            <link>https://medium.com/analytics-vidhya/building-a-dashboard-app-using-plotlys-dash-a-complete-guide-from-beginner-to-pro-e7657a4eb707?source=rss-c6c6dcd9f4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7657a4eb707</guid>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Dayal Chand Aichara]]></dc:creator>
            <pubDate>Tue, 26 Nov 2019 12:19:26 GMT</pubDate>
            <atom:updated>2020-11-15T12:19:53.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ledt51iFkfFkEORy1-9Ubw.jpeg" /><figcaption>View of<a href="https://en.wikipedia.org/wiki/Mount_Fuji"><strong> Mt. Fuji</strong></a><strong> </strong>(3776 m) from Mt. <a href="https://en.wikipedia.org/wiki/Mount_Kumotori"><strong>Kumotori</strong></a><strong> </strong>(2017 m).</figcaption></figure><h4>Complete guide to build an interactive dashboard App with Dash and deploy it to Heroku, Part 2: callbacks, authentication and Heroku deployment</h4><p>In part 1, we learnt how to start with Dash, add dash components, improve graph layout, and define callbacks. In part-2, we will learn <strong>how to add multiple tabs, share data between callbacks, write multi outputs callback, do user authentication, and deploy app to Heroku.</strong></p><p>I will start from where we left in part-1. If you missed part-1, please read it.</p><p><a href="https://medium.com/analytics-vidhya/building-a-dashboard-app-using-plotlys-dash-complete-guide-beginner-to-pro-part-1-61e890bdc423">Building a Dashboard App using Plotly&#39;s Dash -Complete Guide Beginner to Pro Part-1</a></p><h3>Dashboard App</h3><h4>7. <strong>Tabs and data sharing between callbacks</strong></h4><p>Assume we want to make charts of different price technical indicators for given cryptocurrency. For this, we will add tabs to our app layout and modify app.callback for graph so it returns chart for selected tab.</p><p>we have extracted data for table and graph separately till now. But we should only extract price data once for all the callbacks to save time and computation. So we need to share data between callbacks. To make data sharing easy, we will write an another app.callback which will take input from Dropdown and give a json data file as output. Output of this callback will be shared with other callbacks.</p><p>7.1 <strong>Tabs</strong></p><p>I will add tabs above the graph in app.layout .</p><pre>tabs_styles = {<br>    &#39;height&#39;: &#39;51px&#39;<br>}<br>tab_style = {<br>    &#39;borderBottom&#39;: &#39;1px solid #d6d6d6&#39;,<br>    &#39;padding&#39;: &#39;2px&#39;,<br>    &#39;fontWeight&#39;: &#39;bold&#39;<br>}<br><br>tab_selected_style = {<br>    &#39;borderTop&#39;: &#39;1px solid #d6d6d6&#39;,<br>    &#39;borderBottom&#39;: &#39;1px solid #d6d6d6&#39;,<br>    &#39;backgroundColor&#39;: &#39;black&#39;,<br>    &#39;color&#39;: &#39;yellow&#39;,<br>    &#39;padding&#39;: &#39;10px&#39;<br>}<br>dcc.Tabs(id=&quot;all-tabs-inline&quot;, value=&#39;tab-1&#39;, children=[<br>            dcc.Tab(label=&#39;Simple Moving Average&#39;, value=&#39;tab-1&#39;, style=tab_style, selected_style=tab_selected_style),<br>            dcc.Tab(label=&#39;Volatility Index&#39;, value=&#39;tab-2&#39;, style=tab_style, selected_style=tab_selected_style),<br>            dcc.Tab(label=&#39;Relative Strength Index&#39;, value=&#39;tab-3&#39;, style=tab_style, selected_style=tab_selected_style),<br>            dcc.Tab(label=&#39;Moving Average Divergence Convergence&#39;, value=&#39;tab-4&#39;, style=tab_style, selected_style=tab_selected_style),<br>            dcc.Tab(label=&#39;Exponential Moving Average&#39;, value=&#39;tab-5&#39;, style=tab_style, selected_style=tab_selected_style),<br>            dcc.Tab(label=&#39;Bollinger Bands&#39;, value=&#39;tab-6&#39;, style=tab_style,<br>                    selected_style=tab_selected_style),<br>        ], style=tabs_styles,<br>            colors={<br>            &quot;border&quot;: &quot;yellow&quot;,<br>            &quot;primary&quot;: &quot;red&quot;,<br>            &quot;background&quot;: &quot;orange&quot;<br>            }),</pre><p>I have added 6 taps for 6 indicators. In above code, tab_style , tab_selected_style , and tabs_styles are predefined styles for general tab appearance, tab appearance after selection, and tab line appearance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W89qKwD2dWxka6B-yXnwFg.png" /><figcaption>Tabs</figcaption></figure><p><strong>7.2 Data</strong></p><p>We need data to create charts and data table. We will use <a href="https://github.com/dc-aichara/PriceIndices"><strong>PriceIndices</strong></a> python package to get price data and calculate technical indicators. Let’s write a script ( data.py) to get data in dashboard_demo directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7590ff37d8da4829a46be893b7f87740/href">https://medium.com/media/7590ff37d8da4829a46be893b7f87740/href</a></iframe><p>data.py will give us a pandas DataFrame which have all data required for charts.</p><p><strong>7.3 Callbacks and data sharing</strong></p><p>We add a new callback to get data.</p><ul><li>Data callback</li></ul><pre># import get_coin_data function from data.py<br>from data import get_coin_data </pre><pre>@app.callback(Output(&#39;intermediate-value&#39;, &#39;children&#39;),<br>              [Input(&#39;dropdown&#39;, &#39;value&#39;)])<br>def get_data(option): # option from drop down <br>    df = get_coin_data(crypto=option, save_data=True)<br>    return df.to_json(date_format=&#39;iso&#39;, orient=&#39;split&#39;)</pre><p>Now modify data table callback and graph callback.</p><ul><li>DataTable callback</li></ul><pre>@app.callback(Output(&#39;table-output&#39;, &#39;children&#39;), <br>              [Input(&#39;intermediate-value&#39;, &#39;children&#39;)])<br>def get_data_table(data):<br>    df = pd.read_json(data, orient=&#39;split&#39;)<br>    df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;])<br>    data_table = dash_table.DataTable(<br>        id=&#39;datatable-data&#39;,<br>        data=df.to_dict(&#39;records&#39;),<br>        columns=[{&#39;id&#39;: c, &#39;name&#39;: c} for c in df.columns],<br>        style_table={&#39;overflowY&#39;: &#39;scroll&#39;},<br>        fixed_rows={&#39;headers&#39;: True, &#39;data&#39;: 10},<br>        style_cell={&#39;width&#39;: &#39;100px&#39;},<br>        style_header={<br>            &#39;backgroundColor&#39;: &#39;rgb(230, 230, 230)&#39;,<br>            &#39;fontWeight&#39;: &#39;bold&#39;<br>        }<br>    )<br>    return data_table</pre><ul><li>Graph callback</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/555b61a293ada10533f937e76f1f93b6/href">https://medium.com/media/555b61a293ada10533f937e76f1f93b6/href</a></iframe><p><strong>DataTable and Graph callbacks sharing data from Data callback. Output of Data callback is used as input to DataTable and Graph callbacks.</strong> Graph callback function make a graph based on tab selection. Some graphs have two y-axis for better graph appearance. yaxis2 define style of second y-axis. I have explained app work flow in flowchart below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jh1hgm5zd0sqHyOUiJ7Zig.png" /><figcaption>Flowchart-2</figcaption></figure><p>Refresh the app page to see changes we made. Also try different coin, date range, and tab to see how do they alter the results.</p><h4>8. Multi outputs callback</h4><p>We have 3 callbacks till now. How about making a single app.callback of DataTable and Graph callbacks which gives multiple outputs? Sounds cool? Let’s do it.</p><p>We will combine Graph, and DataTable callbacks which will gives two outputs: Graph and DataTable. We can also combine Data callback with other two but if we do that, data will be a requested for each tab or date range or coin selection. We should only make data request once for coin selection and only for coin input change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7528ebedfb20e68cb831a03c54d7a023/href">https://medium.com/media/7528ebedfb20e68cb831a03c54d7a023/href</a></iframe><blockquote>Note: If we put outputs in a list in “app.callback&quot; , callback function must return a list of outputs.</blockquote><p>Flowchart-3 explains input and output flow after combining two callbacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4q1pIxT39dVkReoSabpV5w.png" /><figcaption>Flowchart-3</figcaption></figure><h4><strong>9. User Authentication</strong></h4><p>Dash provide user authentication through a separate python package dash-auth . dash-auth offers two methods of authentications: <strong>HTTP Basic Auth</strong> and <strong>Plotly OAuth</strong>.</p><p><strong>9.1 HTTP Basic Auth</strong></p><p>HTTP Basic Auth is one of the simplest forms of authentication on the web but it has few limitations.</p><ul><li>Users can not log out of applications</li><li>You are responsible for sending the usernames and passwords to your viewers over a secure channel</li><li>Your viewers can not create their own account and cannot change their password</li><li>You are responsible for safely storing the username and password pairs in your code.</li></ul><p>We need to add user and password in source code for HTTP Basic Auth. I will add HTTP Basic Auth code to “app.py”. It is advised to save user and password details in a separate file.</p><pre>import dash<br>import dash_auth<br>external_stylesheets = [&#39;https://codepen.io/chriddyp/pen/bWLwgP.css&#39;]<br>app = dash.Dash(__name__, external_stylesheets=external_stylesheets)<br>server = app.server<br>app.config.suppress_callback_exceptions = True<br><br>VALID_USERNAME_PASSWORD_PAIRS = {<br>    &#39;dash_demo&#39;: &#39;dash@demo&#39;<br>}<br><br>auth = dash_auth.BasicAuth(<br>    app,<br>    VALID_USERNAME_PASSWORD_PAIRS<br>)</pre><p>When we rerun or refresh app page, there will be an authentication pop-up.We need to authenticate app only once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*YKhRVewcB3k9ReyOl69i-w.png" /><figcaption>Authentication pop-up</figcaption></figure><p><strong>9.2 Plotly OAuth</strong></p><p>A paid Plotly subscription account is required for Plotly Auth. Plotly 0Auth provides authentication through a registered online Plotly account or through a company’s <a href="https://plot.ly/products/on-premise">Plotly Enterprise server</a>.</p><p>See Plotly OAuth example here.</p><p><a href="https://dash.plot.ly/authentication">Authentication</a></p><p><strong>10. Login and Logout Buttons</strong></p><p>In this section, I will demonstrate how to use Login and Logout Buttons for authentication. We can protect outputs of callbacks through user authentication.</p><blockquote>Remove HTTP Basic Auth from “app.py” before proceeding.</blockquote><p>Follow the steps written below to achieve authentication with Login and Logout buttons.</p><p><strong>I. Create a “user.py” in</strong><strong>dashboard_demo directory which contains users and passwords.</strong></p><pre>user_pwd = {&#39;dash&#39;: &#39;dash@123&#39;,<br>            &#39;dash1&#39;: &#39;dash1@123&#39;,<br>            }<br>user_names = {&#39;dash&#39;: &#39;User1, welcome to the crypto indicators dashboard&#39;,<br>              &#39;dash1&#39;: &#39;User1, welcome to the crypto indicators dashboard&#39;,<br>              }<br><br>def users_info():<br>    return user_pwd, user_names</pre><p><strong>II. Write Login route</strong></p><p>Login route verify user and password combination and redirect to a url based on authentication results.</p><pre>import flask<br>from users import users_info<br>user_pwd, user_names = users_info()<br>_app_route = &#39;/&#39;</pre><pre># Create a login route<br>@app.server.route(&#39;/login&#39;, methods=[&#39;POST&#39;])<br>def route_login():<br>    data = flask.request.form<br>    username = data.get(&#39;username&#39;)<br>    password = data.get(&#39;password&#39;)<br><br>    if username not in user_pwd.keys() or  user_pwd[username] != password:<br>        return flask.redirect(&#39;/login&#39;)<br>    else:<br><br>        # Return a redirect with<br>        rep = flask.redirect(_app_route)<br><br>        # Here we just store the given username in a cookie.<br>        # Actual session cookies should be signed or use a JWT token.<br>        rep.set_cookie(&#39;custom-auth-session&#39;, username)<br>        return rep</pre><p><strong>III. Define a Login form</strong></p><pre># Simple dash component login form.<br>login_form = html.Div([<br>    html.Form([<br>        dcc.Input(placeholder=&#39;username&#39;, name=&#39;username&#39;, type=&#39;text&#39;),<br>        dcc.Input(placeholder=&#39;password&#39;, name=&#39;password&#39;, type=&#39;password&#39;),<br>        html.Button(&#39;Login&#39;, type=&#39;submit&#39;)<br>    ], action=&#39;/login&#39;, method=&#39;post&#39;)<br>])</pre><p><strong>IV. Add buttons to</strong> app.layout <strong>before DateRangePicker</strong></p><pre>html.Div(id=&#39;custom-auth-frame&#39;),<br>html.Div(id=&#39;custom-auth-frame-1&#39;,<br>           style={<br>                  &#39;textAlign&#39;: &#39;right&#39;,<br>                  &quot;background&quot;: &quot;black&quot;,<br>           }<br>           ),</pre><p><strong>V. Create a Logout route</strong></p><p>Logout route redirects to Login page when user click Logout button.</p><pre># create a logout route<br>@app.server.route(&#39;/logout&#39;, methods=[&#39;POST&#39;])<br>def route_logout():<br>    # Redirect back to the index and remove the session cookie.<br>    rep = flask.redirect(&#39;/login&#39;)<br>    rep.set_cookie(&#39;custom-auth-session&#39;, &#39;&#39;, expires=0)<br>    return rep</pre><p><strong>VI. Edit multi outputs callback</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99194e37300e438206858a1623d11315/href">https://medium.com/media/99194e37300e438206858a1623d11315/href</a></iframe><p>This updated callback will produce three outputs based on authentication results. Callback function will verify user and password combination, if authentication fails, it will redirect to login page, otherwise graph, and data table will be displayed. We will write <strong>LogoutButton</strong> inside the callback function.</p><p>Our app is password protected now. Let’s have a tour of what we build till now.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQC_sZTDW-YQ%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQC_sZTDW-YQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQC_sZTDW-YQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e1b0d2c6c2a4aea272d0d6801c095b3/href">https://medium.com/media/5e1b0d2c6c2a4aea272d0d6801c095b3/href</a></iframe><p>Everything looks fine.There is lot you can do with Dash as per your requirements. Read more use cases and tutorials <a href="https://dash.plot.ly/?_ga=2.104688649.828752419.1574214165-1322431847.1545115553"><strong>here</strong></a>.</p><h4>11. Deploying to Heroku</h4><blockquote><strong>Disclaimer:</strong> Procedure written below is tested on MacBook Pro. It should work fine on Linux but may not work on Windows. Please follow instruction for window here: <a href="https://devcenter.heroku.com/articles/heroku-cli">https://devcenter.heroku.com/articles/heroku-cli</a></blockquote><p>Follow the procedure written below to deploy Dash app to Heroku.</p><p>I. <a href="https://signup.heroku.com/login"><strong>Sign Up a free Heroku account</strong></a>.</p><p><strong>II.</strong> Install <strong>Heroku command Line Interface (CLI)</strong> with brew tap heroku/brew &amp;&amp; brew install heroku on mac or linux.</p><p><strong>III</strong>. Initiate a GitHub repository with git init command.</p><p><strong>IV.</strong> Write Procfile and .gitignore file in dashboard_demo directory as below.</p><p>Procfile</p><pre>web: gunicorn index:server</pre><p>.gitignore</p><pre>*.pyc<br>.DS_Store</pre><p>Your dashboard_demo directory should look like below.</p><pre>dashboard_demo<br>|--.gitignore<br>|--app.py<br>|--index.py<br>|--Procfile<br>|--requirements.txt<br>|--users.py</pre><p><strong>V. </strong>Login to Heroku through CLI with command<strong> </strong><strong>heroku login </strong>and run following commands to create and deploy an app.</p><pre>$ heroku create dash-app-name # change dash-app-name to a unique name<br>$ git add . # add all files to git<br>$ git commit -m &#39;Initial app commit&#39;<br>$ git push heroku master # deploy code to heroku<br>$ heroku ps:scale web=1  # run the app with a 1 heroku &quot;dyno&quot;</pre><p>Now, you be able to see your app at <a href="https://my-dash-app.herokuapp.com/">https://</a>dash-app-name<a href="https://my-dash-app.herokuapp.com/">.herokuapp.com</a>.</p><p>I have created an app on Heroku with name crypto-indicators-dashboard . This is the same app we have created in this tutorial (Part-1 and part-2).</p><p><a href="https://crypto-indicators-dashboard.herokuapp.com/">Cryptocurrency Indicators Dashboard</a></p><p>VI. If you make any change in code, do following to update app.</p><pre>$ git add . # add changes<br>$ git commit -m &#39;change description&#39;<br>$ git push heroku master # push to heroku</pre><p>You should be able to build and deploy app to Heroku now if you have followed all the steps. You may run into deployment error, therefore try to deploy simple app first. Also check recent app logs with heroku logs --tail command to check app/code error.</p><p>You can do a lot with Dash.You can have multiple charts on same page, have sub tabs, decorate data table for specific values, make a data table download button etc. For this tutorial, I just wanted to make a dashboard which shows price indicators chart for a given date range and cryptocurrency.</p><h4>Summary</h4><ul><li>First know and understand your requirements for dashboard.</li><li>Start app with simple layout and callbacks.</li><li>Add dash components and callbacks one by one.</li><li>Refresh app page on local host after addition or deletion to see changes.</li><li>Write separate codes for app, index, data, users etc to make it easy to debug and understand.</li><li>Experiment with different style and app layout for better appearance.</li><li>Share data between callbacks and use multiple outputs callbacks.</li><li>Test app on your local before deployment.</li><li>Deploy a simple app first and then scale.</li></ul><p>Let me know how your first experience with Dash. 😉</p><p>You can find this app on <a href="https://github.com/dc-aichara/DS-ML-Public/tree/master/Medium_Files/dashboard_demo"><strong>Github</strong></a>.</p><p>Thank you for reading! 😊</p><p>I am always available to answer your queries, please reach out to me on <a href="https://www.linkedin.com/in/dcaichara/"><strong>LinkedIn</strong></a> or <a href="https://twitter.com/dc_aichara"><strong>Twitter</strong>.</a></p><blockquote>If you want to add Google Analytics tracking, favicon, custom CSS file etc to your Dash App, read part 3.</blockquote><p><a href="https://medium.com/game-of-data/building-a-dashboard-app-using-plotlys-dash-favicon-google-analytics-custom-css-75f7a1e95a88">Building a Dashboard App using Plotly’s Dash: Favicon, Google analytics, Custom CSS</a></p><p>References/Resources:</p><ol><li><a href="https://dash.plot.ly/?_ga=2.113607566.828752419.1574214165-1322431847.1545115553">https://dash.plot.ly/?_ga=2.113607566.828752419.1574214165-1322431847.1545115553</a></li><li><a href="https://plot.ly/dash/">https://plot.ly/dash/</a></li><li><a href="https://towardsdatascience.com/how-to-build-a-complex-reporting-dashboard-using-dash-and-plotl-4f4257c18a7f">https://towardsdatascience.com/how-to-build-a-complex-reporting-dashboard-using-dash-and-plotl-4f4257c18a7f</a></li><li><a href="https://devcenter.heroku.com/articles/heroku-cli">https://devcenter.heroku.com/articles/heroku-cli</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7657a4eb707" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/building-a-dashboard-app-using-plotlys-dash-a-complete-guide-from-beginner-to-pro-e7657a4eb707">Building a Dashboard App using Plotly’s Dash: A Complete Guide from Beginner to Pro</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Dashboard App using Plotly’s Dash: A Complete Guide from Beginner to Pro]]></title>
            <link>https://medium.com/analytics-vidhya/building-a-dashboard-app-using-plotlys-dash-a-complete-guide-from-beginner-to-pro-61e890bdc423?source=rss-c6c6dcd9f4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/61e890bdc423</guid>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[dashboard]]></category>
            <dc:creator><![CDATA[Dayal Chand Aichara]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 12:13:24 GMT</pubDate>
            <atom:updated>2020-04-07T02:55:42.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8RM6DCyUumm63lJ_WMwD0w.jpeg" /><figcaption>View of<a href="https://en.wikipedia.org/wiki/Mount_Fuji"><strong> Mt. Fuji</strong></a><strong> </strong>(3776 m) from Mt. <a href="https://en.wikipedia.org/wiki/Mount_Kumotori"><strong>Kumotori</strong></a><strong> </strong>(2017 m).</figcaption></figure><h4>Complete guide to building an interactive dashboard App with Dash and deploy it to Heroku, Part 1: Creating a Basic dashboard</h4><p>Dashboards can make data visualization more interactive, communicative, simple, and user friendly. Assume a situation where you need to build an interactive dashboard but you are only comfortable with python. In this situation Dash comes to rescue you.</p><blockquote><strong>Dash</strong> is a Python framework for building analytical web applications. No JavaScript required. Built on top of <strong>Plotly</strong>.js, React and Flask, <strong>Dash</strong> ties modern UI elements like dropdowns, sliders, data tables, and graphs directly to your analytical Python code.</blockquote><p>I will cover whole tutorial in 2 parts. First part will cover creating a basic dashboard and then adding more options to it. In Second part, I will write more on dash components, user authentication, and deploying app to Heroku.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIg3UKZd8IGk&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIg3UKZd8IGk&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d85f895079912b9c22909e20bdbe7daa/href">https://medium.com/media/d85f895079912b9c22909e20bdbe7daa/href</a></iframe><p>We will build above dashboard in this article.</p><blockquote>See a real life dashboard example created with Dash to track <strong>Covid19 cases in India.</strong></blockquote><p><a href="https://covid19-india-tracker.herokuapp.com/">COVID19 India Tracker</a></p><h4><strong>Initial set-up</strong></h4><p>First create a new folder (Example: dashboard_demo) with mkdir dashboard_demo command and change working directory with cd dashboard_demo. I am assuming that you have already installed anaconda and it is working fine. Now create a conda virtual environment with conda create --name dashboard command and active it with source active dashboard or conda activate dashboard commands.</p><p>Install dependencies via pip and save them to “requirements.txt” file.</p><pre>pip install Flask<br>pip install dash<br>pip install plotly<br>pip install dash_html_components # dash html components<br>pip install dash_core_components # dash core components <br>pip install PriceIndices # will used for this tutorial for data <br>pip install lxml # Needed for PriceIndices package<br>pip install dash-table # data table components<br>pip install dash-auth # for user authentication<br>pip install gunicorn # needed for deployment </pre><p>Save above python packages to “requirements.txt” with pip freeze --&gt; requirements.txt command. “requirements.txt” look like below.</p><pre>dash==1.6.1<br>dash-core-components==1.5.1<br>dash-html-components==1.0.2<br>dash-auth==1.3.2<br>dash-table==4.5.1<br>Flask==1.0.2<br>gunicorn==19.9.0<br>numpy==1.15.4<br>pandas==0.23.4<br>plotly==4.2.1<br>PriceIndices==1.1.1<br>lxml==4.4.1</pre><h3>Dashboard App</h3><p>In this section, I will cover basic introduction of dash components and how to use them to make a dashboard.</p><h4><strong>1. Introduction</strong></h4><p>I will give a brief summary of dash components before we build a dashboard app. Dash html components and dash core components are used to build interactive dashboards.</p><p><strong>Dash html components</strong> works as html tags. It convert python code to html code. See example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f2770c1d9814ef54a59ad1b825a2e47/href">https://medium.com/media/1f2770c1d9814ef54a59ad1b825a2e47/href</a></iframe><p><strong>Dash core components </strong>have different components to build interactive dashboards.</p><blockquote>I. <a href="https://dash.plot.ly/dash-core-components/graph">Graphs</a>: It is used to make graphs.</blockquote><blockquote>II. Tabs: A component to make tabs</blockquote><blockquote>III. Dropdown: It creates a dropdown to select items.</blockquote><blockquote>IV. Sliders: It a value range slider.</blockquote><blockquote>V. DatePickers: Date pickers are used to select date or date range.</blockquote><blockquote>V. Table: This component is used to display tables.</blockquote><blockquote>VI. Markdown: It works as markdown.</blockquote><blockquote>VII. Checklist: It offers checklist options.</blockquote><blockquote>VIII. RadioItems: RadiosItems are used to make radio buttons.</blockquote><blockquote>IX. <a href="https://dash.plot.ly/dash-core-components/location">Location</a>: It represents the location bar in your web browser.</blockquote><blockquote>X. Store: It is used to store data in user’s browser.</blockquote><p>I recommend to read <a href="https://dash.plot.ly/?_ga=2.171682729.828752419.1574214165-1322431847.1545115553"><strong>official documentation</strong> </a>to get started with Dash.</p><p>We will see uses of few of above components in this tutorial.</p><h4><strong>2. First Simple App</strong></h4><p>Now create 2 files ( app.py and index.py )in dashboard_demo directory with touch command. touch app.py &amp; touch index.py</p><p>“app.py” will be same for the most of dashboard apps build using dash. In app file we create a dash app, server and define app’s overall style with a css file. external_stylesheets is a css file which is used to define app’s overall style.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e230aab154361302fe9f8f2a2345981c/href">https://medium.com/media/e230aab154361302fe9f8f2a2345981c/href</a></iframe><p>“index.py” will have app’s html and core components. There are two main parts of dash app which will be defined in index file, are app layout and callbacks. App layout describes what the application looks like and callbacks describe the interactivity of the application.</p><p>Let’s write a simple “index.py” which make a line graph.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f181cb1c08fd9bcfded7c9c38e259f58/href">https://medium.com/media/f181cb1c08fd9bcfded7c9c38e259f58/href</a></iframe><p>Run index.py with $ python3 index.py command. You should be able see dashboard app at <a href="http://127.0.0.1:8050/">http://127.0.0.1:8050/</a> . Dashboard will look like below picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mPzRjQpGFdrzdEeEBRHXg.png" /><figcaption>Dashboard App Example-1</figcaption></figure><h4><strong>3. Add callback and improve graph layout</strong></h4><p>Above dashboard looks very simple. Lets’s introduce callbacks and change graph layout.</p><p><strong>How does callbacks work?</strong></p><blockquote>The “inputs” and “outputs” of our application interface are described declaratively through the app.callback decorator which are simply the properties of a particular component. Whenever an input property changes, the function that the callback decorator wraps will get called automatically and output will change in app layout.</blockquote><p>We can define style, color, text format, graph background etc in graph layout. See code example below which has callback and updated graph layout.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/736d5ded321e3311d2c28e309ce7c5b4/href">https://medium.com/media/736d5ded321e3311d2c28e309ce7c5b4/href</a></iframe><p>If we compare “index.py example-1” and “index.py example-2”, We could see that there is an app.callback added and graph layout also got few now items in “index.py example-2”. Refresh the app page to see changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Beg20RAeQYhbNMF9IaOoOg.png" /><figcaption>Dashboard Example -2</figcaption></figure><blockquote>Note: We should use callbacks only when we want to change output/s based on certain input/s. In above example app.callback is not needed. I just used it to demonstrate its use.</blockquote><h4><strong>4. Add DateRangePicker and use real data for graph</strong></h4><p>In this part we will add a DateRangePicker to layout and also use real data for graph.</p><p>I will use Bitcoin price data to make a price vs time line chart for selected date range. Bitcoin price data available on <a href="https://coinmarketcap.com/"><strong>CoinMarketCap </strong></a>. I will use <a href="https://github.com/dc-aichara/PriceIndices"><strong>PriceIndices</strong></a> python library to get price data from CoinMarketCap.</p><p><strong>DateRangePicker’s components are explained below.</strong></p><blockquote><strong>min_date_allowed: </strong>Min date allowed to select</blockquote><blockquote><strong>max_date_allowed: </strong>Maximum date allowed to select</blockquote><blockquote><strong>initial_visible_month: </strong>Initial visible month when click to select date</blockquote><blockquote><strong>start_date: </strong>Start date of date range picker</blockquote><blockquote><strong>end_date :</strong> End date of date range picker</blockquote><blockquote><strong>number_of_months_shown:</strong> Number of months to be shown to select dates</blockquote><blockquote><strong>month_format:</strong> Format to display month and year</blockquote><blockquote><strong>display_format: </strong>Date display format</blockquote><p>I will also add DateRangePicker’s start date and end date to app.callback so graph can be displayed for selected date range.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e55a8a8974b9cf4c0f1773f4e6158cdd/href">https://medium.com/media/e55a8a8974b9cf4c0f1773f4e6158cdd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wseOIpTn-t3BIf2bZ1kCpQ.png" /><figcaption>Dashboard Example -3</figcaption></figure><p>Above app has a DateRangePicker. Graph is displayed between selected date range.</p><h4><strong>5. Add Data Table and Markdown</strong></h4><p>In this section, we will add a data table and markdown to app. First write a function to get data table. Data table can be created using dash-table library. dash-table renders a html table.</p><pre>df = history.get_price(&#39;bitcoin&#39;, &#39;20130428&#39;, &#39;20200510&#39;)<br>def get_data_table():<br>    data_table = dash_table.DataTable(<br>        id=&#39;datatable-data&#39;,<br>        data=df.to_dict(&#39;records&#39;),<br>        columns=[{&#39;id&#39;: c, &#39;name&#39;: c} for c in df.columns],<br>        style_table={&#39;overflowY&#39;: &#39;scroll&#39;},<br>        fixed_rows={&#39;headers&#39;: True, &#39;data&#39;: 10},<br>        style_cell={&#39;width&#39;: &#39;100px&#39;},<br>        style_header={<br>            &#39;backgroundColor&#39;: &#39;rgb(230, 230, 230)&#39;,<br>            &#39;fontWeight&#39;: &#39;bold&#39;<br>        }<br>    )<br>    return data_table</pre><p>Now add 2 html components to app.layout for data table and markdown. Dash markdown works same as any other markdown. I have used markdown to right copyrights at bottom of the app page.</p><pre>html.Div(children=[html.H1(children=&quot;Data Table&quot;, # html for table<br>                   style={<br>                          &#39;textAlign&#39;: &#39;center&#39;,<br>                           &quot;background&quot;: &quot;yellow&quot;}),<br>                      get_data_table()]),<br>html.Div(children=[dcc.Markdown( # markdown<br>    &quot; © 2019 [DCAICHARA](https://github.com/dc-aichara)  All Rights Reserved.&quot;)], style={<br>                 &#39;textAlign&#39;: &#39;center&#39;,<br>                 &quot;background&quot;: &quot;yellow&quot;})</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c839e0846a3dd8d23ab39acaefe7f926/href">https://medium.com/media/c839e0846a3dd8d23ab39acaefe7f926/href</a></iframe><p>Let’s see changes in app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjTZnDv0KQQr8wn4xgjIbA.png" /><figcaption>Dashboard Example -4</figcaption></figure><h4>6. <strong>Add Dropdown</strong></h4><p>Dropdown is used to select one or more items from given options. We have used only bitcoin price data to plot graph till now. Let’s create a dropdown which has option to select different cryptocurrencies.</p><p>I will add Dropdown next to DateRangePicker. Here we need to add a new app.callback for data table which will take input from Dropdown and extract data for given input coin. We will also add Dropdown input to graph callback to plot graph for selected coin. Flowchart below explains how do callbacks work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwNszE5e3MLK5izCPXZCbQ.png" /><figcaption>Flowchart-1</figcaption></figure><p>See changes in &quot;index.py” after adding Dropdown and updating callbacks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcccf8411c510f08b50dac16109e6dc7/href">https://medium.com/media/dcccf8411c510f08b50dac16109e6dc7/href</a></iframe><p>Our Dash app now have a DateRangePicker to select date range, Dropdown to select cryptocurrency, Graph, and Data Table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hj56ZnotAxE4Dkzc2EVBYw.png" /><figcaption>Dashboard Example -5</figcaption></figure><p>This is the end of first part. I will cover <strong>Tabs, data sharing between callbacks, multi outputs callback</strong>, <strong>user authentication, Login &amp; Logout Button, and deploying app to Heroku </strong>in part 2.</p><p><a href="https://medium.com/analytics-vidhya/building-a-dashboard-app-using-plotlys-dash-a-complete-guide-from-beginner-to-pro-e7657a4eb707">Building a Dashboard App using Plotly’s Dash: A Complete Guide from Beginner to Pro</a></p><ul><li>See beautiful collection of Dash resources on <a href="https://github.com/ucg8j/awesome-dash"><strong>awesome-dash</strong></a> page.</li></ul><p>Thank you for reading! If you have any query, please reach out to me on <a href="https://www.linkedin.com/in/dcaichara/"><strong>LinkedIn</strong></a> or <a href="https://twitter.com/dc_aichara"><strong>Twitter</strong>.</a></p><p><strong>Reference:</strong></p><ol><li><a href="https://dash.plot.ly/?_ga=2.113607566.828752419.1574214165-1322431847.1545115553">https://dash.plot.ly/?_ga=2.113607566.828752419.1574214165-1322431847.1545115553</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61e890bdc423" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/building-a-dashboard-app-using-plotlys-dash-a-complete-guide-from-beginner-to-pro-61e890bdc423">Building a Dashboard App using Plotly’s Dash: A Complete Guide from Beginner to Pro</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get Google Analytics Report Data as Pandas DataFrame?]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-get-google-analytics-report-data-as-pandas-dataframe-e3930831fba?source=rss-c6c6dcd9f4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3930831fba</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-api]]></category>
            <category><![CDATA[google-analytics]]></category>
            <dc:creator><![CDATA[Dayal Chand Aichara]]></dc:creator>
            <pubDate>Thu, 14 Nov 2019 08:19:38 GMT</pubDate>
            <atom:updated>2019-11-20T03:57:20.526Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qiLMpHZZ9DHPMceajckxgg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kmuza?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Carlos Muza</a> on <a href="https://unsplash.com/s/photos/web-analytics?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Getting Google Analytics report data with python through Google Analytics Reporting API V4</h4><p>Google Analytics tracks and reports website traffic which helps to understand customers as well as website’s performance.</p><p>Google Analytics report data can be fetched through Google Analytics Reporting API V4 using python with few lines of code. I will explain whole process in 4 steps.</p><h4><strong>1. Set up the project in Google Developer Console and get client token and secret</strong></h4><p>In order to access Google APIs, user need a project on <a href="https://console.cloud.google.com/"><strong>Google Cloud Platform</strong></a><strong> </strong>and a <strong>service account.</strong> Follow the steps written below to set up project and service account in Google Developer Console.</p><blockquote><strong>I.</strong> Create a project here <a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a></blockquote><blockquote><strong>II.</strong> Create a service account and save credentials (.json file). Read more about service account<a href="http://gle.com/iam/docs/creating-managing-service-accounts"> <strong>here</strong></a>.</blockquote><blockquote><strong>III.</strong> Enable Google Analytics Reporting API here <a href="https://console.developers.google.com/apis/dashboard">https://console.developers.google.com/apis/dashboard</a>?</blockquote><p>If you face any issue with this step , watch Google Cloud Platform’s video guide on their <a href="https://www.youtube.com/watch?v=tSnzoW4RlaQ"><strong>YouTube Channel</strong></a>.</p><blockquote>Note: This is one time setup.</blockquote><h4><strong>2. Authentication</strong></h4><p>Once you have clients secrets (credentials file), you can access Google Analytics Reporting API by authentication using OAuth 2.0. We will use oauth2clientand httplib2 python libraries for authentication.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91c6e20632fac3a1a9f8b513910f85f1/href">https://medium.com/media/91c6e20632fac3a1a9f8b513910f85f1/href</a></iframe><pre>ga_auth = authenticate_ga_api() </pre><p>Note: When you run authenticate_ga_api() for the first time , it will redirect to authentication link in default browser. Choose/enter gmail id registered with Google project and click on allow button. This will create and save authentication credential file “ <strong>analyticsreporting.dat</strong>” for Google Analytics Reporting API. See sample authentication credentials file below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f8a30c60ac4f0abfe7d13f7b110174b/href">https://medium.com/media/2f8a30c60ac4f0abfe7d13f7b110174b/href</a></iframe><blockquote>Note: The authentication access token expires in 1 hour, we have to rerun authenticat_ga_api function to refresh access_token .</blockquote><h4><strong>3. Request submission</strong></h4><p>In this step we define requests and execute them using <a href="https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet">reports.batchget</a><br> method<strong> </strong>in the Google API Client.</p><p>Request must be a dictionary object. A request usually includes viewId , dateRanges , dimensions , and metrics .</p><blockquote><strong>View Id :</strong> View id can be found in Google Analytics under view tab.</blockquote><blockquote><strong>Date Ranges:</strong> start date and end date in YYYY-MM-DD format.</blockquote><blockquote><strong>Dimensions:</strong> Variables which are used to group metrics (secondary variables). example: user type, data type : string</blockquote><blockquote><strong>Metrics : </strong>Secondary variables, example: users, datatype: numeric</blockquote><blockquote>Explore all dimensions and metrics combinations at <a href="https://ga-dev-tools.appspot.com/dimensions-metrics-explorer/">https://ga-dev-tools.appspot.com/dimensions-metrics-explorer/</a> .</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11cd561f35506d631320722ad143ad8f/href">https://medium.com/media/11cd561f35506d631320722ad143ad8f/href</a></iframe><p>Execute requests to get data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b24dd8239575fea9a2cf2b9b900c43b/href">https://medium.com/media/0b24dd8239575fea9a2cf2b9b900c43b/href</a></iframe><p>I will provide code for few samples in this step and their processing in step 4.</p><p><strong>Sample 1: Dimensions and Metrics</strong></p><p>Let’s get page views, unique page views , and average time on page for different pages for a month.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e418f3c5dd491a4f15a9ffbeed1b27a/href">https://medium.com/media/9e418f3c5dd491a4f15a9ffbeed1b27a/href</a></iframe><blockquote>Note: It is also possible to create a custom calculated metric, by combining existing metrics into a new metrics expression.</blockquote><pre># Create the Metrics object.<br>metric_expression = {<br>  &#39;expression&#39;: &#39;ga:users/ga:pageviews&#39;,<br>  &#39;formattingType&#39;: &#39;FLOAT&#39;,<br>  &#39;alias&#39;: &#39;Metric Expression&#39;<br>}</pre><p><strong>Sample 2: Multiple Date Ranges</strong></p><p>We will get page views, unique page views , and average time on page for two date ranges.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08e262bdde141b8ba612ac104d8bd9be/href">https://medium.com/media/08e262bdde141b8ba612ac104d8bd9be/href</a></iframe><p><strong>Sample 3: Multiple Dimensions</strong></p><p>In Multi dimensions request, metrics values are grouped by dimensions in their order. You can understand this by comparing this to pandas DataFrame groupby with more than one column and aggregate other columns by sum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25b305a24a4871e9902efc2c5b8c2e70/href">https://medium.com/media/25b305a24a4871e9902efc2c5b8c2e70/href</a></iframe><p><strong>Sample 4: Histogram Buckets</strong></p><p>We add list of histogramBuckets to dimensions, where each value in list, is starting number of bucket. Also, add orderBys to request to define order of buckets. Following code we will return a dictionary of session count buckets and user counts with respect to bucket.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc5833f7adec873d125f7a078ac94294/href">https://medium.com/media/cc5833f7adec873d125f7a078ac94294/href</a></iframe><blockquote><strong>Note:</strong> It is also possible to get segments, pivots, and cohorts through Google Analytics Reporting API. See samples <a href="https://developers.google.com/analytics/devguides/reporting/core/v4/samples"><strong>here</strong></a>.</blockquote><h4><strong>4. Data processing</strong></h4><p>Request submission return a dictionary object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhKnnmgFyiIzAx9aD1aU8g.png" /><figcaption>A data sample</figcaption></figure><p>Let’s process data from samples showed in step 3.</p><ol><li><strong>Dimensions and Metrics</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c478026419b217f89e2582d92c8590df/href">https://medium.com/media/c478026419b217f89e2582d92c8590df/href</a></iframe><p>Above code will create a pandas DataFrame from dictionary object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILlVTUaOb0x0Z-dbWNboMw.png" /><figcaption>Output pandas DataFrame</figcaption></figure><p><strong>2. Multiple Date Ranges</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44542413eb3d256452dcd4fcfce41541/href">https://medium.com/media/44542413eb3d256452dcd4fcfce41541/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2jhPG4UA6hAPO2GH_FAHA.png" /><figcaption>Multi date range DataFrame</figcaption></figure><p><strong>3. Multiple Dimensions</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c478026419b217f89e2582d92c8590df/href">https://medium.com/media/c478026419b217f89e2582d92c8590df/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*g2srsBhuudUI_xQe5YnTVg.png" /><figcaption>Multi dimensions range DataFrame</figcaption></figure><p><strong>4. Histogram Histogram Buckets</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c478026419b217f89e2582d92c8590df/href">https://medium.com/media/c478026419b217f89e2582d92c8590df/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*4zxsSFWkWyZNzlfa826r0Q.png" /><figcaption>Histogram buckets DataFrame</figcaption></figure><p><strong>Jupyter Notebook </strong>for this tutorial, is available on<strong> </strong><a href="https://github.com/dc-aichara/DS-ML-Public/blob/master/Medium_Files/GA.ipynb"><strong>Github</strong></a>.</p><h4>Summary:</h4><ol><li>Create a project &amp; a service account on Google Cloud Platform, enable Google Analytics API, and download credentials.</li><li>Do authentication.</li><li>Write requests and execute them.</li><li>Process dictionary object to get a pandas DataFrame.</li></ol><p><strong>Notes:</strong></p><ol><li>It is possible to define specific date ranges using python libraries. Read date and time related article to see use cases.</li></ol><p><a href="https://medium.com/analytics-vidhya/a-complete-date-time-guide-for-data-scientist-in-python-cd0b1cfb5e74">A Complete Date-Time Guide for Data Scientist in Python</a></p><p>2. We can store pandas DataFrame in Google Sheets. How? Read my another article on Medium.</p><p><a href="https://medium.com/game-of-data/play-with-google-spreadsheets-with-python-301dd4ee36eb">Play with Google Spreadsheets with Python</a></p><p>Thank you for reading! If you have any query, please comment below or reach out to me on <a href="https://www.linkedin.com/in/dcaichara/"><strong>LinkedIn</strong></a> or <a href="https://twitter.com/dc_aichara"><strong>Twitter</strong>.</a></p><h4><strong>References:</strong></h4><ol><li><a href="https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py">https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py</a></li><li><a href="https://developers.google.com/analytics/devguides/reporting/core/v4/samples">https://developers.google.com/analytics/devguides/reporting/core/v4/samples</a></li><li><a href="https://cloud.google.com/iam/docs/creating-managing-service-accounts">https://cloud.google.com/iam/docs/creating-managing-service-accounts</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3930831fba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-get-google-analytics-report-data-as-pandas-dataframe-e3930831fba">How to Get Google Analytics Report Data as Pandas DataFrame?</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Date-Time Guide for Data Scientist in Python]]></title>
            <link>https://medium.com/analytics-vidhya/a-complete-date-time-guide-for-data-scientist-in-python-cd0b1cfb5e74?source=rss-c6c6dcd9f4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd0b1cfb5e74</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-scientist]]></category>
            <dc:creator><![CDATA[Dayal Chand Aichara]]></dc:creator>
            <pubDate>Thu, 10 Oct 2019 05:09:53 GMT</pubDate>
            <atom:updated>2019-10-18T07:53:03.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIyWBJl5DBCRoRZHjXbZhA.jpeg" /><figcaption>Phi Phi Islands 🌴, Thailand</figcaption></figure><h4>A complete guide to deal and process date &amp; time data in python using different python packages</h4><p>Everybody needs to deal with date &amp; time data in some point of data science work. Date &amp; time data help to find important insights such as on which day of the week your website gets maximum hits, in which hour maximum transactions are made or in which hour maximum crypto / stocks are traded etc.</p><p>In this article, I will demonstrate usefulness of few very important python packages to date &amp; time data. Let’s start without any further ado.</p><h3><strong>1. pandas</strong></h3><p>pandas is most used python package along with numpy in data science. Pandas can be used to clean and process date &amp; time data.</p><p><strong>1.1 String to Timestamp</strong><br>When we read a CSV file using pd.read_csv(&#39;data.csv&#39;) command, pandas reads date column as an object (string). Pandas can be used to convert string to Timestamp object.</p><p>First import pandas: import pandas as pd</p><p>I will use <a href="https://www.rugbyworldcup.com/matches">Rugby World Cup 2019 data</a> for this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R57XM94Mu2BdF-_JajV0sA.png" /><figcaption>String to Timestamp</figcaption></figure><blockquote><strong>Bonus 1 : </strong>We can convert seconds or nanoseconds to DateTime using pd.to.datetime()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9C2PoSdazdWCJd1fniUJbw.png" /><figcaption>Seconds and nanoseconds to Timestamp conversion</figcaption></figure><h4><strong>1.2 Processing Timestamp</strong></h4><p>Once we have date and time as Timestamp, we can get year, month, day of month, day of week, hour, minute, seconds from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aYvI8bY0ecTXuzl1qKykw.png" /><figcaption>Timestamp to year, month, day of month, day of week, hour, minutes and seconds</figcaption></figure><blockquote><strong>Bonus:</strong> <em>How to change Timestamp format? </em><em>strftime(format=&quot;desired_format&quot;)<br>is an option. See examples below.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqhhJ6GQyjMJmjtTNAqy_w.png" /></figure><p><strong>Note:</strong> strftime() returns a string. This should be changed to Timestamp using pd.to_datetime() .</p><h3><strong>2. datetime</strong></h3><p>datetime python package is an another import package to process date &amp; time data.</p><p>Import sub-packages from datetime as below:</p><pre>from datetime import datetime, timedelta, timezone</pre><p><strong>datetime</strong> is used to create and process datetime object. Let’s see few important usages of datetime .</p><p><strong>datetime.now() </strong>→ Current date and time in current time zone</p><p><strong>datetime.utcnow() </strong>→ Current UTC time</p><p><strong>datetime.taoday()</strong> → Current date and time in current time zone</p><p><strong>datetime(year, month, day, hour, minutes, seconds)</strong> → create a datetime object</p><blockquote>We can also get year, month, day of month, day of the week, hour, minutes and seconds values from datetime object same as Timestamp object.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G7P4d_AB0oZAy-UPsFL3GA.png" /><figcaption>datetime examples</figcaption></figure><p><strong>timedelta </strong>is mainly used to add or subtract time from datetime object.</p><blockquote>Example:</blockquote><blockquote>datetime ± timedelta(weeks=0, days=0, hours=0, minutes=0, seconds=0), where datetime is datetime object.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1CiWUbEqRoKvYqWx-4mGw.png" /><figcaption>timedelta</figcaption></figure><h3><strong>3. pytz</strong></h3><p>This library allows accurate and cross platform timezone calculations using Python 2.4 or higher.</p><p>Install pytz via pip. pip install pytz .</p><p>pytz can be use to get specific time zone date and time , also to make a specific time zone datetime object. See examples in picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbRHLFuH5OaeioZz0nboRw.png" /><figcaption><strong>pytz</strong></figcaption></figure><h3><strong>4. dateutil</strong></h3><p>I found two important applications of dateutil package: I. Parsing and II. Getting relative date and time (datetime object)</p><p>I. <strong>Parsing</strong>: Parsing is process of converting string to datetime.</p><p>II. <strong>Getting relative date and time</strong>: we just learned time subtraction and addition with timedelta. timedelta add or subtract exact number but what if we want get relative time for example exact one month back or later from today. In this case detail is very useful. See examples in picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vy9Eb5vGf437nrleDTpCrw.png" /><figcaption>dateutil examples</figcaption></figure><blockquote><strong>Pro tips:</strong></blockquote><ol><li>Always use relativedelta to get exact time from specific time because number of days are not same in each month which makes hard to use timedelta.</li><li>If you know the time difference between two time zones then use timedelta instead of pytz.</li><li>Use pandas to convert string into date &amp; time (Timestamp) while working with pandas dataframe.</li></ol><p>Find <a href="https://github.com/dc-aichara/DS-ML-Public/blob/master/Medium_Files/Date_Time.ipynb">Jupyter NoteBook on Github</a> to view codes.</p><p>Reach out to me on <a href="https://www.linkedin.com/in/dcaichara/">LinkedIn</a> or <a href="https://twitter.com/dc_aichara">twitter</a> if you have any query .</p><p>Thank you for reading article .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd0b1cfb5e74" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/a-complete-date-time-guide-for-data-scientist-in-python-cd0b1cfb5e74">A Complete Date-Time Guide for Data Scientist in Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyperparameters Optimization for LightGBM, CatBoost and XGBoost Regressors using Bayesian…]]></title>
            <link>https://medium.com/analytics-vidhya/hyperparameters-optimization-for-lightgbm-catboost-and-xgboost-regressors-using-bayesian-6e7c495947a9?source=rss-c6c6dcd9f4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e7c495947a9</guid>
            <category><![CDATA[bayesian-optimization]]></category>
            <category><![CDATA[catboost]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[lightgbm]]></category>
            <dc:creator><![CDATA[Dayal Chand Aichara]]></dc:creator>
            <pubDate>Fri, 16 Aug 2019 01:55:46 GMT</pubDate>
            <atom:updated>2019-10-18T09:12:53.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReEApCc0X8HQP8vyHoJTyA.jpeg" /><figcaption><strong>A busy street in Tokyo, Japan. Finding English speaking person here, is as hard as finding best hyperparameters for boosting algorithms. </strong>😉</figcaption></figure><h3>Hyperparameters Optimization for LightGBM, CatBoost and XGBoost Regressors using Bayesian Optimization.</h3><h4>How to optimize hyperparameters of boosting machine learning algorithms with Bayesian Optimization?</h4><p>Boosting machine learning algorithms are highly used because they give better accuracy over simple ones. Performance of these algorithms depends on hyperparameters. An optimal set of parameters can help to achieve higher accuracy. Finding hyperparameters manually is tedious and computationally expensive. Therefore, automation of hyperparameters tuning is important. RandomSearch, GridSearchCV, and Bayesian optimization are generally used to optimize hyperparameters. <a href="http://papers.nips.cc/paper/4522-practical-bayesian-optimization-of-machine-learning-algorithms.pdf">Bayesian optimization</a> gives better and fast results compare to other methods.</p><p><strong>How does Bayesian optimization work?</strong></p><ol><li>Build a surrogate probability model of the objective function</li><li>Find the hyperparameters that perform best on the surrogate</li><li>Apply these hyperparameters to the true objective function</li><li>Update the surrogate model incorporating the new results</li><li>Repeat steps 2–4 until max iterations or time is reached</li></ol><p>Bayesian optimizer build a probability model of the a given objective function and use it to select the most promising hyperparameters to evaluate in the true objective function. If you want to study in deep then read<a href="http://papers.nips.cc/paper/4522-practical-bayesian-optimization-of-machine-learning-algorithms.pdf"><strong> here</strong></a> and <a href="https://towardsdatascience.com/a-conceptual-explanation-of-bayesian-model-based-hyperparameter-optimization-for-machine-learning-b8172278050f"><strong>here</strong></a>.</p><p><strong>How to optimize hyperparameters with Bayesian optimization?</strong></p><p>I will use <a href="https://github.com/fmfn/BayesianOptimization">bayesian-optimization</a> python package to demonstrate application of Bayesian model based optimization. Install bayesian-optimization python package via pip .</p><p>pip install bayesian-optimization</p><p>Hyperparameters optimization process can be done in 3 parts.</p><p><strong>Part 1 — Define objective function</strong></p><p>Define an objective function which takes hyperparameters as input and gives a score as output which has be maximize or minimize.</p><p><strong>Part 2 — Define search space of hyperparameters</strong></p><p>Define a range of hyperparameters to optimize. Keep the parameter range narrow for better results.</p><p><strong>Part 3 — Define a surrogate model of the objective function and call it.</strong></p><p>Make a Bayesian optimization function and call it to maximize objective output. Bayesian optimization function takes 3 inputs: Objective Function , Search Space , and random_state .</p><p>Let’s implement Bayesian optimization for boosting machine learning algorithms for regression purpose.</p><p><strong>Import libraries and load data.</strong></p><p>I will use <a href="https://www.kaggle.com/c/boston-housing/data">Boston Housing</a> data for this tutorial.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2533c634fbb6e7b2228bb9cb2bb5cc11/href">https://medium.com/media/2533c634fbb6e7b2228bb9cb2bb5cc11/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJkq9eJOicpWhtek_pC1SQ.png" /><figcaption>First 5 rows of Boston Housing data.</figcaption></figure><p>Our data has 13 predictor variables (independent variables ) and Price as<strong> </strong>criterion variable (dependent variable).</p><h4><strong>1. LightGBM Regressor</strong></h4><p><strong>a. Objective Function</strong></p><p>Objective function will return negative of l1 (absolute loss, alias=mean_absolute_error, mae). Objective will be to miximize output of objective function. You can use l2 , l2_root , poisson also instead of l1 .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f56fcc738ed65531a61b51d2dc4fa0e4/href">https://medium.com/media/f56fcc738ed65531a61b51d2dc4fa0e4/href</a></iframe><p><strong>Note:</strong></p><blockquote>LightGBM and XGBoost don’t have R-Squared metric. If you want to use R2 metric instead of other evaluation metrics, then write your own R2 metric.</blockquote><p><strong>See an example of objective function with R2 metric.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86523c313b71421a02b9e68db43ac496/href">https://medium.com/media/86523c313b71421a02b9e68db43ac496/href</a></iframe><p><strong>b. Search Space</strong></p><p>Define range of input parameters of objective function. You can define number of input parameters based on how many hyperparameters you want to optimize. This example has 6 hyperparameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28fd136f33a46eb6c4853474557b7307/href">https://medium.com/media/28fd136f33a46eb6c4853474557b7307/href</a></iframe><p><strong>c. Surrogate Model and Optimization</strong></p><p>Define a Bayesian optimization function and maximize the output of objective function. Sum of init_points and n_iter is equal to total number of optimization rounds.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfd343b529a0bc160617c91c929965a5/href">https://medium.com/media/cfd343b529a0bc160617c91c929965a5/href</a></iframe><p><strong><em>Put all together in a single function.</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/433416b4ada860b95b373af9687810b2/href">https://medium.com/media/433416b4ada860b95b373af9687810b2/href</a></iframe><p>Output of above code will be table which has output of objective function as target and values of input parameters to objective function. To get best parameters use obtimizer.max[&#39;params&#39;] .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71gBxXRp43JfUdrD56oVYw.png" /><figcaption>Hyperparameters optimization results table of LightGBM Regressor</figcaption></figure><h4><strong>2. Catboost Regressor</strong></h4><p><strong>a. Objective Function</strong></p><p>Objective function takes two inputs : depth and bagging_temperature . Objective function will return maximum mean R-squared value on test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22c304828d4903d781c2558c3ab799a2/href">https://medium.com/media/22c304828d4903d781c2558c3ab799a2/href</a></iframe><p><strong>b. Search Space</strong></p><p>Objective function has only two input parameters, therefore search space will also have only 2 parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2efbadbbf8f25c33cd6855a18937357/href">https://medium.com/media/a2efbadbbf8f25c33cd6855a18937357/href</a></iframe><p><strong>c.</strong> <strong>Surrogate Model and Optimization</strong></p><p>Bayesian optimizer will optimize depth and bagging_temperature to miximize R2 value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72ceacd366a86fd371a1a5d5e7ed47ec/href">https://medium.com/media/72ceacd366a86fd371a1a5d5e7ed47ec/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*AP40EJGMMifDHjr3HzeGzw.png" /><figcaption>Hyperparameters optimization results table for CatBoost Regressor</figcaption></figure><h4><strong>3. XGBoost Regressor</strong></h4><p><strong>a. Objective Function</strong></p><p>Objective function gives maximum value of r2 for input parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce1f29ae75b0993081a281aef171e15e/href">https://medium.com/media/ce1f29ae75b0993081a281aef171e15e/href</a></iframe><p><strong>Note:</strong></p><ol><li>If eval_metric is included in parameters , then use early_stopping_rounds smaller number (10 or less ). Why? Because if the value of evaluation metric doesn’t improve for given early stopping rounds then training will stop.</li><li>If eval_metric is not defined in parameters, then use early_stopping_rounds larger number but less than num_boost_rounds. Why? Because training will stop at given early stoping round.</li></ol><p><strong>b. Search Space</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0f7b0f63ad3d6f8b8dcf49746d63b2d/href">https://medium.com/media/d0f7b0f63ad3d6f8b8dcf49746d63b2d/href</a></iframe><p><strong>c. Surrogate Model and Optimization</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de3ceebbb2854910c840e5f1389e8226/href">https://medium.com/media/de3ceebbb2854910c840e5f1389e8226/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQKcJv65czbpInajldjGHw.png" /><figcaption>Hyperparameters optimization results table of XGBoost Regressor</figcaption></figure><p>I hope, you have learned whole concept of hyperparameters optimization with Bayesian optimization. Hyperparameters tuning seems easy now. Right?</p><h4><strong>Conclusion</strong></h4><p>It is easy to optimize hyperparameters with Bayesian Optimization . LightGBM and XGBoost don’t have r2 metric, therefore we should define own r2 metric . <strong>There is little difference in </strong><strong>r2 metric for LightGBM and XGBoost. LightGBM R2 metric should return 3 outputs, whereas XGBoost R2 metric should return 2 outputs.</strong></p><p>We can use different evaluation metrics based on model requirement. Keep the search space parameters range narrow for better results. bayesian-optimization maximize the output of objective function, therefore output must be negative for l1 &amp; l2 , and positive for r2 .</p><p>Check out <a href="https://github.com/dc-aichara/DS-ML-Public/blob/master/Medium_Files/hyp_tune.ipynb"><strong>Notebook on Github</strong></a> or <a href="https://colab.research.google.com/drive/1gWwUa3ASZLJTijy3JoJl_nEqHlwHVIeB"><strong>Colab Notebook</strong> </a>to see use cases. Reach out to me on <a href="https://www.linkedin.com/in/dcaichara/"><strong>LinkedIn</strong></a> if you have any query. Happy Parameter Tuning! Thank You for reading..! ☺️</p><h4><strong>References:</strong></h4><ol><li><a href="https://towardsdatascience.com/a-conceptual-explanation-of-bayesian-model-based-hyperparameter-optimization-for-machine-learning-b8172278050f">https://towardsdatascience.com/a-conceptual-explanation-of-bayesian-model-based-hyperparameter-optimization-for-machine-learning-b8172278050f</a></li><li><a href="https://towardsdatascience.com/an-introductory-example-of-bayesian-optimization-in-python-with-hyperopt-aae40fff4ff0">https://towardsdatascience.com/an-introductory-example-of-bayesian-optimization-in-python-with-hyperopt-aae40fff4ff</a>o</li><li><a href="https://medium.com/spikelab/hyperparameter-optimization-using-bayesian-optimization-f1f393dcd36d">https://medium.com/spikelab/hyperparameter-optimization-using-bayesian-optimization-f1f393dcd36d</a></li><li><a href="https://www.kaggle.com/omarito/xgboost-bayesianoptimization">https://www.kaggle.com/omarito/xgboost-bayesianoptimization</a></li><li><a href="https://github.com/fmfn/BayesianOptimization">https://github.com/fmfn/BayesianOptimization</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e7c495947a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/hyperparameters-optimization-for-lightgbm-catboost-and-xgboost-regressors-using-bayesian-6e7c495947a9">Hyperparameters Optimization for LightGBM, CatBoost and XGBoost Regressors using Bayesian…</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Play with Google Spreadsheets with Python]]></title>
            <link>https://medium.com/game-of-data/play-with-google-spreadsheets-with-python-301dd4ee36eb?source=rss-c6c6dcd9f4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/301dd4ee36eb</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pygsheets]]></category>
            <category><![CDATA[google-spreadsheets]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dayal Chand Aichara]]></dc:creator>
            <pubDate>Fri, 14 Jun 2019 07:18:13 GMT</pubDate>
            <atom:updated>2019-07-19T03:40:55.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Automate Google Sheets with Python</h3><h4>How to use pygsheets python package to play around google sheets and to automate.</h4><p>Google spreadsheets are easy to maintain, edit, and share with people with python package <a href="https://github.com/nithinmurali/pygsheets"><strong>pygsheets</strong></a>. I have been using pygsheets for long time to automate my daily work in google spreadsheets.</p><p><strong>pygsheets is a simple intuitive python library to access google spreadsheets through the Google Sheets API v4.</strong></p><p>Automating Google Sheets with python is not as hard as climbing Mount Fuji. 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*hqfZIeZU9BddMO6Yi2RewQ.jpeg" /><figcaption>A picture from my Mount Fuji trekking.</figcaption></figure><p>Everyone knows what google spreadsheets are and how to use them. In this article , we will learn how to play around google spreadsheets with python. So, without further ado, let’s start.</p><p><strong>Installation</strong></p><pre>pip install pygsheets</pre><p><strong>Get client secret</strong></p><p><a href="https://developers.google.com/sheets/api/guides/authorizing">Obtain OAuth2 credentials from Google Developers Console for google spreadsheet api and drive api </a>and save the file as client_secret.json in same directory as project. See complete guide <a href="https://pygsheets.readthedocs.io/en/latest/authorization.html"><strong>here</strong></a>.</p><p><strong>Authorization</strong></p><pre>import pygsheets<br>gc = pygsheets.authorize() <br><strong># Use customized credentials</strong> <br>gc = pygsheets.authorize(custom_credentials=my_credentials)</pre><pre># For the first time, it will may produce as a link to authorize</pre><p><strong>Open spreadsheets and worksheets</strong></p><p>Google spreadsheets can be opened by name, id , and link. Worksheets can be accessed by name or index.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1ed8cdd0b821fc582c41af04267486e/href">https://medium.com/media/f1ed8cdd0b821fc582c41af04267486e/href</a></iframe><h4><strong>Playing around spreadsheet</strong></h4><p><strong>Authorize and open a spreadsheet</strong></p><pre>import pygsheets<br>gc = pygsheets.authorize()</pre><pre>sh = gc.open(&#39;medium&#39;) # Open a spreadsheet with name &#39;medium&#39;.</pre><p><strong>Get spreadsheet title</strong></p><pre>sh.id     # Returns id of spreadsheet</pre><p><strong>Get spreadsheet id</strong></p><pre>sh.title      # Returns title of spreadsheet</pre><p><strong>Get spreadsheet url</strong></p><pre>sh.url     # Returns url of spreadsheet</pre><p><strong>Check last update</strong></p><pre>sh.updated  # Returns date and time of last update</pre><p><strong>Delete spreadsheet</strong></p><pre>sh.delete() # Delete spreadsheet</pre><p><strong>Get worksheets info</strong></p><pre>sh.worksheets() # Return information of worksheets</pre><p><strong>Share spreadsheet</strong></p><pre>sh.share(&#39;example@gmail.com&#39;, role=&#39;commenter&#39;, type=&#39;user&#39;, emailMessage=&#39;Here is the spreadsheet we talked about!&#39;)</pre><pre>sh.share(&#39;&#39;, role=&#39;reader&#39;, type=&#39;anyone&#39;) # Make public</pre><p><strong>Remove permissions</strong></p><pre>sh.remove_permission(&#39;example@gmail.com&#39;, permission_id=None)</pre><pre># You can specify permission id</pre><p><strong>Add new worksheet</strong></p><pre>sh.add_worksheet(&#39;sheet3&#39;,rows=250, cols=20) </pre><p><strong>Delete worksheet</strong></p><pre>sh.del_worksheet(&#39;sheet3&#39;)</pre><h4>Playing around Worksheet</h4><p><strong>Open a worksheet</strong></p><pre>wk1 = sh.sheet1 or wk1 =sh[0] # Open first worksheet</pre><p><strong>Get title, id, and url of worksheet</strong></p><pre>wk1.title       # Returns title of worksheet<br>wk1.id          # Returns id of worksheet<br>wk1.url         # Returns url of worksheet</pre><p><strong>Get rows and cols count</strong></p><pre>wk1.rows # returns number of rows<br>wk1.cols # returns number of columns </pre><p><strong>Get cell object and cell value</strong></p><pre>wk1.cell((row_number,col_number))       # Returns cell object<br>wk1.cell((row_number,col_number)).value # Returns cell value as string</pre><p><strong>Get value/values/records</strong></p><pre>wk1.get_value(&#39;A1&#39;)        # Returns A1’s value<br>wk1.get_value(&#39;A1&#39;, &#39;B2&#39;)  # Returns list of values <br>wk1.get_all_values()       # Returns list of all values in worksheet<br>wk1.get_all_records()      # Returns a list of dictionaries</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*7snPwI5rZfi4B3kSmHL2Dg.png" /><figcaption>Example of get_all_records</figcaption></figure><p><strong>Update value/values</strong></p><pre>wk1.update_value(&#39;A8&#39;, &#39;40&#39;)  # Updates A8 with 40<br>or <br>wk1.update_value(&#39;A8&#39;,&#39;=A6+A7&#39;,<strong>True</strong>)#Updates A8 with sum of A6 and A7</pre><pre>wk1.update_values(&#39;A8&#39;, [[&#39;G&#39;,40]]) # Updates values in starting from A8</pre><p><strong>Get rows or columns</strong></p><pre>wk1.get_row(row_number)   # Returns a list of all values in a row <br>wk1.get_col(col_number)   # Returns a list of all values in a column</pre><p><strong>Add/delete rows and columns</strong></p><pre>wk1.add_rows(n)     # Add  n rows to worksheet at end<br>wk1.add_cols(n)     # Add n columns to worksheet at end </pre><pre>wk1.delete_rows(n)  # Delete last n rows of worksheet<br>wk1.delete_rows(n)  # Delete last n columns of worksheet</pre><p><strong>Insert rows and columns</strong></p><pre>wk1.insert_rows(row =1, number = 2) # inserts 2 new rows after 1st row</pre><pre>wk1.insert_rows(row =1, number = 1, values =[&#39;AA&#39;, 40]) # insert 1 new row and insert values in same row</pre><pre>wk1.insert_cols(col =6, number = 2) # inserts 2 new columns after 6th column</pre><pre>wk1.insert_rows(col=6, number = 1, values =[&#39;AA&#39;, 40]) # insert a new column and insert values in same column</pre><p><strong>Update row and column</strong></p><pre>wk1.update_row(row_index, values, col_offset =0) # Updates values in a row from 1st column</pre><pre>Example: &gt;&gt;&gt; wk1.update_row(9, [&#39;H&#39;, 45, 178, 81])</pre><pre>wk1.update_col(col_index, values, row_offset=0)  # Updates values in a column from 1st row</pre><pre>Example: &gt;&gt;&gt; wk1.update_col(9, [78, 45, 178, 81])</pre><p><strong>Adjust width of column and height of row</strong></p><pre>wk1.adjust_column_width(start=0, end=3, pixel_size=50) # Updates column size to 50 pixel </pre><pre>wk1.adjust_row_height(1,10, pixel_size=50) # Updates row height to 50 pixel</pre><p><strong>Resize and clear worksheet</strong></p><pre>wk1.clear(&#39;A9&#39;)     # Clear all values starting from A9<br>wk1.clear(&#39;A9:D10&#39;) # Clear values in grid range A9 to D10</pre><pre>wks.resize(num_rows, num_cols)  # Resize to given dimension </pre><p><strong>Add pandas dataframe to worksheet</strong></p><pre>wk1.set_dataframe(df, &#39;A9&#39;)#Inserts df in worksheet starting from A9</pre><pre># Note: set <strong>copy_head =False </strong> if you don&#39;t want to add first row of df</pre><p><strong>Get worksheet values as pandas dataframe</strong></p><pre>wk1.get_as_df() # Returns a pandas dataframe of worksheet</pre><pre># Note: You can specify start and end to get specific range data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*kHGh81CEkWZZs9s9uc2z4g.png" /><figcaption>Example of get_of_df()</figcaption></figure><p><strong>Add chart to worksheet</strong></p><pre>&gt;&gt;&gt;wk1.add_chart((&#39;A1&#39;, &#39;A6&#39;), [(&#39;B1&#39;, &#39;B6&#39;)], &#39;Age Chart&#39;) <br>&lt;Chart COLUMN &#39;Age Chart&#39;&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLOuF33yXmgzMvT3UAflEQ.png" /><figcaption>Chart added to worksheet.</figcaption></figure><p>I guess, you have learned enough to play around google spreadsheets with python. Many more operations can be performed with pygsheets package. Please, see<a href="https://pygsheets.readthedocs.io/en/latest/index.html"> <strong>documentation</strong></a> of <a href="https://github.com/nithinmurali/pygsheets"><strong>pygsheets</strong></a> to learn more operations.</p><p>Thank you for reading this article. Read my other Medium Articles <a href="https://medium.com/@dc.aichara">here</a>.</p><p>Reach out to me on <a href="https://www.linkedin.com/in/dcaichara/"><strong>LinkedIn</strong></a><strong>,</strong> if you have query.</p><p><strong>Reference:</strong> <a href="https://pygsheets.readthedocs.io/en/latest/index.html">https://pygsheets.readthedocs.io/en/latest/index.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=301dd4ee36eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-of-data/play-with-google-spreadsheets-with-python-301dd4ee36eb">Play with Google Spreadsheets with Python</a> was originally published in <a href="https://medium.com/game-of-data">Game of Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[12 Things to know about Jupyter NotebooK Markdown.]]></title>
            <link>https://medium.com/game-of-data/12-things-to-know-about-jupyter-notebook-markdown-3f6cef811707?source=rss-c6c6dcd9f4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f6cef811707</guid>
            <category><![CDATA[jupyter-notebook-markdown]]></category>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Dayal Chand Aichara]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 09:37:56 GMT</pubDate>
            <atom:updated>2019-06-19T01:07:26.994Z</atom:updated>
            <content:encoded><![CDATA[<h3>12 Things to know about Jupyter Notebook Markdown</h3><h4>This article is about how to write jupyter notebook markdown.</h4><p>Jupyter notebook is in trend among data enthusiasts because it is easy to use, and it allows to create and share documents that contain live code, equations, visualizations and narrative text. Jupyter notebook is used for data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.</p><p>Markdown writing skills are necessary to represent your work in jupyter notebook to provide enough explanation to reader about code and concept. In this article, you will learn how to write a good jupyter notebook markdown. I will cover 12 important things which will make you markdown expert. Let’s start.</p><p>Press<strong> </strong><strong>ESC</strong> key to exit jupyter notebook cell. Press<strong> </strong><strong>M</strong> to convert jupyter code cell to jupyter markdown.</p><ol><li><strong>Headers</strong></li></ol><pre># header 1<br>## header 2<br>### header 3<br>#### header 4<br></pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*ATiXte3MQOOUO9hPDkFISg.png" /></figure><p>2. <strong>Horizontal Line</strong></p><pre><strong>Use any of three to draw a horizontal line.</strong> <br>*** <br>---<br>___</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OenWogj2pLY7K6aLKZRVUA.png" /></figure><p>3. <strong>Text formatting</strong></p><p>Text formatting is important in order to highlight important keywords.</p><p>a. <strong><em>Text color</em></strong></p><pre>&lt;span style=&#39;color:green&#39;&gt; message/text &lt;/span&gt;<br>Example: <br>&lt;span style=&#39;color:Blue&#39;&gt; Blue is my favorite color.  &lt;/span&gt;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*EiIBcZY9wp5hgH1bOyTCOQ.png" /></figure><p>b. <strong><em>Text background</em></strong></p><pre>&lt;span style=&#39;background:yellow&#39;&gt; message/text  &lt;/span&gt;<br>Example: <br>## &lt;span style=&#39;background :yellow&#39; &gt; Background color is yellow &lt;/span&gt;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*hpJPixr5MEb7aWRi5AVzpA.png" /></figure><p>c. <strong><em>Text font-family</em></strong></p><pre>&lt;span style=&#39;font-family:font_family name&#39;&gt; message  &lt;/span&gt;<br>Examples:</pre><pre>## &lt;span style=&#39;font-family:Georgia&#39;&gt; It is Georgia font.</pre><pre>## &lt;span style=&#39;font-family:Helvetica&#39;&gt; It is  Helvetica font.</pre><pre>## &lt;span style=&#39;font-family:&quot;Times New Roman&quot;&#39;&gt; &lt;span styel=&#39;&#39;&gt;It is &quot;Times New Roman&quot; font.</pre><pre>## &lt;span style=&#39;font-family:serif&#39;&gt; It is serif font.</pre><pre>##  &lt;span style=&#39;font-family:sans-serif&#39;&gt; It is sans-serif font.</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*NucVkXmki__NE8EaSI61-w.png" /></figure><p>d. <strong><em>Text Emphasis</em></strong></p><pre>*Italic*  or _Italic_ <br>**Bold** <br>***Bold and Italic*** <br>~~Scratch Me.~~</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*T2LKvFCASNVGLxeN_WgVBQ.png" /></figure><p>f. <strong><em>Text in code style</em></strong></p><pre>`print(&#39;Hello World&#39;)`</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*6Uegyt9rkIS42tPEysKwTA.png" /></figure><p>4. <strong>Blockquotes</strong></p><pre>&gt; 1 Blockquotes<br>&gt;&gt; 2 Blockquotes<br>&gt;&gt;&gt; 3 Blockquotes<br>&gt;&gt;&gt;&gt; 4 Blockquotes<br>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; 8 Blockquotes</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rkkjiIMuRtSrK6bNzbMx4w.png" /></figure><p>5. <strong>List</strong></p><pre>1. Main list &lt;br&gt;<br>a. Sub-list &lt;br&gt;<br>b. sub list <br>2. Main list<br>* main list </pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*yD_Z8jcvJuIQQT0E93kfTQ.png" /></figure><p>6. <strong>Table</strong></p><pre>| How | To | Make | a table|<br>| :---: | :---: | :---: | :---: |<br>| in   | &lt;span style= &#39;background:yellow&#39;&gt; Jupyter &lt;/span&gt;| &lt;span style= &#39;background:yellow&#39;&gt; Notebook &lt;/span&gt;| &lt;span style= &#39;background:yellow&#39;&gt; Markdown &lt;/span&gt; |<br>| It | is | really| cool |</pre><blockquote><strong>Note: </strong>Colons can be used to align columns.<br> :--- Left align<br> ---: Right align <br> :---: Center align</blockquote><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*YiZvhpbc4VVbBm8E4j8pFA.png" /></figure><p>7. <strong>Image insertion</strong></p><pre>![](c0ban_logo.png)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*mbSKv4uyD5Do7jad-2vhuA.png" /></figure><p>8. <strong>Link insertion</strong></p><pre>[My LinkedIn link ](<a href="https://www.linkedin.com/in/dcaichara/">https://www.linkedin.com/in/dcaichara/</a>)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKyawcTyRzyTvs5_1hAdlQ.png" /></figure><p>9. Y<strong>ouTube Video</strong></p><pre>[![YouTube Video Link](<a href="http://img.youtube.com/vi/jqSuaRpCnro/0.jpg)](http://www.youtube.com/watch?v=jqSuaRpCnro)">http://img.youtube.com/vi/YOUR_YUOTUBE_VIDEO_ID/0.jpg)](http://www.youtube.com/watch?v=</a><a href="http://img.youtube.com/vi/jqSuaRpCnro/0.jpg)](http://www.youtube.com/watch?v=jqSuaRpCnro)">YOUR_YUOTUBE_VIDEO_ID</a>)</pre><pre>Example: </pre><pre>[![YouTube Video Link](<a href="http://img.youtube.com/vi/jqSuaRpCnro/0.jpg)](http://www.youtube.com/watch?v=jqSuaRpCnro)">http://img.youtube.com/vi/jqSuaRpCnro/0.jpg)](http://www.youtube.com/watch?v=jqSuaRpCnro</a>)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YKOW2KGvxebBARoV-NN2oQ.png" /><figcaption>If you click on image it will redirect you to youtube link address.</figcaption></figure><p>10. <strong>Image Link</strong></p><pre>[![photo link](DCA.jpg)](<a href="https://www.linkedin.com/in/dayal-chand-aichara-9311759b/">https://www.linkedin.com/in/d</a>caichara)</pre><p>Output will be input image. If you click on image it will redirect you to link addresses.</p><p>11. <strong>Syntax highlighting</strong></p><pre>```python<br>A = &quot;Python syntax highlighting&quot;<br>print(A)<br>for i in range(0,10):<br>    print(A)<br>```</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eZ99FeOeY7veCEIRFz0QqA.png" /></figure><p>12. <strong>Creating navigation within Jupyter Notebook</strong></p><pre># Target cell<br>&lt;a id =integer&gt; &lt;/a&gt; </pre><pre># Navigation button<br>[text](#integer)</pre><pre>Example:<br> &lt;a id =6&gt; &lt;/a&gt; &lt;br&gt; Start of Notebook</pre><pre> [Start of NoteBook](#6)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*xzDq6q8qIUbUX1gWE30ppw.png" /><figcaption>Click on the blue text line to go where black text line starts.</figcaption></figure><p>That’s it. I hope, this article will help to write a better markdown in jupyter notebook. You can find complete code on <a href="https://github.com/dc-aichara/Juputer-Notebook-Markdown">GitHub</a>. You can also download <a href="https://github.com/dc-aichara/Juputer-Notebook-Markdown/blob/master/cheatsheet/Jupyter%20Notebook%20Markdown%20Cheatsheet.pdf">jupyter notebook markdown cheatsheet</a>. Please, reach out to me on <a href="https://twitter.com/dc_aichara">twitter</a> or <a href="https://www.linkedin.com/in/dcaichara/">LinkedIn</a> in case you have any query.</p><p>Read my other articles <a href="https://medium.com/@dc.aichara">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f6cef811707" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-of-data/12-things-to-know-about-jupyter-notebook-markdown-3f6cef811707">12 Things to know about Jupyter NotebooK Markdown.</a> was originally published in <a href="https://medium.com/game-of-data">Game of Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Telegram Channel Data Extraction (User’s information, chats, and specific messages) and Data…]]></title>
            <link>https://medium.com/game-of-data/telegram-channel-data-extraction-users-information-chats-and-specific-messages-and-data-21bb54710fd3?source=rss-c6c6dcd9f4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/21bb54710fd3</guid>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[telethon]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[data-mining]]></category>
            <dc:creator><![CDATA[Dayal Chand Aichara]]></dc:creator>
            <pubDate>Tue, 19 Mar 2019 06:19:45 GMT</pubDate>
            <atom:updated>2020-05-14T08:20:54.816Z</atom:updated>
            <content:encoded><![CDATA[<h3>Telegram Group/Channel Data Extraction (User’s information, chats, and specific messages), and Data Processing</h3><h4>Telegram data extraction using Telethon package, and data processing to get dataframe of required information.</h4><p>Telegram is a cloud-based instant messaging and voice over IP service developed by Telegram Messenger LLP, a privately held company registered in London, United Kingdom.</p><p>Most of the blockchain and cryptocurrencies related companies use <a href="https://telegram.org/">telegram</a> to communicate with their world wide customers and supporters because of its <a href="https://telegram.org/">unique features</a>.</p><p>Telegram groups’ data, such as user’s informations, chats of specific channels, are analyzed to get insights of channels or to get airdrop participants info etc.</p><p>In this tutorial, I will explain how to get users’ information, chats, and messages which contain keyword, step by step.</p><p><strong>Step 1. Prerequisites.</strong></p><p>First of all you need to have a telegram account in order to extract information. Follow steps written below to get credentials (api id and api hash).</p><ol><li>Register on telegram with your mobile number.</li><li>Create telegram app <a href="https://my.telegram.org/apps">here</a>.</li><li>Note down <strong>App api_id</strong> and <strong>App api_hash.</strong></li><li>Join telegram group which information is needed. You can join telegram via group’s share link. ( Example link : <a href="https://t.me/c0ban_global">https://t.me/c0ban_global</a>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbQS21z5HkGY_tMd7CpbTw.png" /><figcaption>Fig 1. Telegram App</figcaption></figure><p><strong>Step 2. Telethon installation.</strong></p><p>Now, install T<a href="https://github.com/LonamiWebs/Telethon">elethon python package</a> on your system using terminal command pip install telethon .</p><p><strong>step 3. Telegram client creation.</strong></p><p>Create telegram client.</p><pre>from telethon import TelegramClient, sync<br>import pandas as pd</pre><pre>api_id = your API ID<br>api_hash = ‘Your API Hash’<br>group_username = ‘your group name’ # Group name can be found in group link (Example group link : <a href="https://t.me/c0ban_global">https://t.me/c0ban_global</a>, group name = &#39;<a href="https://t.me/c0ban_global">c0ban_global</a>&#39;)</pre><pre>client = TelegramClient(&#39;session_name&#39;, api_id, api_hash).start()<br><br># You will be asked to enter your mobile number- Enter mobile number with country code<br># Enter OTP (For OTP check Telegram inbox)</pre><p><strong>Step 4. Getting User&#39;s Information.</strong></p><p>Extract users information as list using client.get_participants . Participants list in below format.</p><blockquote><em>User(id=357343635, is_self=False, contact=False, mutual_contact=False, deleted=False, bot=False, bot_chat_history=False, bot_nochats=False, verified=False, restricted=False, min=False, bot_inline_geo=False, access_hash=-7182373398681298465, </em><strong><em>first_name</em></strong><em>=’DC’, </em><strong><em>last_name</em></strong><em>=Aichara, </em><strong><em>username</em></strong><em>=dcaichara, phone=None, photo=UserProfilePhoto(photo_id=1534779226214999983, photo_small=FileLocation(dc_id=2, volume_id=238230043, local_id=76130, secret=-6996523002233662137, file_reference=b’\x00\\\x90s\xa46\x89\xa0/Z0\xc0K]\x8a!:\x15\x8f\x07\x90&#39;), photo_big=FileLocation(dc_id=2, volume_id=238230043, local_id=76132, secret=-2346907879263725163, file_reference=b’\x00\\\x90s\xa4w\xc0\xa5K”l+\xe0\x94\x9b\xb4\xa9\xf2\x07\xbe\xe8&#39;)), status=UserStatusOffline(was_online=datetime.datetime(2019, 3, 19, 0, 42, 32, tzinfo=datetime.timezone.utc)), bot_info_version=None, restriction_reason=None, bot_inline_placeholder=None, lang_code=None)</em></blockquote><p>You can extract information required from participants list. You can further process data to get a dataframe of intended information.</p><pre>participants = client.get_participants(group_username)<br><br># This code can be used to extracted upto 10k user&#39;s details<br># Let&#39;s get first name, last name and username<br><br>firstname =[]<br>lastname = []<br>username = []<br>if len(participants):<br>    for x in participants:<br>        firstname.append(x.first_name)<br>        lastname.append(x.last_name)<br>        username.append(x.username)<br><br># list to data frame conversion<br><br>data ={&#39;first_name&#39; :firstname, &#39;last_name&#39;:lastname, &#39;user_name&#39;:username}<br><br>userdetails = pd.DataFrame(data)</pre><p><strong>Step 5. Getting Chats.</strong></p><p>We use client.get_messages to get chat history. See chat history format below.</p><blockquote>Message(<strong>id</strong>=105406, to_id=PeerChannel(channel_id=1050637540), <strong>date</strong>=datetime.datetime(2019, 3, 18, 21, 46, 40, tzinfo=datetime.timezone.utc), <strong>message</strong>=’Hello everyone ?’, out=False, mentioned=False, media_unread=False, silent=False, post=False, from_scheduled=False, <strong>from_id</strong>=667966548, fwd_from=None, via_bot_id=None, <strong>reply_to_msg_id</strong>=None, media=None, reply_markup=None, entities=[], views=None, edit_date=None, post_author=None, grouped_id=None)</blockquote><pre>chats =client.get_messages(group_username, n) # n number of messages to be extracted<br># Get message id, message, sender id, reply to message id, and timestamp</pre><pre>message_id =[]<br>message =[]<br>sender =[]<br>reply_to =[]<br>time = []<br>if len(chats):<br>    for chat in chats:<br>        message_id.append(chat.id)<br>        message.append(chat.message)<br>        sender.append(chat.from_id)<br>        reply_to.append(chat.reply_to_msg_id)<br>        time.append(chat.date)<br>data ={&#39;message_id&#39;:message_id, &#39;message&#39;: message, &#39;sender_ID&#39;:sender, &#39;reply_to_msg_id&#39;:reply_to, &#39;time&#39;:time}<br>df = pd.DataFrame(data)</pre><p><strong>Step 6. Extracting Specific messages.</strong></p><p>Extracting messages which have specific keywords. Use cleint.iter_messages to get messages with specific keyword. See message example for keyword <strong>c0ban</strong> in telegram channel <strong>c0ban Global Community</strong> chat history.</p><blockquote>Message(id=29, to_id=PeerChannel(channel_id=1272398905), <strong>date</strong>=datetime.datetime(2018, 11, 16, 8, 17, 9, tzinfo=datetime.timezone.utc), <strong>message</strong>=’<strong>Welcome to c0ban global community</strong> 👋’, out=False, mentioned=False, media_unread=False, silent=False, post=False, from_scheduled=False, from_id=656819292, fwd_from=None, via_bot_id=None, reply_to_msg_id=None, media=None, reply_markup=None, entities=[], views=None, edit_date=None, post_author=None, grouped_id=None)</blockquote><pre># messages =[]<br>time = []<br>for message in client.iter_messages(group_username, search=&#39;keyword&#39;):<br>    messages.append(message.message) # get messages <br>    time.append(message.date) # get timestamp</pre><pre>data ={&#39;time&#39;:time, &#39;message&#39;:messages}<br><br>df = pd.DataFrame(data)</pre><p>I hope, you liked this article. Complete code is available on <a href="https://github.com/dc-aichara/DS-ML-Public/blob/master/Medium_Files/telegram.py"><strong>Github</strong></a>. Reach out to me on <a href="https://www.linkedin.com/in/dayal-chand-aichara-9311759b/"><strong>LinkedIn</strong></a><strong> </strong>or <a href="https://twitter.com/dc_aichara"><strong>Twitter</strong></a>, if you have any query.</p><p><strong>Reference: </strong><a href="https://media.readthedocs.org/pdf/telethon/stable/telethon.pdf">https://media.readthedocs.org/pdf/telethon/stable/telethon.pdf</a></p><p><strong>Note:</strong> To extract private channel’s data, you must have admin privileges.</p><h4><strong>Bonus:</strong> If you struggle to find best hyperparameters for boosting algorithms, read my latest article to help yourself.</h4><p><a href="https://medium.com/game-of-data/hyperparameters-optimization-for-lightgbm-catboost-and-xgboost-regressors-using-bayesian-6e7c495947a9">Hyperparameters Optimization for LightGBM, CatBoost and XGBoost Regressors using Bayesian…</a></p><p><strong>P.P.S. : Please, read my other articles </strong><a href="https://medium.com/@dc.aichara"><strong>here</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21bb54710fd3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-of-data/telegram-channel-data-extraction-users-information-chats-and-specific-messages-and-data-21bb54710fd3">Telegram Channel Data Extraction (User’s information, chats, and specific messages) and Data…</a> was originally published in <a href="https://medium.com/game-of-data">Game of Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Animated Bar Plots of Top 16 CryptoCurrencies (Market Capitalization, Price and Volume)]]></title>
            <link>https://medium.com/@dcaichara/making-animated-bar-plots-of-top-16-cryptocurrencies-market-capitalization-price-and-volume-7889788af264?source=rss-c6c6dcd9f4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/7889788af264</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cryptocurrency-analysis]]></category>
            <dc:creator><![CDATA[Dayal Chand Aichara]]></dc:creator>
            <pubDate>Fri, 01 Mar 2019 02:15:59 GMT</pubDate>
            <atom:updated>2019-10-18T09:10:27.612Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to make animation in python using matplotlib package?</h4><p>Being a data scientist become more exciting job when you get to work in blockchain industry. As blockchain industry is booming, scope of data science and machine learning also increasing . To apply data science and machine learning to blockchain industry, basis understanding of blockchain is must. However, I won’t cover anything about blockchain in this article.</p><p>Recently, I have been exploring trading data of cryptocurrencies on different exchanges and crypto analysis platforms. There are more than 4000 crypto coins in market. Bitcoin dominates crypto market which holds 52% of total cryptocurrency market capitalization. Ethereum (11%) and Ripple (10%) are second and third as per <a href="https://www.coingecko.com/en">coingecko</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJLUWQJEhG7Q5oIqnWS9Yw.png" /><figcaption>Fig 1. Bar plot of market capitalization top 16 cryptocurrencies</figcaption></figure><p>Let’s make animated bar plot video of top 16 crypto currencies market cap-wise. Market capitalization of cryptocurrency is equal to multiplication of total supply of crypto coin and per coin price.</p><blockquote><strong>Market capitalization = Total supply of coins </strong>×<strong> Price per coin</strong></blockquote><p>I have used <a href="https://coinmarketcap.com/">Coinmarketcap</a> historical data for this tutorial. You can extract market capitalization , price and volume data of cryptocurrencies from Coinmarketcap using its API. I have collected market capitalization data of top 16 cryptocurrencies for last 600 days from Coinmarketcap. Figure 1 shows historical market capitalization data sample of top 16 cryptocurrencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G36F81hx6wApOpH3k0P-ag.png" /><figcaption>Fig 2. Historical Market Capitalization Data Sample</figcaption></figure><p><strong>Matplotlib, seaborn, and ploty </strong>are most popular visualization python packages among data scientists. Matplotlib is used for this tutorial. Now, I will explain whole process step by step.</p><p><strong>Step 1. </strong>Import pandas, matplotlib.pyplot and matplotlib.animation.</p><pre><strong>import </strong>pandas<strong> as </strong>pd<strong><br>import</strong> matplotlib.pyplot <strong>as</strong> plt<br><strong>import</strong> matplotlib.animation <strong>as</strong> animation​</pre><p>S<strong>tep 2. </strong>Read CSV data file and do some data processing and cleaning.</p><pre>crypto_cap = pd.read_csv(&#39;crypto_market_cap.csv&#39;) # Read CSV file <br> <br>crypto_cap.index = crypto_cap[&#39;date&#39;]  # Set index as date index<br>crypto_cap = crypto_cap.drop([&#39;date&#39;],axis=1) # Remove date column<br><br>crypto_cap1 = crypto_cap.T   # Get Transpose of DataFrame to make date as columns <br>crypto_cap1.index = crypto_cap1.index.str.upper() # Covert coins names to uppercase</pre><p><strong>Step 3. </strong>select a writer to write animation and define writer’s parameters.</p><pre>Writer = animation.writers[&#39;ffmpeg&#39;] # Select writer<br>writer = Writer(fps=20, metadata=dict(artist=&#39;D C Aichara&#39;)) # Writer&#39;s parameters</pre><p><strong>Step 4. </strong>Define figure and add subplots</p><pre>fig, ax = plt.subplots(figsize =(16,12))</pre><p><strong>Step 5. </strong>Define animate function.</p><p>Animate function includes data range (for our data one day ), plot definition, plot labels, axis labels, texts etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7181c6f1a87e82c1c6ca385770efb503/href">https://medium.com/media/7181c6f1a87e82c1c6ca385770efb503/href</a></iframe><p><em>Note 1.</em> Use <strong>ax.clear() </strong>before plot definition to avoid overlap of plots in animation.</p><p><em>Note 2.</em> You can customize plot as per you requirements and preferences.</p><p><strong>Step 6.</strong> Create animation using <strong>FuncAnimation</strong>.</p><pre>ani = animation.FuncAnimation(fig, animate, interval =100, frames =575, repeat =False) # create animation</pre><blockquote>Interval in FuncAnimation is time per frame in milliseconds.</blockquote><blockquote>Frames = Number of plots (or number number of columns in our case).</blockquote><blockquote>repeat = False to stop animation at the end of frames.</blockquote><p><strong>Step 7.</strong> Save Animation.</p><pre>ani.save(&#39;crypto_market_cap.mp4&#39;)   # save Animation</pre><p>Our animation of bar plots is ready. Let’s watch it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjqSuaRpCnro%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjqSuaRpCnro&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FjqSuaRpCnro%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d471959b43ddbb418ab3bad2ade5a5c6/href">https://medium.com/media/d471959b43ddbb418ab3bad2ade5a5c6/href</a></iframe><p>In same way you can make animation of bar plots of historical price and volume data.</p><p>I hope , you got pretty much idea about how to make animation of bar plots using matplotlib through tutorial. You can find complete code on <a href="https://github.com/dc-aichara/DS-ML-Public/blob/master/Medium_Files/Bar_Plot_Animation.py"><strong>Github</strong></a>. Please, reach out to me on<strong> </strong><a href="https://www.linkedin.com/in/dayal-chand-aichara-9311759b/"><strong>LinkedIn</strong></a><strong> </strong>or <a href="https://twitter.com/dc_aichara"><strong>Twitter</strong></a>, if you have any query.</p><p>P.S. :If you are into blockchain and cryptocurrencies analysis, please join our <a href="https://t.me/joinchat/KO6mT1iY_pGrxkFg9lnPGQ"><strong>Telegram Channel</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7889788af264" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>