])

            for date, c_cent_data in ce_data['dates'].items():
                p_cent_data = pe_data['dates'][date]
                responses.append([
                    date, c_cent_data['prem_close'], p_cent_data['prem_close'],
                    '', '', '', '', c_cent_data['prem_high'],
                    c_cent_data['prem_low'], c_cent_data['prem_open'], '',
                    p_cent_data['prem_high'], p_cent_data['prem_low'],
                    p_cent_data['prem_open']
                ])

            responses.append([
                ce_data['expiry_date'], ce_data['exit_premium'],
                pe_data['exit_premium'], '', '', '', '',
                ce_data['exit_premium_high'], ce_data['exit_premium_low'],
                ce_data['exit_premium_open'], '', pe_data['exit_premium_high'],
                pe_data['exit_premium_low'], pe_data['exit_premium_open']
            ])

            responses.append(['-', '-', '-'])
        except Exception:
            print(traceback.format_exc(), stock_id,
                  lastMonth.strftime("%b-%Y"))

responses.insert(0, [
    'DATE', 'CE', 'PE', '', '', '', '', 'CE(H)', 'CE(L)', 'CE(O/C)', '',
    'PE(H)', 'PE(L)', 'PE(O/C)'
])
gstats.print_statistics(responses, excel_location)
Ejemplo n.º 2
0
            #          current_far_months_range_upper_limit_for_buy, current_far_months_range_upper_limit_for_sell,
            #          spread, next_day_spread['spread'],
            #          spread / current_far_months_range_upper_limit_for_buy,
            #          (spread - next_day_spread['spread']) * option_lots[stock_id], margin,
            #          [0, 1][next_day_spread['spread'] <= current_far_months_range_upper_limit_for_sell],
            #          future_far_month_historical_data[k]['close'], future_current_month_historical_data[k]['close'],
            #          next_day_spread['near_far_fut_price'], next_day_spread['current_fut_price'],
            #          (future_current_month_historical_data[k]['expiry'] -
            #           future_current_month_historical_data[k]['date']).days])

            k += 1

    except Exception as e:
        print(traceback.format_exc())

# cs_responses.sort (key=lambda x: (-x[6]))

if len(cs_responses) > 0:
    cs_responses.insert(0, [
        'STOCK', 'BUY DATE', 'SELL DATE', 'UPPER RANGE(B)', 'UPPER RANGE(S)',
        'SPREAD(B)', 'SPREAD(S)', '%DIFF', 'EARNING', 'MARGIN', 'SUCCESS',
        'NEAR/FAR PREM(B)', 'CURRENT PREM(B)', 'NEAR/FAR PREM(S)',
        'CURRENT PREM(S)', 'EXP. DAYS'
    ])

    gstats.print_statistics(cs_responses, cspread_backtest_excel_location)
else:
    print('No results.')

print("---Script executed in %s seconds ---" % (time.time() - start_time))
Ejemplo n.º 3
0
        atm_ce_option = get_atm_option(options_ce)
        if atm_ce_option['strike'] == option_pe['strike']:
            pl = atm_ce_option['close'] + option_pe['close'] - atm_ce_option[
                'open'] - option_pe['open'] - min_breakeven
            bank_nifty_responses.append([
                option_pe['strike'], option_pe['spot'], atm_ce_option['open'],
                option_pe['open'], atm_ce_option['close'], option_pe['close'],
                pl, pl * lot, [0,
                               1][pl > 0], option_pe['date'], option_pe['date']
            ])

            bank_nifty_responses_len = len(bank_nifty_responses)
            if bank_nifty_responses_len > 400:
                break
            if bank_nifty_responses_len % 100 == 0:
                print(bank_nifty_responses_len)
    # else:
    #     print('No CE option for date: %s' %(option_pe['date']))

if len(bank_nifty_responses) > 0:
    bank_nifty_responses.sort(key=lambda x: (-x[6]))
    bank_nifty_responses.insert(0, [
        'STRIKE', 'SPOT', 'CALL LTP(B)', 'PUT LTP(B)', 'CALL LTP(S)',
        'PUT LTP(S)', 'P/L', 'EARNING', 'SUCC', 'BUY DATE', 'SELL DATE'
    ])
    gstats.print_statistics(bank_nifty_responses, banknifty_excel_location)
else:
    print('No results.')

