Advertisement
Guest User

Untitled

a guest
Nov 7th, 2017
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.77 KB | None | 0 0
  1.  
  2.  
  3. import json
  4. from bokeh.models.layouts import LayoutDOM, Row, Column, Spacer, WidgetBox
  5. from bokeh.models.widgets import Widget
  6. import urllib
  7. import pandas as pd
  8. import numpy as np
  9. import pymssql
  10. import matplotlib as plt
  11. from bokeh.io import gridplot
  12.  
  13. plt.interactive(False)
  14. from datetime import datetime, timedelta
  15. from bokeh.plotting import figure
  16. from bokeh.models import NumeralTickFormatter, Legend
  17. from runpy import run_path
  18. # import GetData
  19. from bokeh.plotting import figure, show, output_file, ColumnDataSource
  20. from bokeh.resources import CDN
  21. from bokeh.embed import file_html
  22. from bokeh.models import PanTool, WheelZoomTool, BoxZoomTool, ResetTool, LassoSelectTool, SaveTool, CrosshairTool, \
  23. HoverTool, Label
  24. from urllib import urlopen
  25.  
  26. server = "marketxls.cnrjxpjg4y05.us-east-2.rds.amazonaws.com"
  27. print server
  28. user = "marketxls"
  29. password = "YgKvgthSDX20"
  30. cnxn = pymssql.connect(server, user, password, "marketxls")
  31.  
  32.  
  33. def mtext(p, x, y, text, text_color):
  34. p.text(x, y, text=[text],
  35. text_color=text_color, text_align="center", text_font_size="8pt", alpha=0.9, text_font="PT Sans")
  36.  
  37.  
  38. def mtext_white(p, x, y, text):
  39. p.text(x, y, text=[text],
  40. text_color="black", text_align="center", text_font_size="7pt")
  41.  
  42.  
  43. def mtext1(p, x, y, text):
  44. p.text(x, y, text=[text],
  45. text_color="black", text_align="center", text_font_size="10pt", alpha=0.9)
  46.  
  47.  
  48. Returns_Data_query = """
  49. SELECT [ticker_symbol]
  50. ,[Five_Year_Price]
  51. ,[Five_Year_Date]
  52. ,[Three_Year_Price]
  53. ,[Three_Year_Date]
  54. ,[One_Year_Price]
  55. ,[One_Year_Date]
  56. ,[Six_Month_Price]
  57. ,[Six_Month_Date]
  58. ,[Three_Month_Price]
  59. ,[Three_Month_Date]
  60. ,[One_Month_Price]
  61. ,[One_Month_Date]
  62. ,[Fifteen_Day_Price]
  63. ,[Fifteen_Days_Date]
  64. ,[Seven_Day_Price]
  65. ,[Seven_Days_Date]
  66. ,[One_Day_Price]
  67. ,[One_Day_Date]
  68. FROM [marketxls].[dbo].[v_ticker_price_date_for_returns1]"""
  69.  
  70. snp_symbols_q = """
  71. SELECT [Symbol]
  72. ,[Name]
  73. ,[ticker_industry]
  74.  
  75. FROM [marketxls].[dbo].[snp500]
  76. INNER JOIN [marketxls].[dbo].[ticker_detail] ON [Symbol] =[ticker_symbol];
  77.  
  78. """
  79.  
  80. Returns_Data = pd.read_sql(Returns_Data_query, cnxn)
  81. ticker_data = pd.read_sql(snp_symbols_q, cnxn)
  82. ticker_data.columns = ['ticker_symbol', 'Name', 'Industry']
  83. # print ticker_data
  84.  
  85. newdf = pd.merge(ticker_data, Returns_Data, on='ticker_symbol')
  86. # print newdf
  87.  
  88. newdf['Seven_Day_Return'] = (newdf['One_Day_Price'] - newdf['Seven_Day_Price']) / newdf['Seven_Day_Price']
  89. newdf['Fifteen_Day_Return'] = (newdf['One_Day_Price'] - newdf['Fifteen_Day_Price']) / newdf['Fifteen_Day_Price']
  90. newdf['Three_Month_Return'] = (newdf['One_Day_Price'] - newdf['Three_Month_Price']) / newdf['Three_Month_Price']
  91. newdf['Six_Month_Return'] = (newdf['One_Day_Price'] - newdf['Six_Month_Price']) / newdf['Six_Month_Price']
  92. newdf['One_Year_Return'] = (newdf['One_Day_Price'] - newdf['One_Year_Price']) / newdf['One_Year_Price']
  93. newdf['Three_Year_Return'] = (newdf['One_Day_Price'] - newdf['Three_Year_Price']) / newdf['Three_Year_Price']
  94. newdf['Five_Year_Return'] = (newdf['One_Day_Price'] - newdf['Five_Year_Price']) / newdf['Five_Year_Price']
  95.  
  96. cols_to_keep = ['ticker_symbol', 'Name', 'Industry', 'Seven_Day_Return',
  97. 'Fifteen_Day_Return', 'Three_Month_Return', 'Six_Month_Return',
  98. 'One_Year_Return', 'Three_Year_Return', 'Five_Year_Return']
  99. data = newdf[cols_to_keep].dropna()
  100. data.index = np.arange(len(data))
  101.  
  102. plots = []
  103. for category in cols_to_keep[3:9]:
  104. print category
  105.  
  106. width = 350
  107. gap = width / float(len(data.index))
  108. colors = ["red", "brown", "pink", "purple",
  109. "orange", "red", "blue", "green"]
  110. category_data = data[category]
  111.  
  112. tools = [HoverTool(tooltips=[
  113. ("Company name", "@name"),
  114. ("Value", "@percent"),
  115. ]), PanTool(), WheelZoomTool(),
  116. BoxZoomTool(), ResetTool(),
  117. LassoSelectTool(), SaveTool(),
  118. CrosshairTool()]
  119.  
  120. p = figure(plot_width=350, plot_height=250,
  121. title=category.replace('_', ' '),
  122. responsive=True, tools=tools)
  123. p.grid.grid_line_alpha = 0.3
  124. p.yaxis.axis_label = 'Return %'
  125. p.xaxis.visible = False
  126. # add a new formatter to y axis for percent view
  127. p.yaxis[0].formatter = NumeralTickFormatter(format="0.00%")
  128. p.title.align = 'center'
  129.  
  130. # divide rendering of text labels and circles with tooltips
  131. # because not necessary to add circles in loop,
  132. # when there is data source
  133. pos = 0
  134. for i in range(len(data)):
  135. mtext(p, pos, category_data[i],
  136. data['ticker_symbol'][i],
  137. colors[len(plots)])
  138. pos += gap
  139.  
  140. # data source is a wrapper on DataFrame or any other structures, which
  141. # can be used as a param to DataSource constructor
  142. # so now add a dict, but can add a DataFrame from this dict
  143. source = ColumnDataSource(
  144. data=dict(
  145. name=data['Name'],
  146. percent=(category_data * 100).astype('int32').apply(str).apply(lambda x: x + '%'),
  147. x=np.arange(0, width, gap),
  148. y=category_data
  149. )
  150. )
  151. # when add a data source, there are 2 ways:
  152. # - add own data for x and y axis
  153. # - just prompt needed columns from data source
  154. p.circle(x='x', y='y', size=15, color='black', source=source, alpha = 0)
  155.  
  156. plots.append(p)
  157.  
  158. mygplot = gridplot([plots[0], plots[1],
  159. plots[2], plots[3],
  160. plots[4], plots[5]],
  161. ncols=3, plot_width=330, plot_height=240,
  162. toolbar_location='right', merge_tools=True, responsive=True)
  163.  
  164. html = file_html(mygplot, CDN, "Returns Screener")
  165.  
  166. with open('returns_screener.html', 'w+') as f:
  167. f.write(html)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement