Beispiel #1
0
    def run(self, *args, **kwargs):
        while True:
            df = LoadNet().get_QVIX()
            self.update_qvix.emit(df)

            df_north = LoadNet().get_north()
            self.update_north.emit(df_north)

            df_vol, cha = Volume().update()
            data, last = LoadNet().get_50_163()
            ser = (data['current'] - last) / last
            self.update_vol.emit(df_vol, ser)

            if not self.data_model.df_op.empty:
                df_month = self.data_model.iv_month_50300()
                self.update_month.emit(df_month)

                df_iv50, df_iv300 = self.data_model.get_iv()
                self.update_iv.emit(df_iv50, df_iv300)

                hp = HoldPositions()
                greek = hp.update(self.data_model.df_op)
                self.update_greek.emit(greek)

            time.sleep(3)
Beispiel #2
0
 def __init__(self):
     self.load = LoadNet()
     self.months = self.load.check_month()
     self.day_later = self.load.get_op_expire_day('2019')
     #print(self.day_later)
     self.etf_price = 2.95
     self.data_price = pd.DataFrame()
     self.data_iv = pd.DataFrame()
     self.histroy_high = 300
Beispiel #3
0
    def __init__(self):
        self.ln = LoadNet()

        self.stock_info_50 = self.ln.get_sz50_price()
        self.stock_info_300 = self.ln.get_sz300_price()
        self.stock_price_50etf = 0.0
        self.stock_price_300etf = 0.0
        self.df_op = pd.DataFrame()

        self.df_codes = self.init_allcodes()

        t = threading.Thread(target=self.loop)
        t.start()
Beispiel #4
0
    def update(self):
        #ax.cla()
        a = LoadNet().get_sz50_price()
        #a.cumsum(axis=0)
        str_time = a[31]
        str_time_end = "15:00:00"
        str_volume = a[9]
        tomorrow = float(a[2])
        current = float(a[3])
        #print(str_time,str_volume)
        time = pd.datetime.strptime(str_time, '%H:%M:%S')
        min_1 = pd.Timedelta(minutes=1)
        time_end = time + min_1

        #mean_data['current'][mean_data.index>time.time()] = int(str_volume)/10000
        self.mean_data.loc[self.mean_data.index > time.time(),
                           'current'] = int(str_volume) / 10000

        self.diff_data = self.mean_data.copy()
        self.diff_data['current'] = pd.to_numeric(self.diff_data['current'])
        self.diff_data['current'] = self.diff_data['current'].diff(1)
        self.diff_data.iloc[0, 1] = float(self.mean_data.iloc[0, 1])
        self.mean_data['mean'] = self.mean_data['current'] / self.mean_data[
            'VOL-TDX.VOLUME']
        self.cha = (current - tomorrow) / tomorrow * 100
        self.res = self.mean_data['mean'][
            self.mean_data.index <= time_end.time()]
        return self.mean_data['mean'][
            self.mean_data.index <= time_end.time()], self.cha
Beispiel #5
0
    def __init__(self):
        self.loadsina = LoadNet()
        self.month = self.loadsina.check_month()

        self.interestRate = 3.00
        self.stockPrice = float(self.loadsina.get_50etf_price()[3])
        self.stockPrice_future = self.stockPrice
        self.iv_future = 0
        self.dayLater = 0

        super(Windows, self).__init__()
        self.setGeometry(20, 50, 1800, 1200)
        self.currentItem = None
        self.create_ui()

        self.fill_dayWidget()
Beispiel #6
0
 def draw_qvix(self):
     self.ax_QVIX.cla()
     #print (LoadNet().get_QVIX())
     df =LoadNet().get_QVIX()
     # iv = df['QVIX'].astype(float)
     # time =df.index.values
     # print(iv,time)
     # self.ax_QVIX.plot(time,iv)
     pd.to_datetime(df['Time'])
     df.index = df['Time']
     #print(df.columns)
     df = df.drop(['Time','Pre','max','min'],axis=1)
     df.plot(ax=self.ax_QVIX)
Beispiel #7
0
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from get_day_histroy import history
import matplotlib.font_manager as font_manager
from load_sina import LoadNet

his = history()
mean_data = his.get_dayMean()
ln = LoadNet()

mean_data['current'] = 0
mean_data['mean'] = 0
POINTS = 100
sin_list = [0] * POINTS
indx = 0
zx_index = []