print("---Script executed in %s seconds ---" % (time.time() - start_time))
Ejemplo n.º 4
0
for result_stock in result_stocks:
    if result_stock[1] in zerodha_MIS_stocks:
        tradable_stock = [result_stock[1], zerodha_MIS_stocks[result_stock[1]]]
        if result_stock[1] in fo_stock_ids:
            tradable_stock.append(sUtils.NSE_FO)
        else:
            tradable_stock.append(None)

        tradable_stock.extend([result_stock[2], result_stock[3]])

        tradable_stocks.append(tradable_stock)

        nse_result_stats = get_nse_result_stats(tradable_stock[0])
        if nse_result_stats is not None:
            tradable_stock.extend(nse_result_stats)
            if len(nse_result_stats) > 4:
                tradable_stock.append(
                    abs(nse_result_stats[0]) + abs(nse_result_stats[1]) +
                    abs(nse_result_stats[2]) + abs(nse_result_stats[3]))
            else:
                tradable_stock.append(None)
        else:
            tradable_stock.extend([None, None, None, None, None])

if len(tradable_stocks) > 0:
    tradable_stocks.insert(0, [
        'STOCK', 'LEVER.', 'FO', 'DECLARATION TIME', 'DECLARATION', 'REV. QOQ',
        'REV. YOY', 'PROFIT QOQ', 'PROFIT YOY', 'TOTAL CHANGE'
    ])
gstats.print_statistics(tradable_stocks, results_excel_location)
                            no_of_failed_cases += 1

                        break

                rsi_more_than_80_responses.append([
                    stock_latest_info[nse_bse.STOCK_ID], 'RSI>80',
                    util.get_date_from_timestamp(
                        stock_latest_data[i + 1]['timestamp']),
                    util.get_date_from_timestamp(
                        stock_latest_data[j]['timestamp']),
                    stock_latest_data[i + 1]['open'],
                    stock_latest_data[j]['close'],
                    ((stock_latest_data[i + 1]['open'] -
                      stock_latest_data[j]['close']) * 100) /
                    stock_latest_data[i + 1]['open'],
                    stock_latest_data[i]['volume']
                ])

            i = pivot + i

    except Exception as e:
        print(traceback.format_exc())

print("Successful RSI>80 cases: %s" %
      ((no_of_successful_cases * 100) /
       (no_of_successful_cases + no_of_failed_cases)))

gstats.print_statistics(rsi_more_than_80_responses, rsi80_excel_location)

print("---Script executed in %s seconds ---" % (time.time() - start_time))
Ejemplo n.º 6
0
                                            stock_volatility)
        else:
            print('None options', itm_option, otm_option)

        itm_option, otm_option, strategy_name, net_credit, net_debit = o_strat.get_bull_call_spreads(stock_options)
        if itm_option is not None and otm_option is not None:
            append_to_otm_strategy_response(stock_id, itm_option, otm_option, strategy_name.name, net_credit, net_debit,
                                            stock_volatility)
        else:
            print('None options', itm_option, otm_option)

        itm_option, otm_option, strategy_name, net_credit, net_debit = o_strat.get_bull_put_spreads(stock_options)
        if itm_option is not None and otm_option is not None:
            append_to_otm_strategy_response(stock_id, itm_option, otm_option, strategy_name.name, net_credit, net_debit,
                                            stock_volatility)
        else:
            print('None options', itm_option, otm_option)

    except Exception as e:
        print(traceback.format_exc())

if len(otm_strategy_responses) > 0:
    otm_strategy_responses.insert(0,
                                  ['STOCK', 'STRATEGY', 'ITM(STRIKE)', 'OTM(STRIKE)', 'ITM(LTP)', 'OTM(LTP)', 'SPOT',
                                   'NET CREDIT', 'NET DEBIT', 'STOCK VOLA', 'IV(ITM)', 'IV(OTM)', 'IV high',
                                   'PHYSIC. SETT.', 'LOTS'])
    gstats.print_statistics(otm_strategy_responses, otm_excel_location)
else:
    print('No results')
print("---Script executed in %s seconds ---" % (time.time() - start_time))
                stock_option.ltp, stock_option.ltp * option_lots[stock_id],
                required_margins[stock_id], stock_option.liquidity, max_pain,
                pcr,
                outil.is_call(stock_option.symbol),
                stock_option.strike_price > max_pain,
                option_implied_volatility > (stock_volatility * 100),
                pcr < outil.lower_pcr_value_for_shorting,
                ((stock_option.strike_price + stock_option.ltp -
                  stock_option.spot_price) / stock_option.spot_price),
                resistance, stock_option.strike_price > resistance,
                outil.is_stock_physically_settled(stock_id),
                option_lots[stock_id]
            ])

    except Exception as e:
        print(traceback.format_exc())

