from flask import Flask, render_template, request, make_response, Response, flash
from functools import wraps

app = Flask(__name__)
app.secret_key = 't\xd5\x16>F\x00\x12\x0e\x16\x9b\x01@\x12_\x16\xa3^\xab\xbf\xa2\\Z\xd6-'

BASEPATH = '/www/lassp-test-stack/htdocs/wsgi_apps/stock_site/'
app.config["APPLICATION_ROOT"] = "http://lassp-test-stack.hosting.cornell.edu/sethna/stocks/"

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from StringIO import StringIO

import numpy as np
import ystockquote as yq
import pandas as pd

df = pd.load(BASEPATH + 'sitedata/SMLM_StockInfo.pickle')
X0 = np.load(BASEPATH + 'sitedata/A_full_noM.npy')
XC0 = np.load(BASEPATH + 'sitedata/XC_full.npy')
S0 = np.load(BASEPATH + 'sitedata/S_full.npy')
C0 = np.load(BASEPATH + 'sitedata/C_full.npy')
flows = np.load(BASEPATH + 'sitedata/flows.npy')
sticks = np.load(BASEPATH + 'sitedata/tickers.pickle.npy')

order = np.array([3, 1, 7, 0, 4, 2, 5, 6])

XC0= XC0[:,order]
S0 = S0[order,:]
C0 = C0[:,order]
flows = flows[:,order,:]

labs = np.array(['c-Cyclical', 'c-Energy','c-Financial', 'c-Industrial','c-Non-cyclical','c-Real estate', 'c-Tech','c-Utility'])
expl = [0.1]*8
cs = np.array(['#f781bf',      '#E41A1C', '#fff000',        '#984ea3',     '#4DAF4A',      '#a65628',   '#377eb8', '#FF7f00' ])

#labs= labs[[order]]
#cs = cs[[order]]

superdict = dict(zip(labs, np.arange(8)))

tops = sticks[np.argsort(S0, axis=1)[:,-50:]]
tops = tops.T
tops = tops[::-1]

conames = []
sectors = []
industries= []
mcaps = []
for tick in sticks:
    conames.append(df.get_value(tick,'Company Name'))
    sectors.append(df.get_value(tick, 'Sector'))
    industries.append(df.get_value(tick, 'Industry'))
    mcaps.append(df.get_value(tick, 'Market Cap'))
namesdict = dict(zip(sticks, zip(conames, sectors, industries, mcaps)))

"""def check_auth(username, password):
    #""This function is called to check if a username /
    password combination is valid.
    #""
    return username == 'ricky' and password == 'IBM2014'

def authenticate():
    #""Sends a 401 response that enables basic auth
    #""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated
"""

@app.route('/', methods=["POST", "GET"])
#@requires_auth
def tickerform():
    ticker= ""
    cover = True
    if request.method == "POST":
        ticker = request.form.get('ticker', '')
        ticker = ticker.upper()
        cover = False
        if ticker not in namesdict:
            flash("Ticker {} not in dataset".format(ticker))
            ticker = ""
    return render_template("ticker.html", ticker=ticker, namesdict=namesdict, cover=cover)

@app.route('/alltickers')
#@requires_auth
def showalltickers():
    return render_template("tickerlist.html", namesdict=namesdict)

@app.route('/allsupersecs')
#@requires_auth
def showallsupers():
    return render_template("superseclist.html", superdict=superdict)

@app.route('/allsectors')
def showallsecs():
    return render_template("classicalsecs.html")

@app.route('/flowgal')
#@requires_auth
def showflowgal():
    return render_template("flowgal.html", namesdict=namesdict)

@app.route('/piegal')
#@requires_auth
def showpiegal():
    return render_template("piegal.html", namesdict=namesdict)


@app.route('/supersec/<supersec>')
#@requires_auth
def superdisp(supersec):
    idx = superdict[supersec]
    comps = tops[:,idx]
    # print np.shape(comps)
    return render_template("supersec.html", supersec=supersec, namesdict=namesdict, comps=comps)

@app.route('/ticker/<tick>')
#@requires_auth
def tickerdisp(tick):
    ticker=tick.upper()
    return render_template("ticker.html", ticker=ticker, namesdict=namesdict)