fig, ax = plt.subplots()
# ax.set_ylim([-2, 2])
# ax.set_xlim([0, POINTS])
# ax.set_autoscale_on(False)
#ax.set_xticks(range(0, 100, 10))
# ax.set_yticks(range(-2, 3, 1))
#ax.grid(True)

#line_sin, = ax.plot(mean_data, label='volume', color='cornflowerblue')
ax.legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=8))

print(mean_data)
diff_data = pd.DataFrame()
Beispiel #8
0
class Windows(QMainWindow):
    def __init__(self):
        self.loadsina = LoadNet()
        self.month = self.loadsina.check_month()

        self.interestRate = 3.00
        self.stockPrice = float(self.loadsina.get_50etf_price()[3])
        self.stockPrice_future = self.stockPrice
        self.iv_future = 0
        self.dayLater = 0

        super(Windows, self).__init__()
        self.setGeometry(20, 50, 1800, 1200)
        self.currentItem = None
        self.create_ui()

        self.fill_dayWidget()
        #self.fill_wight_out()

    def create_ui(self):
        wight = QWidget(self)
        wight.setGeometry(10, 10, 1400, 300)

        self.listWidget = QtWidgets.QListWidget(self)
        self.listWidget.setGeometry(QtCore.QRect(20, 40, 1000, 1000))
        self.listWidget.setObjectName("listWidget")
        self.listWidget.itemClicked.connect(self.check_in_item)

        btn_jian = QPushButton(self)
        btn_jian.move(1020, 360)
        btn_jian.resize(15, 30)
        btn_jian.setText('>')
        btn_jian.clicked.connect(self.del_item)

        wight_call = QWidget(self)
        wight_call.setGeometry(1035, 70, 100, 670)
        self.layout_call = QVBoxLayout()
        self.layout_call.setContentsMargins(0, 0, 0, 0)
        wight_call.setLayout(self.layout_call)

        wight_mid = QWidget(self)
        wight_mid.setGeometry(1135, 70, 100, 670)

        self.layout_mid = QVBoxLayout()
        self.layout_mid.setContentsMargins(0, 0, 0, 0)
        wight_mid.setLayout(self.layout_mid)

        wight_put = QWidget(self)
        wight_put.setGeometry(1235, 70, 100, 670)
        self.layout_put = QVBoxLayout()
        self.layout_put.setContentsMargins(0, 0, 0, 0)
        wight_put.setLayout(self.layout_put)

        wight_right = QWidget(self)
        wight_right.setGeometry(1355, 40, 200, 650)
        #wight_right.setStyleSheet('background-color:gray')
        layout_r = QVBoxLayout()

        self.labelr_currentstock_prince = QLabel()
        self.labelr_currentstock_prince.setText(
            self.loadsina.get_50etf_price()[3])
        labelr_2 = QLabel('利率')
        self.spin_lilv = QDoubleSpinBox()
        self.spin_lilv.setValue(self.interestRate)
        self.spin_lilv.valueChanged.connect(
            lambda val: self.set_interestRate(val))
        labelr_3 = QLabel('50etf未来价格:')
        self.spin_future = QDoubleSpinBox()
        self.spin_future.setDecimals(3)

        self.spin_future.setSingleStep(0.005)
        self.spin_future.setValue(float(
            self.labelr_currentstock_prince.text()))
        self.spin_future.valueChanged.connect(
            lambda val: self.set_stockPricefuture(val))

        self.labelr_iv_future = QLabel('未来波动:')
        # self.spin_future_iv = QDoubleSpinBox()
        # self.spin_future_iv.setDecimals(2)
        # self.spin_future_iv.setSingleStep(0.05)
        # self.spin_future_iv.setValue(self.iv_future)
        #self.spin_future_iv.valueChanged.connect(lambda val:self.set_ivFuture(val))
        self.sp = QSlider(Qt.Horizontal)
        self.sp.setMinimum(-100)
        self.sp.setMaximum(100)
        self.sp.setSingleStep(0.01)
        self.sp.setValue(self.iv_future)
        self.sp.setTickPosition(QSlider.TicksBelow)
        self.sp.setTickInterval(5)
        self.sp.valueChanged.connect(lambda val: self.set_ivFuture(val))

        labelr_daylater = QLabel('几天以后:')
        self.spin_daylater = QSpinBox()
        self.spin_daylater.setRange(0, 300)
        self.spin_daylater.setValue(self.dayLater)
        self.spin_daylater.valueChanged.connect(
            lambda val: self.set_daylater(val))

        btn_calculated = QPushButton('计算收益')
        btn_calculated.clicked.connect(self.Show_Profit)
        self.labelr_4 = QLabel('收益')
        btn_draw = QPushButton('画图')
        btn_draw.clicked.connect(self.draw)

        layout_r.addWidget(self.labelr_currentstock_prince)
        layout_r.addWidget(labelr_2)
        layout_r.addWidget(self.spin_lilv)
        layout_r.addWidget(labelr_3)
        layout_r.addWidget(self.spin_future)
        layout_r.addWidget(self.labelr_iv_future)
        layout_r.addWidget(self.sp)
        layout_r.addWidget(labelr_daylater)
        layout_r.addWidget(self.spin_daylater)
        layout_r.addWidget(btn_calculated)
        layout_r.addWidget(self.labelr_4)
        layout_r.addWidget(btn_draw)
        wight_right.setLayout(layout_r)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')
        newAct = QAction('load', self)
        saveAct = QAction('save', self)
        csvAct = QAction('load_csv', self)
        fileMenu.addAction(newAct)
        fileMenu.addAction(saveAct)
        fileMenu.addAction(csvAct)
        fileMenu.triggered[QAction].connect(self.processtrigger)

    def rest(self):
        pass

    def processtrigger(self, q):
        #保存和读取

        if q.text() == 'load':
            fname, _ = QFileDialog.getOpenFileName(self, '读取')
            data = np.load(fname)
            print(data)
            self.listWidget.clear()
            for i in range(0, data.shape[0]):
                code = str(data[i, 0])[0:8]
                ls = data[i, 1]
                count = data[i, 2]
                self.add_listwidget(code, lonshort=ls, count=count)

        elif q.text() == 'save':
            filename = QFileDialog.getSaveFileName(self, 'save file')
            count = self.listWidget.count()
            data = np.zeros((count, 3))

            for j in range(self.listWidget.count()):
                item = self.listWidget.item(j)
                code, callput, longshort, eprice, price, count, time, iv, iv_h = self.get_itemInfo(
                    item)
                data[j, :] = [code, longshort, count]
            #print (data)
            np.save(filename[0], data)

        else:
            fname, _ = QFileDialog.getOpenFileName(self, '读取')
            csv_data = pd.read_csv(fname,
                                   usecols=['代码', '买卖', '持仓'],
                                   encoding='GB2312')

            positionList = csv_data.values.tolist()
            print(positionList)

            self.listWidget.clear()
            for option in positionList:
                code = str(option[0])
                bs = option[1]
                if bs == '买':
                    ls = 1
                else:
                    ls = -1
                count = option[2]
                self.add_listwidget(code, lonshort=ls, count=count)

    def set_interestRate(self, value):
        self.interestRate = value

    def set_stockPricefuture(self, value):
        self.stockPrice_future = value

    def set_ivFuture(self, value):
        print(value)
        self.iv_future = value
        self.labelr_iv_future.setText('未来波动: ' + str(value))

    def set_daylater(self, value):
        self.dayLater = value

    def Show_Profit(self):
        pass

    def draw(self):
        pass

    def fill_dayWidget(self):
        # for i in self.layout_call.count():
        #     self.layout_call.remove(self.layout_call.children().at(i)i)

        wight_out_tt = QWidget(self)
        wight_out_tt.setGeometry(1035, 40, 300, 25)
        layout_out_tt = QHBoxLayout()
        layout_out_tt.setContentsMargins(0, 0, 0, 0)
        #wight_out_tt.setStyleSheet('background-color:red')
        for month in self.month:
            btm = QPushButton(month)
            btm.clicked.connect(self.on_monthbtm_click)
            layout_out_tt.addWidget(btm)
        wight_out_tt.setLayout(layout_out_tt)

    def check_in_item(self, item):
        self.currentItem = item
        self.get_itemInfo(item)

    def check_out_item(self):
        pass

    def on_monthbtm_click(self):
        btm = self.sender()
        month = btm.text()
        print(month)
        self.fill_wight_out(month)

    def fill_wight_out(self, month):
        for i in range(self.layout_call.count()):
            self.layout_call.itemAt(i).widget().deleteLater()
        for i in range(self.layout_mid.count()):
            self.layout_mid.itemAt(i).widget().deleteLater()
        for i in range(self.layout_put.count()):
            self.layout_put.itemAt(i).widget().deleteLater()

        callop, putop = self.loadsina.get_op_codes(month)
        for op in callop:
            opprice = self.loadsina.get_op_info(op)
            btm = QPushButton(opprice[2])
            btm.setObjectName(op)
            btm.clicked.connect(self.outBtm_click)

            self.layout_call.addWidget(btm)
        for op in callop:
            opprice = self.loadsina.get_op_info(op)
            btm = QPushButton(opprice[37][-4:])
            btm.setEnabled(False)
            self.layout_mid.addWidget(btm)

        for op in putop:
            opprice = self.loadsina.get_op_info(op)
            btm = QPushButton(opprice[2])
            btm.setObjectName(op)
            btm.clicked.connect(self.outBtm_click)
            self.layout_put.addWidget(btm)

    def outBtm_click(self):
        btm = self.sender()
        print(btm.objectName())
        self.add_listwidget(btm.objectName())

    def add_listwidget(self, opcode, lonshort=0, count=0):
        print('addlist_opcode:::' + opcode)
        greek = self.loadsina.get_op_greek_alphabet(opcode)
        print(greek)
        data = '20' + greek[12][7:11]
        #data表示是几月的合约

        expire_day = self.loadsina.get_op_expire_day(data)[1]

        callput_text = greek[0][5]  #“购”或“沽”

        eprice = greek[13]  #行权价,如c2.95

        price = greek[14]  #当前期权价格

        callput = 1
        if callput_text == '购':
            callput = 1
        else:
            callput = -1

        currentOption = Option(stockPrice=self.stockPrice,
                               strikePrice=float(eprice),
                               interestRate=self.interestRate,
                               daysToExpiration=float(expire_day),
                               callput=callput,
                               optionPrice=float(price))

        impliedVolatility = currentOption.impliedVolatility

        #print(impliedVolatility,"iv_")

        #iv_h=impliedVolatility+ self.iv_future*impliedVolatility*0.01
        #print(iv_h,"iv_h")

        delta = currentOption.delta

        gamma = currentOption.gamma

        theta = currentOption.theta

        vega = currentOption.vega

        item = QListWidgetItem()
        item.setToolTip(opcode)
        item.setSizeHint(QSize(600, 60))
        wight = QWidget()
        layout_main = QHBoxLayout()

        # label_code = QLabel('id')
        # label_code.setText(opcode)
        # layout_main.addWidget(label_code)

        spin_longshort = QSpinBox()
        spin_longshort.setMaximum(1)
        spin_longshort.setMinimum(-1)
        spin_longshort.setValue(lonshort)
        spin_longshort.setObjectName('longshort')
        layout_main.addWidget(spin_longshort)

        label_callput = QLabel('callput')
        label_callput.setObjectName('callput')
        label_callput.setText(callput_text)

        layout_main.addWidget(label_callput)

        label_eprice = QLabel('eprice')
        label_eprice.setObjectName('eprice')
        label_eprice.setText(eprice)
        layout_main.addWidget(label_eprice)

        label_price = QLabel('price')
        label_price.setObjectName('price')
        label_price.setText(price)
        layout_main.addWidget(label_price)

        Delta = QLabel('Delta')
        Delta.setText(str(delta)[0:5])
        layout_main.addWidget(Delta)
        Gamma = QLabel('Gamma')
        Gamma.setText(str(gamma)[0:5])
        layout_main.addWidget(Gamma)
        Theta = QLabel('Theta')
        Theta.setText(str(theta)[0:8])
        layout_main.addWidget(Theta)
        Vega = QLabel('Vega')
        Vega.setText(str(vega)[0:8])
        layout_main.addWidget(Vega)
        iv = QLabel('iv')
        iv.setObjectName('iv')
        iv_value = round(impliedVolatility, 4)
        iv.setText(str(iv_value)[0:5])
        #iv.setText(greek[9])
        layout_main.addWidget(iv)

        spin_count = QSpinBox()
        spin_count.setMinimum(0)
        spin_count.setValue(count)
        spin_count.setObjectName('count')
        layout_main.addWidget(spin_count)

        label_expire_day = QLabel('label_expire_day')
        label_expire_day.setObjectName('label_expire_day')
        label_expire_day.setText(str(expire_day))
        layout_main.addWidget(label_expire_day)

        wight.setLayout(layout_main)
        self.listWidget.addItem(item)
        self.listWidget.setItemWidget(item, wight)

    def del_item(self):
        if self.currentItem == None:
            return
        index = self.listWidget.row(self.currentItem)
        self.listWidget.takeItem(index)

    def get_itemInfo(self, item):
        widget = self.listWidget.itemWidget(item)
        code = item.toolTip()
        longshort = widget.findChild(QSpinBox, 'longshort').value()
        count = widget.findChild(QSpinBox, 'count').value()

        callput_text = widget.findChild(QLabel, 'callput').text()
        callput = 0

        if callput_text == '购':
            callput = 1
        else:
            callput = -1

        eprice = widget.findChild(QLabel, 'eprice').text()
        price = widget.findChild(QLabel, 'price').text()
        expire_day = widget.findChild(QLabel, 'label_expire_day').text()
        #iv =widget.findChild(QLabel,'iv').text()

        currentOption = Option(stockPrice=self.stockPrice,
                               strikePrice=float(eprice),
                               interestRate=self.interestRate,
                               daysToExpiration=float(expire_day),
                               callput=callput,
                               optionPrice=float(price))

        impliedVolatility = currentOption.impliedVolatility

        iv_h = impliedVolatility + self.iv_future * impliedVolatility * 0.01

        return code, callput, longshort, eprice, price, count, expire_day, impliedVolatility, iv_h

    def getAllListInfo(self):
        count = self.listWidget.count()
        data = np.zeros((count, 8))
        for j in range(self.listWidget.count()):
            item = self.listWidget.item(j)
            code, callput, longshort, eprice, price, count, time, iv, iv_h = self.get_itemInfo(
                item)
            data[j, :] = [
                callput, longshort, eprice, price, count, time, iv, iv_h
            ]
        return data

    def Calculation_pointMoney(self, pricefuture, iscal_greeks=False):

        #print(pricefuture)
        data = self.getAllListInfo()
        #print(data)
        alreadPay = 0
        price_sametime = 0
        delta = 0
        gamma = 0
        vega = 0
        theta = 0

        for i in range(0, data.shape[0]):
            #data[i,5]是合约距到期有多少天
            expire_day = data[i, 5]
            #day表示以新的日期算,距到期还有多少天
            day = expire_day - self.dayLater

            #print('data? ',data)

            callput = data[i, 0]

            strikePrice = data[i, 2]

            longShort = data[i, 1]

            optionPrice = data[i, 3]

            amount = data[i, 4]

            new_iv = data[i, 7]

            if day < 1:
                day = 1

            futureOption = Option(stockPrice=pricefuture,
                                  strikePrice=strikePrice,
                                  interestRate=self.interestRate,
                                  daysToExpiration=day,
                                  callput=callput,
                                  impliedVolatility=new_iv)

            if self.dayLater < expire_day:
                futureOptionPrice = futureOption.optionPrice
                if iscal_greeks:
                    delta = amount * longShort * futureOption.delta + delta
                    print("futureOption.delta=", futureOption.delta)
                    print("delta=", delta)
                    gamma = amount * longShort * futureOption.gamma + gamma
                    vega = amount * longShort * futureOption.vega + vega
                    theta = amount * longShort * futureOption.theta + theta

            else:
                print('tianshuchaoguole')
                if callput == 1:
                    if pricefuture < strikePrice:
                        futureOptionPrice = 0
                    else:
                        futureOptionPrice = pricefuture - strikePrice
                else:
                    if pricefuture > strikePrice:
                        futureOptionPrice = 0
                    else:
                        futureOptionPrice = strikePrice - pricefuture

            if True:
                alreadPay = alreadPay + longShort * optionPrice * amount * 10000
                futureOptionPrice = longShort * futureOptionPrice * amount * 10000

            else:
                futureOptionPrice = 0

            price_sametime = price_sametime + futureOptionPrice
        if iscal_greeks:
            print(delta, gamma, vega, theta)
            self.statusBar().showMessage('delta=' + str(delta) + '  gamma=' +
                                         str(gamma) + '  vega=' + str(vega) +
                                         '  theta=' + str(theta))

        return price_sametime - alreadPay

    def Show_Profit(self):
        profit = self.Calculation_pointMoney(self.stockPrice_future,
                                             iscal_greeks=True)
        #print(profit)
        self.labelr_4.setText(str(profit))

    def draw(self):
        longth = np.linspace(-0.2, 0.2, 48)
        profits = np.zeros(longth.shape[0])

        plt.figure(figsize=(16, 7.5))
        ax = plt.gca()
        ax.spines['right'].set_color('none')
        ax.spines['top'].set_color('none')
        ax.spines['bottom'].set_position(('data', 0))
        #x =longth+self.stockPrice_future
        x = longth + self.stockPrice

        for row in range(longth.shape[0]):
            #pricefuture =longth[row]+self.stockPrice_future
            pricefuture = longth[row] + self.stockPrice
            profits[row] = self.Calculation_pointMoney(pricefuture)
            if row % 4 == 0:
                #xx =longth[row]+self.stockPrice_future
                xx = longth[row] + self.stockPrice
                plt.annotate("%s" % np.trunc(profits[row]),
                             xy=(xx, profits[row]),
                             xytext=(-20, 10),
                             xycoords='data',
                             textcoords='offset points')
                plt.plot([xx, xx], [0, profits[row]],
                         color='blue',
                         linewidth=1,
                         linestyle="--")
        y = profits

        plt.plot(x, y, color='red', linewidth=2.5)
        plt.show()