otm_contract_responses.sort(key=lambda x: (-x[16]))

if len(otm_contract_responses) > 0:
    otm_contract_responses.insert(0, [
        'OPTION', 'STRIKE', 'SPOT', '1 SD', 'STOCK VOLA', 'IV', 'PREM',
        'EARNING', 'MARGIN', 'LIQUID', 'MAX_PAIN', 'PCR', 'CALL', '> PAIN',
        'IV high', 'GOOD PCR', 'DEVI', 'RESIS', '>RESIS', 'PHYSIC. SETT.',
        'LOTS'
    ])
    gstats.print_statistics(otm_contract_responses, otm_excel_location)
else:
    print('No results')
print("---Script executed in %s seconds ---" % (time.time() - start_time))
Ejemplo n.º 8
0
                    scalper_responses.append(scalper_response)

        time.sleep(.5)

    except Exception as e:
        print(traceback.format_exc())

for scalper_response in scalper_responses:
    key_high = str(scalper_response[1]) + 'high'
    key_low = str(scalper_response[1]) + 'low'
    if (key_high in price_changes and scalper_response[0]
            == price_changes[key_high][nse_bse.STOCK_ID]) or (
                key_low in price_changes and scalper_response[0]
                == price_changes[key_low][nse_bse.STOCK_ID]):
        scalper_response.append(1)
    else:
        scalper_response.append(0)

if len(scalper_responses) > 0:
    scalper_responses.insert(0, [
        'STOCK', 'BUY DATE', 'BUY PRICE', 'TARGET', 'STOPLOSS', 'LONG/SHORT',
        'SELL PRICE', 'EARNING', 'SUCC', 'HIGHEST/LOWEST'
    ])
    gstats.print_statistics(scalper_responses,
                            scalper_responses_excel_location)
else:
    print('No results.')

print("---Script executed in %s seconds ---" % (time.time() - start_time))
Ejemplo n.º 9
0
        stock_datas = util.get_equity_historical_data(stock_id)[-max_duration_to_consider:]
        min_daily_order_size_criteria_failed = False

        total_order_size = 0
        for stock_data in stock_datas:
            order_size = stock_data['close'] * stock_data['volume']

            if order_size < min_daily_order_size:
                print('Min daily order size criteria failed for stock:' + stock_id)
                min_daily_order_size_criteria_failed = True
                break

            total_order_size += order_size

        if min_daily_order_size_criteria_failed:
            continue

        stock_market_cap[stock_id] = total_order_size / max_duration_to_consider

    except Exception as e:
        print(str(traceback.format_exc()) + '\nError in stock:' + stock_id)

stock_market_cap = {k: v for k, v in sorted(stock_market_cap.items(), key=lambda item: item[1], reverse= True)}

res_to_print = [['STOCK', 'MARKET CAP', 'FO']]
for stock_id, market_cap in stock_market_cap.items():
    res_to_print.append([stock_id, market_cap, stock_id in nse_fo_stocks])

gstats.print_statistics(res_to_print, excel_location)
Ejemplo n.º 10
0
                half_future_lot, max_move, max_volat
            ]

    ascent_stocks = [
        (k[0], ascent_stocks[k[0]])
        for k in sorted(ascent_stocks.items(), key=lambda x: x[1][2])
    ]
    descent_stocks = [
        (k[0], descent_stocks[k[0]])
        for k in sorted(descent_stocks.items(), key=lambda x: x[1][2])
    ]

    if len(descent_stocks) > 0:
        updowngap_responses.append(descent_stocks[int(len(descent_stocks) /
                                                      2)][1])
    else:
        print('No descent stocks on %s' % (str(s_date)))

    if len(ascent_stocks) > 0:
        updowngap_responses.append(ascent_stocks[int(len(ascent_stocks) /
                                                     2)][1])
    else:
        print('No ascent stocks on %s' % (str(s_date)))

updowngap_responses = sorted(updowngap_responses,
                             key=lambda x: x[0],
                             reverse=True)
