Advertisement
Guest User

Untitled

a guest
Feb 5th, 2017
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.77 KB | None | 0 0
  1. # Jan 2017
  2.  
  3. # submit script bunny tithing obligations below:
  4. # (BTC) 1Hu7mVg4GudEcnRLN94oWC9Umh4JohNp3F
  5.  
  6. # custom bots, any technical indication rpfpresence@gmail.com
  7.  
  8. # dependencies: python 2.7, matplotlib 1.3.1, python-tk
  9.  
  10. import matplotlib.pyplot as plt
  11. import numpy as np
  12. import urllib2
  13. import json
  14. import math
  15. import time
  16.  
  17. VERSION = 'POLO EXTINCTION EVENT v1.0 by litepresence'
  18.  
  19. # PAIR
  20. CURRENCY = 'BTC'
  21. ASSET = 'FLDC'
  22.  
  23. # ALPHA CROSS (DAYS)
  24. MA1 = 16.66
  25. MA2 = 50.00
  26.  
  27. # STATE MACHINE THRESHOLDS
  28. SELLOFF = 1.5
  29. DESPAIR = 0.75
  30. CROSS = 1.02
  31.  
  32. # BACKTEST RESOLUTION
  33. CANDLE = 14400
  34. DAYS = 650
  35. END = 9999999999 #9999999999 is to current; else unix
  36.  
  37. # STARTING PORTFOLIO
  38. portfolio = {}
  39. portfolio['assets'] = 0
  40. portfolio['currency'] = 1
  41.  
  42. # INITIALIZED STORAGE VALUES
  43. storage = {}
  44. storage['trades'] = 0
  45.  
  46. # INFO OBJECTS
  47. info = {}
  48. info['begin'] = int(time.time())-DAYS*86400
  49. info['tick'] = 0
  50. info['interval'] = CANDLE
  51. info['current_time'] = info['begin']
  52. info['end']=info['begin']+DAYS*86400
  53.  
  54. # BACKTEST CONSTANTS
  55. DEPTH = int(max(MA1,MA2)*(86400/CANDLE)+50)
  56. START = info['begin']-(CANDLE*DEPTH)
  57. SATOSHI = 0.00000001
  58. ANTISAT = 100000000.0
  59.  
  60. def initialize():
  61.  
  62.     print(VERSION)
  63.     print('~===BEGIN BACKTEST=======================~')
  64.     if info['interval']  not in [300, 900, 1800, 7200, 14400, 86400]:
  65.         print ('Tick Interval must be in [300, 900, 1800, 7200, 14400, 86400]')
  66.         raise stop()
  67.  
  68. def test_sell(price):
  69.  
  70.         now = time.ctime(info['current_time'])
  71.         portfolio['currency'] = portfolio['assets']*price
  72.         print ('[%s] %s SELL %.2f %s at %s sat value %.2f %s' % (now,
  73.             storage['trades'], portfolio['assets'], ASSET, int(price)/SATOSHI,
  74.             portfolio['currency'], CURRENCY))
  75.         portfolio['assets'] = 0
  76.         plt.plot(info['current_time'],math.log(price),markersize=8,
  77.             marker='o',color='coral',label='sell')
  78.  
  79. def test_buy(price):
  80.  
  81.         now = time.ctime(info['current_time'])
  82.         portfolio['assets'] = portfolio['currency']/(price)
  83.         print ('[%s] %s BUY %.2f %s at %s sat value %.2f %s' % (now,
  84.             storage['trades'], portfolio['assets'], ASSET, int(price)/SATOSHI,
  85.             portfolio['currency'], CURRENCY))
  86.         portfolio['currency'] = 0
  87.         plt.plot(info['current_time'],math.log(price),markersize=8,
  88.             marker='o',color='lime',label='buy')
  89.    
  90. def fetch_polo():
  91.    
  92.     candles={}
  93.     asset = ASSET
  94.     polo = asset + '_polo'
  95.     candles[polo] = {}
  96.     url = ('https://poloniex.com/public?command=returnChartData' +
  97.         '&currencyPair=%s_%s&start=%s&end=%s&period=%s' %
  98.         (CURRENCY,asset,START,END,CANDLE))
  99.     ret = urllib2.urlopen(urllib2.Request(url))
  100.     try: candles[polo] = json.loads(ret.read())
  101.     except: pass
  102.     print('*********%s%s*********'% (asset,CURRENCY))
  103.     print('DEPTH......: %s' % len(candles[polo]))
  104.     print('CANDLE.....: %s' % CANDLE)
  105.     print('START DATE.: %s' % time.ctime(info['begin']))
  106.     print('END DATE...: %s' % time.ctime(info['end']))
  107.     print('1st CANDLE.: %s' % str(candles[polo][-(DAYS*86500/CANDLE)])[:200])
  108.     print('LAST CANDLE: %s' % str(candles[polo][-1])[:200])
  109.     storage[polo]={}
  110.     storage[polo]['date']=[]
  111.     storage[polo]['close'] = []
  112.     storage[polo]['high'] = []
  113.     storage[polo]['low'] = []
  114.     for i in range(len(candles[polo])):
  115.         storage[polo]['date'].append(candles[polo][i]['date'])
  116.         storage[polo]['close'].append(candles[polo][i]['close'])
  117.         storage[polo]['high'].append(candles[polo][i]['high'])
  118.         storage[polo]['low'].append(candles[polo][i]['low'])    
  119.  
  120. def build_polo_candles():
  121.  
  122.     # allow (for asset in ASSET:) for multiple pairs
  123.     asset = ASSET
  124.     polo = asset + '_polo'
  125.     polo_close = asset + '_polo_close'
  126.     polo_high = asset + '_polo_high'
  127.     polo_low = asset + '_polo_low'
  128.     for i in range(len(storage[polo]['date'])):
  129.         if (info['current_time'] <=
  130.             storage[polo]['date'][i] <
  131.             (info['current_time']+info['interval'])):
  132.             storage[polo_close] = []
  133.             storage[polo_high] = []
  134.             storage[polo_low] = []            
  135.             for j in range(DEPTH):
  136.                 try:
  137.                     storage[polo_close].append(storage[polo]['close'][i-j])
  138.                     storage[polo_high].append(storage[polo]['high'][i-j])
  139.                     storage[polo_low].append(storage[polo]['low'][i-j])
  140.                 except: pass
  141.             storage[polo_close] = storage[polo_close][::-1]
  142.             storage[polo_high] = storage[polo_high][::-1]
  143.             storage[polo_low] = storage[polo_low][::-1]
  144.     storage['close'] = np.array(storage[polo_close])
  145.     storage['high'] = np.array(storage[polo_high])
  146.     storage['low'] = np.array(storage[polo_low])
  147.  
  148. def simple_mean():
  149.  
  150.     # CALCULATE SIMPLE MOVING AVERAGES
  151.     close = storage['close']
  152.     ma1_interval = int(MA1*86400/info['interval'])
  153.     ma2_interval = int(MA2*86400/info['interval'])
  154.     storage['ma1'] = np.sum(close[-ma1_interval:]) / len(close[-ma1_interval:])
  155.     storage['ma2'] = np.sum(close[-ma2_interval:]) / len(close[-ma2_interval:])
  156.  
  157.  
  158. def holdings():
  159.  
  160.     # STORE STARTING PORTFOLIO
  161.     close = storage['close']
  162.     if info['tick']==0:
  163.         storage['begin_max_assets']=(
  164.             portfolio['currency']/(close[-1])+portfolio['assets'])
  165.         storage['begin_max_currency']=(
  166.             portfolio['currency']+portfolio['assets']*(close[-1]))
  167.         storage['start_price'] = close[-1]
  168.            
  169. def tick():
  170.    
  171.     build_polo_candles()
  172.     holdings()
  173.     simple_mean()
  174.     state_machine()
  175.     chart()
  176.  
  177. def state_machine():
  178.  
  179.     # SAMPLE MOVING AVERAGE CROSSOVER STRATEGY
  180.     # YOUR STRATEGY GOES HERE:
  181.  
  182.     # LOCALIZE DATA
  183.     ma1 = storage['ma1']
  184.     ma2 = storage['ma2']
  185.     close = storage['close']
  186.     high = storage['high']
  187.     low = storage['low']
  188.  
  189.     # ALPHA SIGNAL
  190.     market_cross = False
  191.     if 1.03*ma1>ma2:
  192.         market_cross = True
  193.  
  194.     # STATE MACHINE - BULL MARKET
  195.     mode = 0
  196.     if market_cross:
  197.         mode = 10
  198.         if portfolio['currency'] > 0:
  199.             if storage['close'][-1]<ma1:
  200.                 test_buy(price=storage['close'][-1])
  201.                 storage['trades']+=1
  202.            
  203.     # STATE MACHINE - BEAR MARKET
  204.     else:
  205.         mode = -10
  206.         if portfolio['assets'] > 0:
  207.             if storage['close'][-1]>ma1:
  208.                 test_sell(price=storage['close'][-1])      
  209.                 storage['trades']+=1
  210.                
  211.     storage['mode']=mode
  212.  
  213.  
  214. def chart():
  215.  
  216.     # LOCALIZE DATA
  217.     now = info['current_time']      
  218.     ma1 = storage['ma1']
  219.     ma2 = storage['ma2']
  220.     close = storage['close']
  221.     high = storage['high']
  222.     low = storage['low']
  223.     mode = storage['mode']
  224.  
  225.     # PLOT OBJECTS
  226.     plt.plot(now,math.log(ma1),markersize=1,marker='.',
  227.         color='white',label='ma1')
  228.     plt.plot(now,math.log(ma2),markersize=2,marker='.',
  229.         color='white',label='ma2')
  230.     plt.plot(now,math.log(close[-1]),markersize=1,marker='.',
  231.         color='aqua',label='close')
  232.     plt.plot(now,math.log(high[-1]),markersize=1,marker='.',
  233.         color='MediumSpringGreen',label='high')
  234.     plt.plot(now,math.log(low[-1]),markersize=1,marker='.',
  235.         color='darkmagenta',label='low')
  236.  
  237.  
  238. def plot():
  239.  
  240.     # PLOT FORMAT
  241.     try:
  242.         ax = plt.gca()
  243.         ax.set_axis_bgcolor('0.1')
  244.         ax.yaxis.tick_right()
  245.         ax.set_xlim(info['begin'], info['end'])
  246.         ax.get_xaxis().get_major_formatter().set_useOffset(False)
  247.         ax.get_xaxis().get_major_formatter().set_scientific(False)
  248.         ax.ticklabel_format(useOffset=False, style='plain')
  249.         ax.grid(True)
  250.         plt.autoscale(enable=True, axis='y')
  251.         #plt.autoscale(enable=True, axis='x')
  252.         plt.gcf().autofmt_xdate(rotation=90)
  253.         plt.title(VERSION+'PAIR: %s_%s' %
  254.             (ASSET, CURRENCY))
  255.         plt.tight_layout()
  256.  
  257.     except:
  258.         print('plot format failed')
  259.         pass
  260.     # SHOW PLOT
  261.     try:  
  262.         plt.show()
  263.         plt.pause(0.1)
  264.     except:
  265.         print('plot show failed')
  266.  
  267. def stop():
  268.  
  269.     # MOVE TO CURRENCY
  270.     if portfolio['assets'] > 0:
  271.         print('stop() EXIT TO CURRENCY')
  272.         test_sell(price=storage['close'][-1])
  273.     # CALCULATE RETURN ON INVESTMENT
  274.     end_max_assets=(
  275.         portfolio['currency']/(storage['close'][-1])+portfolio['assets'])
  276.     end_max_currency=(
  277.         portfolio['currency']+portfolio['assets']*(storage['close'][-1]))
  278.     roi_assets = end_max_assets/storage['begin_max_assets']
  279.     roi_currency = end_max_currency/storage['begin_max_currency']
  280.     # FINAL REPORT
  281.     print('===============================================================')
  282.     print('START DATE........: %s' % time.ctime(info['begin']))
  283.     print('END DATE..........: %s' % time.ctime(info['end']))
  284.     print('START PRICE.......: %s satoshi' % ANTISAT*int(storage['start_price']))
  285.     print('END PRICE.........: %s satoshi' % ANTISAT*int(storage['close'][-1]))
  286.     print('START MAX ASSET...: %.2f %s' % (storage['begin_max_assets'],ASSET))
  287.     print('END MAX ASSET.....: %.2f %s' % (end_max_assets,ASSET))
  288.     print('ROI ASSET.........: %.1fX' % roi_assets)
  289.     print('START MAX CURRENCY: %.2f %s' % (storage['begin_max_currency'],CURRENCY))
  290.     print('END MAX CURRENCY..: %.2f %s' % (end_max_currency, CURRENCY))
  291.     print('ROI CURRENCY......: %.1fX' % roi_currency)
  292.     print('===============================================================')
  293.     print(VERSION)
  294.     print('~===END BACKTEST=========================~')
  295.  
  296. # PRIMARY EVENT LOOP
  297. initialize()
  298. fetch_polo()
  299.  
  300. while 1:
  301.     if info['current_time'] < info['end']:
  302.         info['current_time']+=CANDLE
  303.         tick()
  304.         info['tick']+=1
  305.     else:
  306.         stop()
  307.         plot()
  308.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement