# -*- coding: utf-8 -*-
"""Mlr.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1EGSeylUNEUBrGm2S08tCINPntY51YDjo
"""

!apt-get -qq install -y libarchive-dev && pip install -U metabase-data-api

from metabase_data_api import MetabaseDataApi as M
import json



url = "" #@param {type:"string"}
username = "" #@param {type:"string"}
password = "" #@param {type:"string"}

session_params = dict(user=username,
                      password=password,
                      url=url
                      )

query  = """select date_created, 
 orders,
 visitors,
 app_users,
 app_orders,
--
from schema_name.tablename jt 
 """

mbapi = M(**session_params)

#you can get the database id from the metabase url
database_id = "" #@param {type:"int"}
d = mbapi.export_from_query(query, database_id=database_id)
data = json.loads(d.decode("utf-8"))
#print(data)

import pandas as pd
import statsmodels.api as sm

df = pd.DataFrame.from_records(data, index = 'date_created')

Y = df['orders']
X = df[['visitors','app_users']]

X = sm.add_constant(X)
model = sm.OLS(Y, X).fit()

summary = model.summary()
params = model.params

df_out = df[['app_orders']]
df_out['orders_correlated_to_app_use'] = df.app_users * params['app_users']
df_out['rest_orders'] = df.orders - df.app_users * params['app_users'] - df.app_orders 
print(summary)
#print(df_out)

df_out.sort_index(inplace=True)
#plot area chart (stacked) and show the slope of the app use contribution to orders
df_out.plot.area(title=f"""Order source regression.\n App users order contribution slope: {params['app_users']}.\n Yesterday correlated order contribution: {params['app_users'] * df['app_users'].iloc[0]}""",
                 figsize=(20,10))