Beispiel #9
0
class scan():
    def __init__(self):
        self.load = LoadNet()
        self.months = self.load.check_month()
        self.day_later = self.load.get_op_expire_day('2019')
        #print(self.day_later)
        self.etf_price = 2.95
        self.data_price = pd.DataFrame()
        self.data_iv = pd.DataFrame()
        self.histroy_high = 300
        # self.data_panel = pd.DataFrame()
        # self.fig = plt.figure()
        # self.tmp =0.0
        # self.ax = self.fig.gca(projection='3d')
        # timer = self.fig.canvas.new_timer(interval=1000)
        # timer.add_callback(self.draw)
        # timer.start()
        # plt.show()

    def get_df(self):
        self.etf_price = float(self.load.get_50etf_price()[3])
        self.data_price = pd.DataFrame()
        self.data_iv = pd.DataFrame()
        for month in self.months:
            up, down = self.load.get_op_codes(month)
            xqj_list = []
            iv_list = []
            p_list = []
            for code in up:
                data = self.load.get_op_greek_alphabet(code)
                xqj_list.append(float(data[13]))
                iv_list.append(float(data[9]))
                p_list.append(float(data[14]))
            df_p = pd.DataFrame(p_list,
                                index=xqj_list,
                                columns=[month + '_call'])
            self.data_price = pd.concat([self.data_price, df_p], axis=1)
            df_iv = pd.DataFrame(iv_list,
                                 index=xqj_list,
                                 columns=[month + '_call'])
            self.data_iv = pd.concat([self.data_iv, df_iv], axis=1)
            xqj_list = []
            iv_list = []
            p_list = []
            for code in down:
                data = self.load.get_op_greek_alphabet(code)
                xqj_list.append(float(data[13]))
                iv_list.append(float(data[9]))
                p_list.append(float(data[14]))
            df_p = pd.DataFrame(p_list,
                                index=xqj_list,
                                columns=[month + '_put'])
            self.data_price = pd.concat([self.data_price, df_p], axis=1)
            df_iv = pd.DataFrame(iv_list,
                                 index=xqj_list,
                                 columns=[month + '_put'])
            self.data_iv = pd.concat([self.data_iv, df_iv], axis=1)
        self.data_price = self.data_price[self.data_price != 0]
        #print(self.data_price)
        #print(self.data_iv)

    def find_pd_diff(self):
        df_diff = pd.DataFrame()  #期权价格偏离 越大越偏离便宜 只适用于实值
        for month in self.months:
            #列出看涨现货差价
            long_diff =self.etf_price - \
                (self.data_price.index + self.data_price[month+'_call'])
            df_diff[month + 'call_p'] = long_diff
            short_diff =self.data_price.index - \
                (self.etf_price + self.data_price[month+'_put'])
            df_diff[month + 'put_p'] = short_diff

        for index, row in df_diff.iterrows():
            for i, v in row.items():
                if v > 0.01:
                    print(df_diff)
        return df_diff

    # def find_most_cheapset(self,data):
    #     cheapest_op =data.idxmax()
    #     most_op =data.idxmin()
    #     print(cheapest_op,most_op)

    def find_combination_pd(self):
        #买一个现货赚多少钱 卖一个现货赚-多少钱
        pd_combination = pd.DataFrame()
        for month in self.months:

            good_price =self.data_price[month+'_call']- self.data_price[month+'_put']\
                -(self.etf_price-self.data_price.index)
            pd_combination[month] = -good_price * 10000

        #print(pd_combination)
        return pd_combination

    def find_good_combination(self, pd_data):
        # short_ = pd_data[pd_data.columns].min()
        # long_ = pd_data[pd_data.columns].max()
        # print(long_,short_)
        # money = long_ - short_
        long_ = 0
        short_ = 0
        money = 1
        long_date = 'none'
        short_data = 'none'
        long_right = 0
        short_right = 0
        for index, row in pd_data.iterrows():
            for i, v in row.items():
                if (v > long_):
                    long_ = v
                    long_date = i
                    long_right = index
                if (v < short_):
                    short_ = v
                    short_data = i
                    short_right = index
        money = long_ - short_
        long_ = ("%.1f" % long_)
        short_ = ("%.1f" % short_)
        #money=("%.1f" % money)
        return long_date, long_right, long_, short_data, short_right, short_, money

    def get_histroy_high(self, h):
        if h > self.histroy_high:
            self.histroy_high = h
        return self.histroy_high

    def save_excel(self):
        data = QDateTime.currentDateTime()
        currTime = data.toString("yyyy-MM-dd-hh-mm-ss")
        writer = pd.ExcelWriter('./save_file/' + currTime + '.xlsx')
        self.data_price.to_excel(writer, sheet_name='price')
        self.data_iv.to_excel(writer, sheet_name='iv')
        self.find_combination_pd().to_excel(writer, sheet_name='longshort')
        writer.save()
