momentum.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import sys
  2. from pyspark import SparkContext
  3. from pyspark.streaming import StreamingContext
  4. from pyspark.streaming.kafka import KafkaUtils
  5. from numpy import *
  6. import pylab
  7. from scipy import stats
  8. import threading
  9. import time
  10. import os
  11. ##
  12. ##
  13. ##
  14. ## This example demonstrates the use of accumulators and broadcast
  15. ## and how to terminate spark running jobs
  16. ##
  17. ##
  18. ##
  19. ##
  20. ## insert the path so spark-submit knows where
  21. ## to look for a file located in a given directory
  22. ##
  23. ## the other method is to export PYTHONPATH before
  24. ## calling spark-submit
  25. ##
  26. # import sys
  27. # sys.path.insert(0, '/home/larry-13.04/workspace/finopt/cep')
  28. print sys.path
  29. #import optcal
  30. import json
  31. import numpy
  32. #from finopt.cep.redisQueue import RedisQueue
  33. from comms.redisQueue import RedisQueue
  34. def persist(time, rdd):
  35. #print (time, rdd)
  36. #lt = (rdd.collect())
  37. rdd.saveAsTextFile("./rdd/rdd-%s-%03d" % (Q.value['rname'], NumProcessed.value))
  38. print 'process................... %d' % NumProcessed.value
  39. NumProcessed.add(1)
  40. #pass
  41. #print '\n'.join ('%d %s'% (l[0], ''.join(('%f'% e) for e in l[1])) for l in list)
  42. def simple(time, rdd):
  43. lt = (rdd.collect())
  44. if lt:
  45. first = lt[0][1][0]
  46. last_pos = len(lt) - 1
  47. last = lt[last_pos][1][0]
  48. change = (last - first) / last
  49. print change, first, last, len(lt)
  50. print 'process................... %d' % NumProcessed.value
  51. NumProcessed.add(1)
  52. def cal_trend(time, rdd):
  53. def detect_trend(x1, y1, num_points_ahead, ric):
  54. z4 = polyfit(x1, y1, 3)
  55. p4 = poly1d(z4) # construct the polynomial
  56. #print y1
  57. z5 = polyfit(x1, y1, 4)
  58. p5 = poly1d(z5)
  59. extrap_y_max_limit = len(x1) * 2 # 360 days
  60. x2 = linspace(0, extrap_y_max_limit, 50) # 0, 160, 100 means 0 - 160 with 100 data points in between
  61. pylab.switch_backend('agg') # switch to agg backend that support writing in non-main threads
  62. pylab.plot(x1, y1, 'o', x2, p4(x2),'-g', x2, p5(x2),'-b')
  63. pylab.legend(['%s to fit' % ric, '4th degree poly', '5th degree poly'])
  64. #pylab.axis([0,160,0,10])
  65. #
  66. pylab.axis([0,len(x1)*1.1, min(y1)*0.997,max(y1)*1.002]) # first pair tells the x axis boundary, 2nd pair y axis boundary
  67. # compute the slopes of each set of data points
  68. # sr - slope real contains the slope computed from real data points from d to d+5 days
  69. # s4 - slope extrapolated by applying 4th degree polynomial
  70. y_arraysize = len(y1)
  71. # s4, intercept, r_value, p_value, std_err = stats.linregress(range(0,num_points_ahead), [p4(i) for i in range(y_arraysize,y_arraysize + num_points_ahead )])
  72. # s5, intercept, r_value, p_value, std_err = stats.linregress(range(0,num_points_ahead), [p5(i) for i in range(y_arraysize,y_arraysize + num_points_ahead )])
  73. s4, intercept, r_value, p_value, std_err = stats.linregress(x1, y1)
  74. s5, intercept, r_value, p_value, std_err = stats.linregress(x1, y1)
  75. rc = (1.0 if s4 > 0.0 else 0.0, 1.0 if s5 > 0.0 else 0.0)
  76. print s4, s5, rc, y_arraysize
  77. #pylab.show()
  78. pylab.savefig('../data/extrapolation/%s-%s.png' % (ric, time))
  79. d = Q.value
  80. q = RedisQueue(d['qname'], d['namespace'], d['host'], d['port'], d['db'])
  81. q.put((time, y1))
  82. # # clear memory
  83. pylab.close()
  84. return rc
  85. ls = rdd.collect()
  86. # print [y[1][0] for y in ls]
  87. # print len(ls), [range(len(ls))]
  88. # print len([y[1][0] for y in ls])
  89. if ls:
  90. rc = detect_trend(range(len(ls)), [y[1][0] for y in ls], 5, '_HSI')
  91. # to run from command prompt
  92. # 0. start kafka broker
  93. # 1. edit subscription.txt and prepare 2 stocks
  94. # 2. run ib_mds.py
  95. # 3. spark-submit --jars spark-streaming-kafka-assembly_2.10-1.4.1.jar ./alerts/pairs_corr.py vsu-01:2181
  96. # http://stackoverflow.com/questions/3425439/why-does-corrcoef-return-a-matrix
  97. #
  98. if __name__ == "__main__":
  99. if len(sys.argv) != 5:
  100. print("Usage: %s <broker_list ex: vsu-01:2181> <rdd_name> <tick id> <fn name>" % sys.argv[0])
  101. print("Usage: to gracefully shutdown type echo 1 > /tmp/flag at the terminal")
  102. exit(-1)
  103. app_name = "Momentum"
  104. sc = SparkContext(appName= app_name) #, pyFiles = ['./cep/redisQueue.py'])
  105. ssc = StreamingContext(sc, 2)
  106. ssc.checkpoint('../checkpoint')
  107. brokers, qname, id, fn = sys.argv[1:]
  108. id = int(id)
  109. #
  110. # demonstrate how to use broadcast variable
  111. #
  112. NumProcessed = sc.accumulator(0)
  113. Q = sc.broadcast({'rname': 'rname', 'qname': qname, 'namespace': 'mdq', 'host': 'localhost', 'port':6379, 'db': 3})
  114. #kvs = KafkaUtils.createDirectStream(ssc, ['ib_tick_price', 'ib_tick_size'], {"metadata.broker.list": brokers})
  115. kvs = KafkaUtils.createStream(ssc, brokers, app_name, {'ib_tick_price':1, 'ib_tick_size':1})
  116. lines = kvs.map(lambda x: x[1])
  117. s1 = lines.map(lambda line: json.loads(line)).filter(lambda x: (x['tickerId'] == id and x['typeName']== 'tickPrice'))\
  118. .filter(lambda x: (x['field'] == 1))\
  119. .map(lambda x: (id, x['price'])).window(30, 20)
  120. s2 = lines.map(lambda line: json.loads(line)).filter(lambda x: (x['tickerId'] == id and x['typeName']== 'tickSize'))\
  121. .filter(lambda x: (x['field'] == 5))\
  122. .map(lambda x: (id, x['size'])).window(30, 20)
  123. #trades = s1.join(s2)
  124. trades = s1.leftOuterJoin(s2)
  125. #s1.pprint()
  126. trades.pprint()
  127. trades.foreachRDD(eval(fn))
  128. def do_work():
  129. while 1:
  130. # program will stop after processing 40 rdds
  131. if NumProcessed.value == 999:
  132. break
  133. # program will stop on detecting a 1 in the flag file
  134. try:
  135. f = open('/tmp/flag')
  136. l = f.readlines()
  137. print 'reading %s' % l[0]
  138. if '1' in l[0]:
  139. break
  140. f.close()
  141. time.sleep(2)
  142. except:
  143. continue
  144. print 'terminating...'
  145. ssc.stop(True, False)
  146. os.remove('/tmp/flag')
  147. t = threading.Thread(target = do_work, args=())
  148. t.start()
  149. ssc.start()
  150. ssc.awaitTermination()