Advertisement
Neki4ar

Untitled

Apr 14th, 2022
890
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from datetime import datetime, timedelta
  2.  
  3. import pandas as pd
  4. from pandas import DataFrame
  5. from ta.momentum import rsi, awesome_oscillator
  6. from tinkoff.invest import Client, RequestError, CandleInterval, HistoricCandle
  7. import matplotlib.pyplot as plt
  8. import matplotlib.dates as mdates
  9.  
  10. account_token = 't.P9y0_FG94o0Qj1esRJRdEP6iZG1I6q0yYQLWiEWdYPPk7O_NiLboZctkgUOghra1vSd4-ual9gEmbm9jTTD1gw'
  11. commission = 0.04/100
  12. begin_time = '2021-01-01 00:00:00+00:00'
  13.  
  14.  
  15. def AllCandles(figi_name, num_days):
  16.     df = DataFrame([{
  17.         'time': c.time,
  18.         'volume': c.volume,
  19.         'open': MoneyValueToFloat(c.open),
  20.         'close': MoneyValueToFloat(c.close),
  21.         'high': MoneyValueToFloat(c.high),
  22.         'low': MoneyValueToFloat(c.low),
  23.     } for c in client.get_all_candles(
  24.         figi=figi_name,
  25.         from_=datetime.utcnow() - timedelta(days=num_days),
  26.         to=datetime.utcnow(),
  27.         interval=CandleInterval.CANDLE_INTERVAL_5_MIN
  28.     )])
  29.     return df
  30.  
  31.  
  32. def MoneyValueToFloat(MonVal):
  33.     return MonVal.units + MonVal.nano * 1e-9
  34.  
  35.  
  36. def candleToDF(candles: [HistoricCandle]):
  37.     dfCandles: DataFrame = DataFrame([{
  38.         'time': c.time,
  39.         'volume': c.volume,
  40.         'open': MoneyValueToFloat(c.open),
  41.         'close': MoneyValueToFloat(c.close),
  42.         'high': MoneyValueToFloat(c.high),
  43.         'low': MoneyValueToFloat(c.low),
  44.     } for c in candles])
  45.     return dfCandles
  46.  
  47.  
  48. def RSI_OSCILATOR(df: DataFrame):
  49.     df['rsi'] = rsi(close=df['close'], window=14)
  50.     df.plot(x='time', y='rsi')
  51.     # plt.show()
  52.     return df
  53.  
  54.  
  55. def AO_OSCILATOR(df: DataFrame):
  56.     df['ao'] = awesome_oscillator(high=df['high'], low=df['low'], window1=5, window2=25)
  57.     fig, axs = plt.subplots(2, 1)
  58.     ax1 = df.plot(x='time', y='close', ax=axs[0])
  59.     ax2 = df.plot(x='time', y='ao', ax=axs[1])
  60.     axs[1].axhline(0, linestyle='--', alpha=0.5)
  61.     ax1.xaxis.set_major_locator(mdates.WeekdayLocator())
  62.     ax2.xaxis.set_major_locator(mdates.WeekdayLocator())
  63.     # for i in range(len(df) - 1):
  64.     #     if (df['ao'][i] < 0) and (df['ao'][i + 1] > 0):
  65.     #         a = df['time'][i]
  66.     #         b = df['open'][i]
  67.     #         c = df['close'][i]
  68.     #         print(a, b, c, 'buy')
  69.     #     if (df['ao'][i] > 0) and (df['ao'][i + 1] < 0):
  70.     #         a = df['time'][i]
  71.     #         b = df['open'][i]
  72.     #         c = df['close'][i]
  73.     #         print(a, b, c, 'sell')
  74.     # plt.show()
  75.     return df
  76.  
  77. def make_signal(DatFr):
  78.     rsi_low = 30.0
  79.     rsi_high = 70.0
  80.     avg_buy = 0.0
  81.     num_r = 0
  82.     num_a = 0
  83.     num = 0
  84.     balance = 10000.0
  85.     RSI = False
  86.     AO = False
  87.     to_sold = 0
  88.     print('start', balance)
  89.     for i in range(len(DatFr) - 1):
  90.         if (df['ao'][i] < 0) and (df['ao'][i + 1] > 0) and not (avg_buy > 0) and (balance - DatFr['close'][i+1] > 0) and str(DatFr['time'][i+1]) > begin_time:
  91.             RSI = True
  92.             if num_r == 0:
  93.                 num_r = 1
  94.         elif (df['ao'][i] < 0) and (df['ao'][i + 1] > 0)  and (balance - DatFr['close'][i+1] > 0) and (avg_buy > DatFr['close'][i+1]):
  95.             RSI = True
  96.             if num_r == 0:
  97.                 num_r = 1
  98.         elif (df['ao'][i] > 0) and (df['ao'][i + 1] < 0) and  0 < avg_buy < (1 + commission) * DatFr['close'][i+1]:
  99.             RSI = False
  100.             to_sold = 1
  101.             if to_sold == 1:
  102.                 to_sold = 2
  103.  
  104.         if not (rsi_high > DatFr['rsi'][i] > rsi_low) and (balance - DatFr['close'][i + 1] > 0) and str(
  105.             DatFr['time'][i + 1]) > begin_time:
  106.             if (DatFr['rsi'][i] < rsi_low) and (DatFr['rsi'][i + 1] >= rsi_low) and not (avg_buy > 0.0):
  107.                 AO = True
  108.                 if num_a == 0:
  109.                     num_a = 1
  110.             elif (DatFr['rsi'][i] < rsi_low) and (DatFr['rsi'][i + 1] >= rsi_low) and (DatFr['close'][i] < avg_buy) and (
  111.                     avg_buy > 0.0):
  112.                 AO = True
  113.                 if num_a == 0:
  114.                     num_a = 1
  115.             elif (DatFr['rsi'][i] > rsi_high) and (DatFr['rsi'][i + 1] <= rsi_high) and (
  116.                     DatFr['close'][i + 1] > (1 + 2.3 * commission) * avg_buy) and (avg_buy > 0.0):
  117.                 AO = False
  118.                 to_sold = 1
  119.                 if to_sold == 1:
  120.                     to_sold = 2
  121.  
  122.     if num_r > 0:
  123.         num_r = num_r + 1
  124.     if num_a > 0:
  125.         num_a = num_a + 1
  126.  
  127.     if num_r > 8:
  128.         num_r = 0
  129.         RSI = False
  130.     if num_a > 8:
  131.         num_a = 0
  132.         AO = False
  133.  
  134.     if RSI == True and AO == True:
  135.         if not (avg_buy > 0):
  136.             balance = balance - (1 + commission) * DatFr['close'][i + 1]
  137.             avg_buy = DatFr['close'][i + 1]
  138.             num = num + 1
  139.             print('bought', balance, DatFr['close'][i + 1])
  140.         else:
  141.             balance = balance - (1 + commission) * DatFr['close'][i + 1]
  142.             avg_buy = (num * avg_buy + DatFr['close'][i + 1]) / (num + 1)
  143.             num = num + 1
  144.             print('rebought', balance, DatFr['close'][i + 1])
  145.  
  146.     if to_sold == 2:
  147.         balance = balance + num * (1 - commission) * DatFr['close'][i + 1]
  148.         avg_buy = 0.0
  149.         num = 0
  150.         print('sold', balance, DatFr['close'][i + 1])
  151.  
  152.  
  153. def balance_ao(DatFr):
  154.     avg_buy = 0.0
  155.     num = 0
  156.     balance = 10000.0
  157.     print('start', balance)
  158.     for i in range(len(DatFr) - 1):
  159.         if (df['ao'][i] < 0) and (df['ao'][i + 1] > 0) and not (avg_buy > 0) and (balance - DatFr['close'][i+1] > 0) and str(DatFr['time'][i+1]) > begin_time:
  160.             balance = balance - (1 + commission) * DatFr['close'][i+1]
  161.             avg_buy = DatFr['close'][i+1]
  162.             num = num + 1
  163.             print('bought', balance, DatFr['close'][i+1])
  164.         elif (df['ao'][i] < 0) and (df['ao'][i + 1] > 0)  and (balance - DatFr['close'][i+1] > 0) and (avg_buy > DatFr['close'][i+1]):
  165.             balance = balance - (1 + commission) * DatFr['close'][i + 1]
  166.             avg_buy = (num * avg_buy + DatFr['close'][i + 1]) / (num + 1)
  167.             num = num + 1
  168.             print('rebought', balance, DatFr['close'][i + 1])
  169.         elif (df['ao'][i] > 0) and (df['ao'][i + 1] < 0) and  0 < avg_buy < (1 + commission) * DatFr['close'][i+1]:
  170.             balance = balance + num * (1 - commission) * DatFr['close'][i+1]
  171.             avg_buy = 0.0
  172.             num = 0
  173.             print('sold', balance, DatFr['close'][i+1])
  174.  
  175.  
  176.     print(balance, avg_buy)
  177.  
  178.  
  179. def balance_rsi(DatFr):
  180.     rsi_low = 30.0
  181.     rsi_high = 70.0
  182.     avg_buy = 0.0
  183.     num = 0
  184.     balance = 10000.0
  185.     print('start', balance)
  186.     for i in range(len(DatFr)-1):
  187.         if not(rsi_high > DatFr['rsi'][i] > rsi_low) and (balance - DatFr['close'][i+1] > 0) and str(DatFr['time'][i+1]) > begin_time:
  188.             # print(DatFr['time'][i+1])
  189.             if(DatFr['rsi'][i] < rsi_low) and (DatFr['rsi'][i+1] >= rsi_low) and not (avg_buy > 0.0):
  190.                 balance = balance - (1 + commission) * DatFr['close'][i+1]
  191.                 num = 1
  192.                 avg_buy = DatFr['close'][i+1]
  193.                 print('bought', balance, DatFr['close'][i+1])
  194.             elif (DatFr['rsi'][i] < rsi_low) and (DatFr['rsi'][i+1] >= rsi_low) and (DatFr['close'][i] < avg_buy) and (avg_buy > 0.0) :
  195.                 balance = balance - (1 + commission) * DatFr['close'][i+1]
  196.                 avg_buy = (num * avg_buy + DatFr['close'][i+1]) / (num + 1)
  197.                 num = num + 1
  198.                 print('rebought', balance, DatFr['close'][i+1])
  199.             elif (DatFr['rsi'][i] > rsi_high) and (DatFr['rsi'][i + 1] <= rsi_high) and (
  200.                     DatFr['close'][i + 1] > (1 + 2.3 * commission) * avg_buy) and (avg_buy > 0.0):
  201.                 balance = balance + num * (1 - commission) * DatFr['close'][i + 1]
  202.                 num = 0
  203.                 avg_buy = 0
  204.                 print('sold', balance, DatFr['close'][i + 1])
  205.             # elif (avg_buy > 0) and ((1 - DatFr['close'][i + 1] / avg_buy) * 100 > 8):
  206.             #     balance = balance - (1 + commission) * DatFr['close'][i + 1]
  207.             #     num = num + 1
  208.             #     avg_buy = (avg_buy + DatFr['close'][i + 1]) / 2
  209.             #     print('rerebought', balance, DatFr['close'][i])
  210.             # elif (avg_buy > 0) and ((1 - avg_buy/DatFr['close'][i + 1]) * 100 > 10):
  211.             #     balance = balance + num * (1 - commission) * DatFr['close'][i + 1]
  212.             #     num = 0
  213.             #     avg_buy = 0
  214.             #     print('resold', balance, DatFr['close'][i+1])
  215.     print(balance)
  216.  
  217.  
  218. if __name__ == '__main__':
  219.     yandex = 'BBG006L8G4H1'
  220.     gazprom = 'BBG004730RP0'
  221.     sgng = 'BBG0047315D0'
  222.     rosneft = 'BBG004731354'
  223.     pik = 'BBG004S68BH6'
  224.     with Client(account_token) as client:
  225.         df: DataFrame = AllCandles(pik, 90)
  226.         RSI_OSCILATOR(df)
  227.         AO_OSCILATOR(df)
  228.         # balance_rsi(df)
  229.         # print('rsi')
  230.         # balance_ao(df)
  231.         # print('ao')
  232.         make_signal(df)
  233.     # print(df)
  234.     #
  235.     # r = client.users.get_accounts()
  236.     # account_id = r.accounts[0].id
  237.     # r: PortfolioResponse = client.operations.get_portfolio(account_id=account_id)
  238.     # # keys = ['total_amount_bonds', 'total_amount_etf', 'total_amount_currencies']
  239.     #
  240.     # # print(pd.DataFrame([MoneyValueToFloat(getattr(r, k)) for k in keys], index=keys))
  241.     # # print(r)
  242.     #
  243.     # data = pd.DataFrame([{
  244.     #     'figi': p.figi,
  245.     #     # 'instrument_type': p.instrument_type,
  246.     #     'num': MoneyValueToFloat(p.quantity),
  247.     #     'expected_yield': MoneyValueToFloat(p.expected_yield),
  248.     #     'average_buy_price': MoneyValueToFloat(p.average_position_price_fifo),
  249.     #     'current_price': MoneyValueToFloat(p.current_price)
  250.     #     # 'currency': p.average_position_price.currency,
  251.     #     # 'nkd': MoneyValueToFloat(p.current_nkd)
  252.     #
  253.     # } for p in r.positions])
  254.     # print(data)
  255.  
Advertisement
RAW Paste Data Copied
Advertisement