[Investment] Practical Calculation of Straddle Options

There are a lot of options trading pairs. In actual trading, it is difficult to calculate the profit and loss of each option quickly with only the naked eye and brain. In most ordinary people's situation, the price fluctuates as soon as one of them is calculated, forming a It is necessary to use a computer to complete this work, let alone calculate all the contents.

This article will briefly explain how to calculate straddle options, and draw a chart for visual observation.

Insert image description here

The content of obtaining data and calculating basic options has been written before , you can refer back to it.

Calculating a straddle is also very simple. A long straddle is the sum of two call options, and a short straddle is the sum of two put options.

So next you need to write a loop to calculate all available options, and draw a graph to intuitively feel it.

cycle

Since the x-axis we need for each cycle is the expiration date price, the premium and exercise price are fixed, and since the option division of each expiration date contract is distinguished based on the exercise price, we Cycle through each exercise price, that is: for s in df['行权价'], set df['当期行权价']=s.

Then calculate the straddle option based on the normal calculation of the basic option value: df2['买入跨式']=df2['买入看涨']+df['买入看跌'], and sell the straddle in the same way.

Just put the generated graph where you want to put it in each loop.

Draw a picture

You can draw multiple sub-pictures on a large picture, or you can make a chart similar to tabs and timelines. The ultimate goal is visualization.

Let’s take the timeline as an example:

tl = Timeline()
tl.add_schema()
for s in df['行权价']:
    fig = (Line()
        .add_xaxis()
        .add_yaxis())
    tl.add(fig, s)
tl.render()

This is generally such a framework. Whether it is calculating straddle options or spread combinations, the logic is the same. How to judge the opening conditions is up to your own thinking.

The entire code is as follows:

import pandas as pd
import numpy as np
import ccxt
from pyecharts.charts import *
from pyecharts import options as opts


df = pd.DataFrame()
exchange = ccxt.okex()  # 建立交易所
df = pd.read_csv(r'C:\Users\xxx\Python\options\options.csv')
params = {
    
    'instrument_id': 'EOS-USD'}  # 参数
price = float(pd.DataFrame(exchange.indexGetInstrumentIdConstituents(params=params)).loc['last', 'data'])  # 获取现价
df['price'] = np.sort(np.append(np.linspace(price-0.5, price+0.5, 18), np.linspace(price-0.5, price+0.5, 18)))
# 画图,新建一个timeline对象
tl = Timeline()
tl.add_schema()
straddle_sell = {
    
    }
straddle_buy = {
    
    }

for s in df['strike']:
    df['strike_using'] = s  # 设定该循环的行权价
    # 计算数据
    Call = df.groupby('type').get_group('C')
    Put = df.groupby('type').get_group('P')
    # 设置参数
    strike = df.loc[df['strike'] == s]  # 行权价暂定值
    Call['best_bid'] = strike.loc[strike['type'] == 'C', 'best_bid']
    Call['best_ask'] = strike.loc[strike['type'] == 'C', 'best_ask']
    Put['best_bid'] = strike.loc[strike['type'] == 'P', 'best_bid']
    Put['best_ask'] = strike.loc[strike['type'] == 'P', 'best_ask']
    Call = Call.fillna(method='ffill')  # 填充权利金
    Call = Call.fillna(method='bfill')
    Put = Put.fillna(method='ffill')
    Put = Put.fillna(method='bfill')
    # 买入看涨
    Call['call_buy'] = -(Call['strike_using'] - Call['price']) * 100 - Call['best_ask'] * 100
    Call.loc[Call['price'] < Call['strike_using'], 'call_buy'] = - Call['best_ask'] * 100
    # 买入看跌
    Put['put_buy'] = (Put['strike_using'] - Put['price']) * 100 - Put['best_ask'] * 100
    Put.loc[Put['price'] > Put['strike_using'], 'put_buy'] = - Put['best_ask'] * 100
    # 卖出看涨
    Call['call_sell'] = (Call['strike_using'] - Call['price']) * 100 + Call['best_bid'] * 100
    Call.loc[Call['price'] < Call['strike_using'], 'call_sell'] = Call['best_bid'] * 100
    # 卖出看跌
    Put['put_sell'] = -(Put['strike_using'] - Put['price']) * 100 + Put['best_bid'] * 100
    Put.loc[Put['price'] > Put['strike_using'], 'put_sell'] = Put['best_bid'] * 100
    # 再次整理
    df2 = Call[['best_bid', 'best_ask', 'type', 'strike_using', 'price', 'call_buy', 'call_sell']]
    df2['put_buy'] = Put['put_buy'].tolist()
    df2['put_sell'] = Put['put_sell'].tolist()
    # 跨式
    df2['straddle_sell'] = df2['call_sell'] + df2['put_sell']
    df2['straddle_buy'] = df2['call_buy'] + df2['put_buy']
    # 画图
    fig_all = (Line(init_opts=opts.InitOpts(width='1200px', height='700px', page_title='Javan'))
               .add_xaxis(df2['price'])
               .add_yaxis('买入跨式', df2['straddle_buy'], linestyle_opts=opts.LineStyleOpts(width=2))
               .add_yaxis('卖出跨式', df2['straddle_sell'], linestyle_opts=opts.LineStyleOpts(width=2))
               .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
               .set_global_opts(tooltip_opts=opts.TooltipOpts(is_show=True,
                                                              formatter='{b}{c}'),
                                yaxis_opts=opts.AxisOpts(name='profit'),
                                xaxis_opts=opts.AxisOpts(name='到期日价格', min_='dataMin')
                                ))
    tl.add(fig_all, s)
    straddle_buy[str(s)] = df2['straddle_buy'].min()
    straddle_sell[str(s)] = df2['straddle_sell'].max()
    # 储存
    df2.to_csv(r'C:\\Users\\xxx\\Python\\options\\cal\\' + 'options' + str(s) + '.csv')

tl.render(r'C:\\Users\\xxx\\Python\\options\\cal\\all.html')
print(pd.DataFrame(straddle_sell.items(), columns=['行权价', '最大收益']))
print(pd.DataFrame(straddle_buy.items(), columns=['行权价', '最小收益']))
exit()

Guess you like

Origin blog.csdn.net/food_for_thought/article/details/108358540