Beispiel #10
0
class DataModel:
    def __init__(self):
        self.ln = LoadNet()

        self.stock_info_50 = self.ln.get_sz50_price()
        self.stock_info_300 = self.ln.get_sz300_price()
        self.stock_price_50etf = 0.0
        self.stock_price_300etf = 0.0
        self.df_op = pd.DataFrame()

        self.df_codes = self.init_allcodes()

        t = threading.Thread(target=self.loop)
        t.start()

    def init_allcodes(self):
        mouths = self.ln.check_month()
        codes = self.ln.get_allop_codes(mouths)
        return codes

    def update_alldf(self):
        '''
        get 50etf 300etf
        '''
        stock_price_50_allinfo = self.ln.get_50etf_price()
        time = stock_price_50_allinfo[31]
        self.stock_price_50etf = stock_price_50_allinfo[3]
        self.stock_price_300etf = self.ln.get_300etf_price()[3]
        self.stock_info_50 = self.ln.get_sz50_price()
        self.stock_info_300 = self.ln.get_sz300_price()
        '''
        get sina info all
        '''
        codes, names, prices, eprices, edays, days = self.ln.get_allop_info(
            self.df_codes)
        df_all = pd.DataFrame()
        df_all['code'] = codes
        df_all['name'] = names
        df_all['price'] = prices
        df_all['eprice'] = eprices
        df_all['eday'] = edays
        df_all['day'] = days
        '''
        get my count discountlist
        '''
        discountlist = []
        for date, row in df_all.T.iteritems():
            discount = 0
            if '50ETF购' in row['name']:
                discount = float(self.stock_price_50etf) - float(
                    row['eprice']) - float(row['price'])
            if '50ETF沽' in row['name']:
                discount = float(row['eprice']) - float(
                    self.stock_price_50etf) - float(row['price'])
            if '300ETF购' in row['name']:
                discount = float(self.stock_price_300etf) - float(
                    row['eprice']) - float(row['price'])
            if '300ETF沽' in row['name']:
                discount = float(row['eprice']) - float(
                    self.stock_price_300etf) - float(row['price'])

            discountlist.append(discount)
        df_all['discount'] = discountlist
        '''
        count iv
        '''
        ivlist = []
        deltalist = []
        gammalist = []
        thetalist = []
        vegalist = []
        timelist = []

        for date, row in df_all.T.iteritems():

            if row['day'] == 0.0:
                impliedVolatility = 0
                delta = 0
                gamma = 0
                theta = 0
                vega = 0
                #row['price'] = float(row['price'])  + discount*1.5
            else:
                op_price = float(row['price'])
                eprice = float(row['eprice'])
                day = float(row['day'])

                callput = 1
                if '沽' in row['name']:
                    callput = -1

                stock_price = self.stock_price_50etf
                if '300ETF' in row['name']:
                    stock_price = self.stock_price_300etf
                #print (stock_price,eprice,INTERESTRate,day,callput,op_price)
                currentOption = Option(stockPrice= stock_price, strikePrice = eprice, interestRate=INTERESTRate, daysToExpiration=day,\
                    callput = callput, optionPrice=op_price)
                impliedVolatility = currentOption.impliedVolatility
                delta = currentOption.delta
                gamma = currentOption.gamma
                theta = currentOption.theta
                vega = currentOption.vega

            ivlist.append(impliedVolatility)
            deltalist.append(delta)
            gammalist.append(gamma)
            thetalist.append(theta)
            vegalist.append(vega)
            timelist.append(time)
            #print(row['month'],callput, eprice,impliedVolatility,delta,gamma,theta,vega)
            #print(impliedVolatility)
        df_all['delta'] = deltalist
        df_all['gamma'] = gammalist
        df_all['vega'] = vegalist
        df_all['theta'] = thetalist
        df_all['iv'] = ivlist
        df_all['time'] = timelist

        self.df_op = df_all.copy()
        #print (self.df_op)
        #self.df_op.to_csv('./Result1.csv',index=0)

    def get_iv(self):
        '''
        50
        '''
        df_50 = self.df_op[self.df_op['name'].str.contains('50ETF购')]
        mindex = df_50['eprice'].drop_duplicates()
        eday = df_50['eday'].drop_duplicates()

        df_50call_res = pd.DataFrame(index=mindex, columns=eday)
        for date, row in df_50.T.iteritems():
            df_50call_res.loc[row['eprice'], row['eday']] = row['iv']
        df_50call_res['x'] = df_50call_res.index

        df_50_put = self.df_op[self.df_op['name'].str.contains('50ETF沽')]
        mindex = df_50_put['eprice'].drop_duplicates()
        eday = df_50_put['eday'].drop_duplicates()

        df_50put_res = pd.DataFrame(index=mindex, columns=eday)
        for date, row in df_50_put.T.iteritems():
            df_50put_res.loc[row['eprice'], row['eday']] = row['iv']
        df_50put_res['x'] = df_50put_res.index

        df_50res = pd.concat([df_50call_res, df_50put_res], axis=1)
        #df_50res['x'] =df_50res.index
        '''
        300
        '''
        df_300 = self.df_op[self.df_op['name'].str.contains('300ETF购')]
        mindex = df_300['eprice'].drop_duplicates()
        eday = df_300['eday'].drop_duplicates()

        df_300call_res = pd.DataFrame(index=mindex, columns=eday)
        for date, row in df_300.T.iteritems():
            df_300call_res.loc[row['eprice'], row['eday']] = row['iv']
        df_300call_res['x'] = df_300call_res.index

        df_300_put = self.df_op[self.df_op['name'].str.contains('300ETF沽')]
        mindex = df_300_put['eprice'].drop_duplicates()
        eday = df_300_put['eday'].drop_duplicates()

        df_300put_res = pd.DataFrame(index=mindex, columns=eday)
        for date, row in df_300_put.T.iteritems():
            df_300put_res.loc[row['eprice'], row['eday']] = row['iv']
        df_300put_res['x'] = df_300put_res.index

        df_300res = pd.concat([df_300call_res, df_300put_res], axis=1)

        return df_50res, df_300res

    def iv_month_50300(self):

        if self.df_op.empty:
            return
        df_50 = self.df_op[self.df_op['name'].str.contains('50ETF')]
        df_50 = df_50[df_50['iv'] > 0.1]
        months = df_50['eday'].drop_duplicates()
        meanlist = []
        for month in months:
            iv_month = df_50[df_50['eday'] == month]
            meanlist.append(iv_month.mean(axis=0)['iv'])
        df_res50 = pd.DataFrame()
        df_res50['date'] = months
        df_res50['iv'] = meanlist
        df_res50.index = months

        df_300 = self.df_op[self.df_op['name'].str.contains('300ETF')]
        df_300 = df_300[df_300['iv'] > 0.1]
        months = df_300['eday'].drop_duplicates()
        meanlist = []
        for month in months:
            iv_month = df_300[df_300['eday'] == month]
            meanlist.append(iv_month.mean(axis=0)['iv'])
        df_res300 = pd.DataFrame()
        df_res300['date'] = months
        df_res300['iv'] = meanlist
        df_res300.index = months

        df_res = pd.concat([df_res50, df_res300], axis=1)
        #print(df_res)
        return df_res

    def loop(self):
        while True:
            self.update_alldf()
            #self.iv_month_50300()
            time.sleep(RATE)