gstats.print_statistics(updowngap_responses, excel_location)

print("---Script executed in %s seconds ---" % (time.time() - start_time))
Ejemplo n.º 11
0
                int(500000 / open_price), None, None, None, profit_loss,
                parent_order['tag']
            ])

positions = kite.positions()

for formed_order in formed_orders:
    position_exist = False
    for position in positions['day']:
        if formed_order['symbol'].upper() == position['tradingsymbol'].upper():
            position_exist = True
    if position_exist is False:
        max_high_price = stocks_live_data[formed_order['nse_symbol']]['ohlc'][
            'open'] - formed_order['trigger_price_pts'] + (
                abs(max_loss_to_bear) /
                (min_lot_percent_of_future_lot * formed_order['future_lot']))
        min_low_price = stocks_live_data[formed_order['nse_symbol']]['ohlc'][
            'open'] + formed_order['trigger_price_pts'] - (
                abs(max_loss_to_bear) /
                (min_lot_percent_of_future_lot * formed_order['future_lot']))
        trades.append([
            today_date, formed_order['symbol'].upper(), 'NA', 0, 0, 0,
            formed_order['future_lot'], formed_order['trigger_price_pts'],
            max_high_price, min_low_price, 0
        ])

gstats.print_statistics(trades, trades_excel_location)

# detailed_orders.sort(key = lambda x: x[3])
gstats.print_statistics(detailed_orders, detailed_orders_excel_location)
Ejemplo n.º 12
0
low_vol_tradable_co_bo_stocks = []
for tradable_co_bo_stock in tradable_co_bo_stocks:
    try:
        stock_datas = util.get_equity_historical_data(tradable_co_bo_stock)
        stock_datas = stock_datas[-max_data_len:]
    except Exception as e:
        print('Stock:%s data not found:' % (tradable_co_bo_stock))
        continue
    total_trade = 0
    for stock_data in stock_datas:
        total_trade += (stock_data['close'] * stock_data['volume'])
    aver_trade = total_trade / len(stock_datas)
    if aver_trade >= (min_aver_trade / 2):
        high_vol_tradable_co_bo_stocks.append(
            [tradable_co_bo_stock, aver_trade])
    else:
        low_vol_tradable_co_bo_stocks.append(
            [tradable_co_bo_stock, aver_trade])

print('HIGH VOL TR CO BO stocks:%d' % (len(high_vol_tradable_co_bo_stocks)))

low_vol_responses = [['STOCK', 'TRADE AMNT.']]
for low_vol_tradable_co_bo_stock in low_vol_tradable_co_bo_stocks:
    low_vol_responses.append(low_vol_tradable_co_bo_stock)
gstats.print_statistics(low_vol_responses, low_vol_excel_location)

responses = [['STOCK', 'TRADE AMNT.']]
for high_vol_tradable_co_bo_stock in high_vol_tradable_co_bo_stocks:
    responses.append(high_vol_tradable_co_bo_stock)

gstats.print_statistics(responses, excel_location)
            stock_option.ltp = max(x['price'] for x in stock_option.bids)
            high_volat_contract_responses.append([
                stock_option.symbol, stock_option.strike_price,
                stock_option.spot_price, stock_volatility * 100,
                stock_option.implied_volatility, stock_option.ltp,
                stock_option.ltp * option_lots[stock_id],
                stock_option.liquidity, max_pain, pcr,
                outil.is_call(stock_option.symbol),
                stock_option.strike_price > max_pain,
                pcr < outil.lower_pcr_value_for_shorting,
                required_margins[stock_id], option_lots[stock_id],
                stock_option.implied_volatility > (stock_volatility * 100)
            ])

    except Exception as e:
        print(traceback.format_exc())

high_volat_contract_responses.sort(key=lambda x: (-((x[1] + x[5]) / x[2])))

if len(high_volat_contract_responses) > 0:
    high_volat_contract_responses.insert(0, [
        'OPTION', 'STRIKE', 'SPOT', 'STOCK VOLA', 'IV', 'PREM', 'EARNING',
        'LIQUID', 'MAX_PAIN', 'PCR', 'CALL', '> PAIN', 'GOOD PCR', 'MARGIN',
        'LOT', 'HIGH. VOLA.'
    ])
    gstats.print_statistics(high_volat_contract_responses,
                            high_volat_options_excel_location)
else:
    print('No results.')