@app.route('/tickerreturn/<tick>')
#@requires_auth
def makereturnsplot(tick):
    tick=tick.upper()
    idxa = np.argwhere(sticks==str(tick))
    if (idxa.shape !=(0,0)):
        matplotlib.rcParams['ytick.color']='#636363'
        matplotlib.rcParams['xtick.color']='#636363'
        matplotlib.rcParams['axes.linewidth']= 0
        idx = idxa[0][0]
        output=StringIO()
        plt.ioff()
        fig = plt.figure(figsize=(8,3))
        fig.frameon = False
        ax = fig.add_subplot(111)
        ax.plot(X0[:,idx], '#636363', linewidth=0.5);
        plt.xlim(0, len(X0[:,idx]))
        plt.ylim(-10,10)
        plt.xticks([343,1102,1853,2604,3359,4115,4869], ['95', '98', '01', '04', '07', '10', '13'])
        #plt.xticks(np.arange(97,len(X0[:, idx]), 504), np.arange(1994, 2014, 2))
        fig.canvas.print_png(output)
        response = make_response(output.getvalue())
        response.mimetype = 'image/png'
        return response
    else: return render_template("tickers.html", ticker=tick)

@app.route('/superreturns/<supersec>')
#@requires_auth
def makesuperreturns(supersec):
        idx = superdict[supersec]
        matplotlib.rcParams['ytick.color']='#636363'
        matplotlib.rcParams['xtick.color']='#636363'
        matplotlib.rcParams['axes.linewidth']= 0
        output=StringIO()
        plt.ioff()
        fig = plt.figure(figsize=(8,3))
        fig.frameon = False
        ax = fig.add_subplot(111)
        ax.plot(np.arange(len(XC0[:,idx])), XC0[:,idx], cs[idx]);
        plt.xlim(0, len(XC0[:,0]))
        plt.ylim(-5,5)
        plt.xticks([343,1102,1853,2604,3359,4115,4869], ['95', '98', '01', '04', '07', '10', '13'])
        #plt.xticks(np.arange(97,len(X0[:, idx]),504), np.arange(1994, 2014, 2))
        fig.canvas.print_png(output)
        response = make_response(output.getvalue())
        response.mimetype = 'image/png'
        return response

@app.route('/tickpie/<tick>')
#@requires_auth
def makefullperiodtickpie(tick):
    tick=tick.upper()
    idxa = np.argwhere(sticks==str(tick))
    if (idxa.shape !=(0,0)):
        matplotlib.rcParams['patch.linewidth'] = 0
        idx = idxa[0][0]
        output=StringIO()
        plt.ioff()
        fig = plt.figure(figsize=(3,3))
        fig.frameon = False
        ax = fig.add_subplot(111)
        ax.pie(S0[:,idx], colors=cs, explode=expl);
        fig.canvas.print_png(output)
        response = make_response(output.getvalue())
        response.mimetype = 'image/png'
        return response
    else: return render_template("tickers.html", ticker=tick)

@app.route('/tickflow/<tick>')
#@requires_auth
def makeflow(tick):
    tick=tick.upper()
    idxa = np.argwhere(sticks==str(tick))
    if (idxa.shape !=(0,0)):
        idx = idxa[0][0]
        output=StringIO()
        plt.ioff()
        fig = plt.figure(figsize=(8,3))
        fig.frameon = False
        plt.axis('off')
        ax = fig.add_subplot(111)
        yoff = 0.
        periods=np.shape(flows)[0]
        bases=np.shape(flows)[1]
        for j in np.arange(bases):
            ax.fill_between(np.arange(periods), flows[:,j,idx] + yoff, yoff,
                color= cs[j], linewidth=0, edgecolor='k')
            yoff = yoff + flows[:,j, idx]
        #plt.xlim(-15,85)
        plt.xticks(np.arange(0,periods,10))
        plt.ylim(0,1)
        ax.axes.get_yaxis().set_visible(False)
        #plt.axes(frameon=False)
        fig.canvas.print_png(output)
        response = make_response(output.getvalue())
        response.mimetype = 'image/png'
        return response
    else: return render_template("tickers.html", ticker=tick)

if __name__ == "__main__":
    app.run(debug=True,host='0.0.0.0',port=5001)
