# -*- coding: utf-8 -*-

from WindPy import w
import talib
import pandas as pd
import numpy as np
import plotly
import plotly.offline
from plotly.offline import iplot
import cufflinks as cf
plotly.offline.init_notebook_mode(connected=True)
cf.set_config_file(theme=None, sharing='private', offline=True)
import plotly.plotly as py
import plotly.tools as tls
import plotly.graph_objs as go


w.start()
stock_list = w.wset("sectorconstituent","date=2017-06-09;windcode=000300.SH").Data[1]

stock_list = stock_list[:50]
today = "2017-06-09"
days = 20

diff = w.wsd(','.join(stock_list), "MACD", "ED-%dTD" % days, "2017-06-09", \
             "MACD_L=26;MACD_S=12;MACD_N=9;MACD_IO=1;PriceAdj=F")
dea = w.wsd(','.join(stock_list), "MACD", "ED-%dTD" % days, "2017-06-09", \
            "MACD_L=26;MACD_S=12;MACD_N=9;MACD_IO=2;PriceAdj=F")
macd = w.wsd(','.join(stock_list), "MACD", "ED-%dTD" % days, "2017-06-09", \
             "MACD_L=26;MACD_S=12;MACD_N=9;MACD_IO=3;PriceAdj=F")

# print diff
# print dea
# print macd
print "start search"
print diff
for stock_idx, stock in enumerate(diff.Codes):

    df = pd.DataFrame(
        data={
            'macd': macd.Data[stock_idx],
            'diff': diff.Data[stock_idx],
            'dea' : dea.Data[stock_idx],
        },
        index=pd.Index(diff.Times, name=stock),
        columns=['macd', 'diff', 'dea']
    )

    for macd_idx in range(df.index.size - 1):
        if df.iloc[macd_idx].macd <= 0 and df.iloc[macd_idx+1].macd >= 0 and df.iloc[macd_idx].dea < -1:
            print '%s %8.2f' % (stock, df.iloc[macd_idx]['dea'])
            break

#     print df