print("---Script executed in %s seconds ---" % (time.time() - start_time))
Ejemplo n.º 14
0
                                    'date'] or atm_option_pe['date'] != future[
                                        'date']:
                                print('Dates mismatch:', atm_option_ce['date'],
                                      atm_option_pe['date'], future['date'])

                            pcr_responses.append([
                                stock_id, atm_option_pe['strike'],
                                atm_option_ce['ltp'], atm_option_pe['ltp'],
                                future['ltp'], atm_option_ce['spot'], earning,
                                future['date'], future['expiry']
                            ])

                else:
                    print('No options:', future['date'], stock_id)

            pivot += 1
    except Exception as e:
        print(str(traceback.format_exc()) + '\nError in stock:' + stock_id)

if len(pcr_responses) > 0:
    pcr_responses.sort(key=lambda x: (-x[6]))
    pcr_responses.insert(0, [
        'STOCK ID', 'STRIKE', 'CALL LTP', 'PUT LTP', 'FUT LTP', 'STOCK LTP',
        'EARNING', 'BUY DATE', 'SELL DATE'
    ])
    gstats.print_statistics(pcr_responses, pcp_excel_location)
else:
    print('No results.')

print("---Script executed in %s seconds ---" % (time.time() - start_time))
Ejemplo n.º 15
0
                                # outil.sell_future (upstox_api, cs_response[1], nse_bse.NSE_FO, ltp2,
                                #                    option_lots[stock_id])
                                # outil.buy_future (upstox_api, cs_response[0], nse_bse.NSE_FO, ltp1, option_lots[stock_id])
                                print('Executed:', cs_response)
                                print('B,A.L:', bids, asks, ltp1)
                                break

                        else:
                            print('Illiquid future 3:', bids, asks, stock_id)
                    else:
                        print('Too high ltp for future 3:', bids, stock_id,
                              ltp2)
            else:
                print('Illiquid future 1:', bids, asks, stock_id)
        else:
            print('Too low ltp for future 1:', asks, stock_id, ltp1)

    except Exception as e:
        print(traceback.format_exc() + ' in Stock:' + stock_id)

if len(cs_responses) > 0:
    cs_responses.insert(0, [
        'CURRENT FUT', 'NEAR/FAR FUT', 'CURRENT PREM', 'NEAR/FAR PREM',
        'UPPER RANGE(B)', 'UPPER RANGE(S)', 'SPREAD', '%DIFF', 'EARNING',
        'MARGIN', 'LOTS'
    ])
    gstats.print_statistics(cs_responses, otm_excel_location)
else:
    print('No results.')
print("---Script executed in %s seconds ---" % (time.time() - start_time))
Ejemplo n.º 16
0
                        'sell_price': stock_latest_data[j]['close'],
                    'action': action.name, 'sell_day': stock_latest_data[j]['timestamp'],
                        'stock_data': stock_latest_data[i], 'trend': trend.name,
                        'long_candle_length': long_candle_length}

            i += 1

    except Exception as e:
        print (traceback.format_exc ())

for key, highest_vol_daily in highest_vols_daily.items():

    highest_vol_daily_responses.append (
        [highest_vol_daily[nse_bse.STOCK_ID], highest_vol_daily['stock_data']['volume'], highest_vol_daily['av_vol'],
         highest_vol_daily['vol_rise'], util.get_date_from_timestamp (highest_vol_daily['stock_data']['timestamp']),
         util.get_date_from_timestamp(highest_vol_daily['sell_day']), highest_vol_daily['buy_price'],
         highest_vol_daily['sell_price'],
         highest_vol_daily['target'], highest_vol_daily['stop_loss'], highest_vol_daily['action'],
         highest_vol_daily['trend'], highest_vol_daily['long_candle_length'], highest_vol_daily['trade_success']])

highest_vol_daily_responses.sort(key=lambda x: -x[3])

highest_vol_daily_responses.insert(0,
                                   ['STOCK', 'VOL', 'AV. VOL', 'VOL RISE', 'VOL DAY', 'SELL DAY', 'BUY PRICE',
                                    'SELL PRICE', 'TARGET',
                                    'SL', 'ACTION', 'TREND', 'CANDLE LEN', 'SUCCESS'])

gstats.print_statistics (highest_vol_daily_responses, high_volume_back_test_excel_location)

print ("---Script executed in %s seconds ---" % (time.time () - start_time))