hhashim1

Sample Python Code

Dec 7th, 2021
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 146.77 KB | None | 0 0
  1. import pandas as pd
  2. from enum import Enum
  3. from psycopg2 import pool
  4. from sqlalchemy import create_engine, text
  5. from datetime import date, datetime, timedelta, timezone
  6. import concurrent.futures
  7. import requests as rq
  8. import requests
  9. import time
  10. #import .config.config
  11. import os
  12. import sys
  13. sys.path.append(os.path.abspath('config/'))
  14. import config
  15. #from config.config import config
  16. import traceback
  17. import stocks
  18. import options
  19. import reference
  20. import multiprocessing
  21. import threading
  22. import pprint
  23. import pytz
  24. import pandas_market_calendars as mcal
  25. import json
  26. import redis
  27. import io
  28. import csv
  29. import re
  30. import pickle
  31. from collections import defaultdict
  32. import asyncio
  33. #import justpy as jp
  34. from redis_dict import RedisDict
  35. #import unittest
  36. import dateutil.parser
  37. from datetimerange import DateTimeRange
  38. import polygon
  39. from polygon import enums, cred
  40. from requests.models import Response
  41. from httpx import Response as HttpxResponse
  42. from typing import Union
  43. import httpx
  44. sys.path.append(os.path.abspath('big/'))
  45. from resample_price_indicators import resample
  46.  
  47. options_key = config.polygon_key_options
  48. #stocks_key = config.polygon_key_stocks
  49. stocks_key = cred.KEY
  50.  
  51. pd.set_option('display.max_columns', None)
  52. #pd.set_option('display.max_rows', None)
  53. # Key
  54. key = config.polygon_key_stocks
  55.  
  56. r = redis.Redis(host=config.redis_host, port=config.redis_port, charset="utf-8", decode_responses=True)
  57. r_dict = RedisDict(host=config.redis_host, port=config.redis_port, charset="utf-8")
  58.  
  59.  
  60. ## Input
  61. #multiplier = 1
  62. #timespan = 'minute'
  63. #adjusted = 'true'
  64. #sort = 'desc'
  65. #limit = 50000
  66.  
  67. # Database / Get list of tickers
  68.  
  69. engine = create_engine(config.psql, pool_size=400, max_overflow=75)
  70.  
  71. postgreSQL_pool = pool.ThreadedConnectionPool(200, 295, host=config.psql_host, database=config.psql_db,
  72. user=config.psql_user, password=config.psql_pw)
  73. #engine = create_engine(postgreSQL_pool)
  74.  
  75. conn = postgreSQL_pool.getconn()
  76. # code that uses a connection
  77. postgreSQL_pool.putconn(conn)
  78. #engine = conn
  79.  
  80. #symbols_df = pd.read_sql_query('select ticker from companies where active = true', con=conn)
  81. #symbols = symbols_df['ticker'].to_list()
  82. #print(symbols)
  83.  
  84. #print(multiprocessing.cpu_count())
  85.  
  86. stock_ticks_df = pd.DataFrame()
  87. one_minute_df = pd.DataFrame()
  88. bars_df = pd.DataFrame()
  89. latest_min_bar_df = pd.DataFrame()
  90.  
  91. minutes_processed = {}
  92. minute_candlesticks = []
  93. current_tick = None
  94. previous_tick = None
  95. in_position = False
  96.  
  97. big_df = pd.DataFrame()
  98.  
  99. class DataType(str, Enum):
  100. Bars = "Bars"
  101. Trades = "Trades"
  102. Quotes = "Quotes"
  103.  
  104.  
  105. def get_data_method(data_type: DataType):
  106. if data_type == DataType.Bars:
  107. return rest.get_bars_async
  108. elif data_type == DataType.Trades:
  109. return rest.get_trades_async
  110. elif data_type == DataType.Quotes:
  111. return rest.get_quotes_async
  112. else:
  113. raise Exception(f"Unsupoported data type: {data_type}")
  114.  
  115.  
  116.  
  117. class Historical_Data:
  118. def __init__(self):
  119. self.KEY = key # your key
  120. self.BASE = 'https://api.polygon.io'
  121. self.session = rq.session()
  122. self.session.headers.update({'Authorization': 'Bearer %s' % self.KEY})
  123.  
  124. def get_response(self, path: str, params: dict = None):
  125. return self.session.request('GET', self.BASE + path, params=params).json()
  126.  
  127. def get_next_page(self, url: str):
  128. return self.session.request('GET', url).json()
  129.  
  130.  
  131. def redis_message(list, messages):
  132. #print(messages)
  133. #print(type(messages))
  134.  
  135. #print(messages)
  136. #print( json.dumps(messages))
  137.  
  138. #return
  139. #for message in messages:
  140. # print(message)
  141.  
  142. #return
  143.  
  144. #r.hmset(list, json.dumps(messages))
  145.  
  146. #r.hmgetall(list)
  147.  
  148.  
  149. #return
  150.  
  151. #p_mydict = pickle.dumps(messages)
  152. #r.set('mydict',p_mydict)
  153.  
  154. #read_dict = r.get('mydict')
  155. #yourdict = pickle.loads(read_dict)
  156. #print(yourdict)
  157. #return
  158.  
  159.  
  160. #r.hmset(list, json.dumps(messages))
  161. #r.hgetall(list)
  162. #return
  163.  
  164. try:
  165. for message in messages:
  166. #print(message)
  167. r.rpush(list, json.dumps(message))
  168. #r.rpush('stock-list', json.dumps(message))
  169. except Exception:
  170. traceback.print_exc()
  171. return None
  172.  
  173.  
  174. def redis_dict_update(messages):
  175. #redis_dic = self.create_redis_dict()
  176.  
  177. #dic = dict()
  178.  
  179. #input_values = {
  180. # "int": 1,
  181. # "float": 0.9,
  182. # "str": "im a string",
  183. # "bool": True,
  184. # "None": None,
  185. #}
  186. print(' ')
  187. print(' ')
  188. print(' ')
  189. pprint.pprint(messages['todaysChangePerc'][:10])
  190. #pprint.pprint(messages['todaysChangePerc'], messages['symbol'])
  191. #self.assertEqual(len(redis_dic), 0)
  192. #self.assertEqual(len(dic), 0)
  193. #self.assertEqual(len(input_values), 5)
  194.  
  195. ###r_dict.update('abc', messages)
  196. #dic.update(input_values)
  197.  
  198. #assertEqual(len(r_dict), 5)
  199. #assertEqual(len(dic), 5)
  200. #assertEqual(len(input_values), 5)
  201.  
  202. #print(len(r_dict))
  203. ##print(len(dic))
  204. ##print(len(input_values))
  205. #print(len(messages))
  206. #message_count = len(r_dict)
  207. #print('message count = ', message_count)
  208.  
  209. ##for expected_key, expected_value in input_values.items():
  210. ##for expected_key, expected_value in messages.items():
  211. ## print(r_dict[expected_key], expected_value)
  212. # #print(dic[expected_key], expected_value)
  213. ##pprint.pprint(sorted(r_dict))
  214. ##expected = [dic.popitem() for _ in range(5)]
  215. ##result = [r_dict.popitem() for _ in range(7)]
  216. ##result = [r_dict.popitem() for _ in range(7)]
  217. ##i = 1
  218. ##for k in r_dict: #range(7)
  219. ## print(i)
  220. ## print(k)
  221. ## i += 1
  222. ## result = r_dict.popitem()
  223.  
  224.  
  225. ##for i, key in enumerate(r_dict.keys(), start=1):
  226. ## #expected = dic.pop(key)
  227. ## result = r_dict.pop(key)
  228. ## #pprint.pprint(result)
  229. ## #print(i)
  230.  
  231. #copied_dict = r_dict.copy()
  232. #r_dict.clear()
  233. #print(len(r_dict))
  234. #print(len(copied_dict))
  235.  
  236. ##for i, key in enumerate(copied_dict.keys(), start=1):
  237. ##i = 1
  238. ##for key in list(r_dict):
  239. ## #expected = dic.pop(key)
  240. ## result = r_dict.pop(key)
  241. ## #pprint.pprint(result)
  242. ## i += 1
  243. ## #print(i)
  244. ##print(i)
  245.  
  246. #i = 1
  247. #for key in list(copied_dict):
  248. # #expected = dic.pop(key)
  249. # result = copied_dict.pop(key)
  250. # #pprint.pprint(result)
  251. # i += 1
  252. # #print(i)
  253. #print(i)
  254. #result = [r_dict.popitem() for _ in range(message_count)]
  255. #pprint.pprint(result)
  256. #self.assertEqual(sorted(map(str, expected)), sorted(map(str, result)))
  257. #pprint.pprint(sorted(map(str, result)))
  258. #sorted_dict = sorted(map(str, result))
  259.  
  260. #pprint.pprint(sorted_dict)
  261.  
  262. #for key in sorted_dict:
  263. # print(key)
  264. #print(sorted_dict[key])
  265.  
  266.  
  267. #self.assertEqual(len(dic), 0)
  268. #self.assertEqual(len(redis_dic), 0)
  269. #print(len(r_dict))
  270.  
  271. #with self.assertRaises(KeyError):
  272. # dic.popitem()
  273. #with self.assertRaises(KeyError):
  274. # redis_dic.popitem()
  275.  
  276. #wp = jp.WebPage(delete_flag=False)
  277. #my_paragraph_design = "w-64 bg-blue-500 m-2 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
  278. #for i in range(1,11):
  279. # jp.P(text=f'{i}) Hello World!', a=wp, classes=my_paragraph_design)
  280.  
  281. #def my_click(self, msg):
  282. # self.text = 'I was clicked'
  283.  
  284. #def event_demo():
  285. # wp = jp.WebPage()
  286. # d = jp.Div(text='Not clicked yet', a=wp, classes='w-48 text-xl m-2 p-1 bg-blue-500 text-white')
  287. # d.on('click', my_click)
  288. # return wp
  289.  
  290.  
  291.  
  292. #def my_click(self, msg):
  293. # self.text = 'I was clicked'
  294. # self.set_class('bg-blue-500')
  295.  
  296. #def my_mouseenter(self, msg):
  297. # self.text = 'Mouse entered'
  298. # self.set_class('bg-red-500')
  299.  
  300. #def my_mouseleave(self, msg):
  301. # self.text = 'Mouse left'
  302. # self.set_class('bg-teal-500')
  303.  
  304.  
  305. #def event_demo():
  306. # wp = jp.WebPage()
  307. # d = jp.Div(text='Not clicked yet', a=wp, classes='w-64 text-2xl m-2 p-2 bg-blue-500 text-white',
  308. # click=my_click, mouseenter=my_mouseenter, mouseleave=my_mouseleave)
  309. # return wp
  310.  
  311.  
  312. #def button_click(self, msg):
  313. # self.num_clicked += 1
  314. # # self.message.text = f'{self.text} clicked. Number of clicks: {self.num_clicked}'
  315. # p = jp.P(text=f'{self.text} clicked. Number of clicks: {self.num_clicked}')
  316. # self.message.add_component(p, 0)
  317. # for button in msg.page.button_list:
  318. # button.set_class('bg-blue-500')
  319. # button.set_class('bg-blue-700', 'hover')
  320. # self.set_class('bg-red-500')
  321. # self.set_class('bg-red-700', 'hover')
  322.  
  323. #def event_demo():
  324. # number_of_buttons = 25
  325. # wp = jp.WebPage()
  326. # button_div = jp.Div(classes='flex m-4 flex-wrap', a=wp)
  327. # button_classes = 'w-32 mr-2 mb-2 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full'
  328. # message = jp.Div(classes='text-lg border m-2 p-2 overflow-auto h-64', a=wp)
  329. # message.add(jp.P(text='No button clicked yet'))
  330. # button_list = []
  331. # for i in range(1, number_of_buttons + 1):
  332. # b = jp.Button(text=f'Button {i}', a=button_div, classes=button_classes, click=button_click)
  333. # b.message = message
  334. # b.num_clicked = 0
  335. # button_list.append(b)
  336. # wp.button_list = button_list # The list will now be referenced by the WebPage instance attribute
  337. # return wp
  338.  
  339. def comp_test():
  340. wp = jp.WebPage()
  341. d = jp.Div(text='hello1',
  342. click='self.text="clicked"',
  343. mouseenter='self.text="entered"; self.set_class("text-5xl"); msg.page.add(Div(text=f"{len(msg.page)} Additional Div"))',
  344. mouseleave='self.text="left"; self.set_class("text-xl")',
  345. classes='text-2xl border p-2 m-2', a=wp )
  346. d = jp.Div(text='hello2', click='self.text="clicked"', mouseenter='self.text="entered"', classes='text-2xl border p-2 m-2', a=wp )
  347. d = jp.Div(text='hello3', click='self.text="clicked"', mouseenter='self.text="entered"', classes='text-2xl border p-2 m-2', a=wp )
  348. return wp
  349.  
  350. def hello_world():
  351. #wp = jp.WebPage()
  352. ##for i in range(1,11):
  353. ## jp.P(text=f'{i}) Hello World!', a=wp, style=f'font-size: {10*i}px')= "w-64 bg-blue-500 m-2 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
  354.  
  355. #my_paragraph_design = "w-64 bg-blue-500 m-2 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
  356. #for i in range(1,11):
  357. # jp.P(text=f'{i}) Hello World!', a=wp, classes=my_paragraph_design)
  358. return wp
  359.  
  360. def grid_test():
  361. #try:
  362.  
  363. wp = jp.WebPage()
  364. wm_df = symbols_df
  365. #wm_df = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
  366. if wm_df.empty != True:
  367. grid = wm_df.jp.ag_grid(a=wp)
  368. grid.options.pagination = True
  369. grid.options.paginationAutoPageSize = True
  370. grid.options.columnDefs[0].cellClass = ['text-white', 'bg-blue-500', 'hover:bg-blue-200']
  371. for col_def in grid.options.columnDefs[1:]:
  372. col_def.cellClassRules = {
  373. 'font-bold': 'x < 20',
  374. 'bg-red-300': 'x < 20',
  375. 'bg-yellow-300': 'x >= 20 && x < 50',
  376. 'bg-green-300': 'x >= 50'
  377. }
  378. #except Exception as exe:
  379. # print(exe)
  380. # traceback.print_exc()
  381. ##else:
  382. ## return None
  383. return wp
  384.  
  385. def unix_convert(ts):
  386. if len(str(ts)) == 13:
  387. ts = int(ts/1000)
  388. else:
  389. ts = int(ts/1000000000)
  390. tdate = datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S.%f')
  391. return tdate
  392.  
  393.  
  394. def get_historic_bars(symbol, start_date, end_date, adjusted=True, sort='desc', limit=50000, multiplier=1, timespan='minute'):
  395. try:
  396.  
  397. #multiplier = 1
  398. #timespan = 'minute'
  399. #adjusted = 'true'
  400. #sort = 'desc'
  401. #limit = 50000
  402.  
  403. #pg_client = Historical_Data()
  404. s = stocks.StocksPolygon
  405.  
  406. endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
  407. #resp = pg_client.get_response(
  408. # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
  409. resp = s.get_aggregate_bars(symbol, start_date, end_date, adjusted, sort, limit, multiplier, timespan)
  410. #print('resp=')
  411. #print(resp)
  412. if resp == 'results':
  413. df = None
  414. else:
  415. if 'results' in resp:
  416. df = pd.DataFrame.from_dict(resp['results'])
  417.  
  418. #if 'a' in df.columns:
  419. if len(df) > 0:
  420. df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't']]
  421. pass
  422. #else:
  423. #df.insert(1, 'a', None)
  424. #df.insert(9, 'op', None)
  425. #df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't', 'n',]]
  426.  
  427. df.columns = ['volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp']
  428. df.insert(0, 'symbol', symbol)
  429. df.insert(1, 'frequency', str(multiplier) + timespan)
  430. #df.insert(3, 'total_volume', None)
  431. #df.insert(3, 'vwap', None)
  432. #df.insert(3, 'avg_trade_size', None)
  433. #df.insert(3, 'time_beg', None)
  434. #df.drop('a', axis=1, inplace=True)
  435. #df.drop('n', axis=1, inplace=True)
  436. df['tdate'] = df['timestamp'].map(lambda x: unix_convert(x))
  437. df['save_date'] = datetime.utcnow()
  438. #df = df[['symbol', 'volume', 'open', 'close', 'high', 'low', 'vwap', 'timestamp', 'tdate', 'save_date']]
  439. df = df[['symbol', 'frequency', 'volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp', 'tdate', 'save_date']]
  440. #else:
  441. # print('its empty bars ', start_date, ' ', end_date, symbol)
  442. else:
  443. df=None
  444. except Exception as exe:
  445. print(exe)
  446. traceback.print_exc()
  447. time.sleep(10)
  448. df = None
  449. return df
  450.  
  451. def get_historic_bars_options(option_symbol, start_date, end_date, adjusted=True, sort='desc', limit=50000, multiplier=1, timespan='minute'):
  452. try:
  453.  
  454. #multiplier = 1
  455. #timespan = 'minute'
  456. #adjusted = 'true'
  457. #sort = 'desc'
  458. #limit = 50000
  459.  
  460. #pg_client = Historical_Data()
  461. s = stocks.StocksPolygon
  462.  
  463. endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
  464. #resp = pg_client.get_response(
  465. # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
  466. #resp = s.get_aggregate_bars(symbol, start_date, end_date, adjusted, sort, limit, multiplier, timespan)
  467. resp = get_options_aggregate_bars(option_symbol, start_date, end_date, adjusted=True, sort='asc', limit=50000, multiplier=1, timespan='minute')
  468. #print('resp=')
  469. #print(resp)
  470. if resp == 'results':
  471. df = None
  472. else:
  473. if 'results' in resp:
  474. df = pd.DataFrame.from_dict(resp['results'])
  475.  
  476. #if 'a' in df.columns:
  477. if len(df) > 0:
  478. df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't']]
  479. pass
  480. #else:
  481. #df.insert(1, 'a', None)
  482. #df.insert(9, 'op', None)
  483. #df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't', 'n',]]
  484.  
  485. df.columns = ['volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp']
  486. df.insert(0, 'symbol', option_symbol)
  487. df.insert(1, 'frequency', str(multiplier) + timespan)
  488. #df.insert(3, 'total_volume', None)
  489. #df.insert(3, 'vwap', None)
  490. #df.insert(3, 'avg_trade_size', None)
  491. #df.insert(3, 'time_beg', None)
  492. #df.drop('a', axis=1, inplace=True)
  493. #df.drop('n', axis=1, inplace=True)
  494. df['tdate'] = df['timestamp'].map(lambda x: unix_convert(x))
  495. df['save_date'] = datetime.utcnow()
  496. #df = df[['symbol', 'volume', 'open', 'close', 'high', 'low', 'vwap', 'timestamp', 'tdate', 'save_date']]
  497. df = df[['symbol', 'frequency', 'volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp', 'tdate', 'save_date']]
  498. #else:
  499. # print('its empty bars ', start_date, ' ', end_date, symbol)
  500. else:
  501. df=None
  502. except Exception as exe:
  503. print(exe)
  504. traceback.print_exc()
  505. time.sleep(10)
  506. df = None
  507. return df
  508.  
  509. def get_last_bar(symbol, timespan='minute'):
  510. try:
  511.  
  512. #multiplier = 1
  513. #timespan = 'minute'
  514. #adjusted = 'true'
  515. #sort = 'desc'
  516. #limit = 50000
  517.  
  518. #pg_client = Historical_Data()
  519. s = stocks.StocksPolygon
  520.  
  521. #endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
  522. #resp = pg_client.get_response(
  523. # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
  524. resp = s.get_aggregate_bars(symbol, date.today(), date.today(), adjusted=True, sort='desc', limit=1, multiplier=1, timespan=timespan)
  525. #print('resp=')
  526. #print(resp)
  527. if resp == 'results':
  528. df = None
  529. else:
  530. if 'results' in resp:
  531. df = pd.DataFrame.from_dict(resp['results'])
  532.  
  533. #if 'a' in df.columns:
  534. if len(df) > 0:
  535. df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't']]
  536. pass
  537. #else:
  538. #df.insert(1, 'a', None)
  539. #df.insert(9, 'op', None)
  540. #df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't', 'n',]]
  541.  
  542. df.columns = ['volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp']
  543. df.insert(0, 'symbol', symbol)
  544. df.insert(1, 'frequency', str(1) + timespan)
  545. #df.insert(3, 'total_volume', None)
  546. #df.insert(3, 'vwap', None)
  547. #df.insert(3, 'avg_trade_size', None)
  548. #df.insert(3, 'time_beg', None)
  549. #df.drop('a', axis=1, inplace=True)
  550. #df.drop('n', axis=1, inplace=True)
  551. df['tdate'] = df['timestamp'].map(lambda x: unix_convert(x))
  552. df['save_date'] = datetime.utcnow()
  553. #df = df[['symbol', 'volume', 'open', 'close', 'high', 'low', 'vwap', 'timestamp', 'tdate', 'save_date']]
  554. df = df[['symbol', 'frequency', 'volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp', 'tdate', 'save_date']]
  555. #else:
  556. # print('its empty bars ', start_date, ' ', end_date, symbol)
  557. else:
  558. df=None
  559. except Exception as exe:
  560. print(exe)
  561. traceback.print_exc()
  562. time.sleep(10)
  563. df = None
  564. return df
  565.  
  566. def get_historic_trades(symbol, requestdate, reverse=True, limit=5000):
  567. #def get_historic_trades(symbol, requestdate, timestamp, reverse=True, limit=5000):
  568. try:
  569. #pg_client = Historical_Data()
  570. s = stocks.StocksPolygon
  571.  
  572. #endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
  573. #resp = pg_client.get_response(
  574. # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
  575. resp = s.get_trades(symbol=symbol, requestdate=requestdate, reverse=reverse, limit=limit)
  576. #resp = s.get_trades(symbol=symbol, requestdate=requestdate, timestamp=timestamp, reverse=reverse, limit=limit)
  577. #print('resp=')
  578. #print(resp)
  579. if resp == 'results':
  580. df = None
  581. else:
  582. if 'results' in resp:
  583. df = pd.DataFrame.from_dict(resp['results'])
  584. #pprint.pprint(df[:5])
  585.  
  586. #if 'c' in df.columns:
  587. if len(df) > 0:
  588. df = df[['c', 'i', 'p', 'q', 's', 't', 'x', 'y', 'z']]
  589. df.columns = ['conditions', 'id', 'price', 'sequence_number',
  590. 'size', 'sip_timestamp', 'exchange', 'participant_timestamp', 'tape']
  591. #pass
  592. #else:
  593. # df.insert(1, 'a', None)
  594. # df.insert(9, 'op', None)
  595. # df = df[['v', 'a', 'vw', 'o', 'c', 'h', 'l', 't', 'n', 'op']]
  596.  
  597. #df.columns = ['conditions', 'id', 'price', 'sequence_number',
  598. # 'size', 'sip_timestamp', 'exchange', 'participant_timestamp', 'tape']
  599. df.insert(0, 'symbol', symbol)
  600. #df.insert(3, 'total_volume', None)
  601. #df.insert(3, 'vwap', None)
  602. #df.insert(3, 'avg_trade_size', None)
  603. #df.insert(3, 'time_beg', None)
  604. #df.drop('a', axis=1, inplace=True)
  605. #df.drop('n', axis=1, inplace=True)
  606. df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
  607. df['save_date'] = datetime.utcnow()
  608. df.columns = ['symbol', 'conditions', 'id', 'price', 'sequence_number',
  609. 'size', 'sip_timestamp', 'exchange', 'participant_timestamp', 'tape', 'tdate', 'save_date']
  610. #pprint.pprint(df)
  611. #else:
  612. # print('its empty trades ', requestdate, ' ', symbol)
  613.  
  614. #if len(df) > 0:
  615. # pprint.pprint(df)
  616. else:
  617. df=None
  618. except Exception as exe:
  619. print(exe)
  620. traceback.print_exc()
  621. time.sleep(10)
  622. df = None
  623. return df
  624.  
  625. def get_historic_quotes(symbol, requestdate, reverse=True, limit=5000):
  626. #def get_historic_trades(symbol, requestdate, timestamp, reverse=True, limit=5000):
  627. try:
  628. #pg_client = Historical_Data()
  629. s = stocks.StocksPolygon
  630.  
  631. #endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
  632. #resp = pg_client.get_response(
  633. # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
  634. resp = s.get_quotes(symbol=symbol, requestdate=requestdate, reverse=reverse, limit=limit)
  635. #resp = s.get_trades(symbol=symbol, requestdate=requestdate, timestamp=timestamp, reverse=reverse, limit=limit)
  636. #print('resp=')
  637. #print(resp)
  638. if resp == 'results':
  639. df = None
  640. else:
  641. if 'results' in resp:
  642. df = pd.DataFrame.from_dict(resp['results'])
  643. #pprint.pprint(df[:5])
  644.  
  645. #if 'c' in df.columns:
  646. if len(df) > 0:
  647. df = df[['t', 'y', 'q', 'c', 'p', 's', 'x', 'P', 'S', 'X', 'z']]
  648. df.columns = ['sip_timestamp', 'participant_timestamp', 'sequence_number', 'conditions', 'bid_price', 'bid_size', 'bid_exchange',
  649. 'ask_price', 'ask_size', 'ask_exchange', 'tape']
  650. #pass
  651. #else:
  652. # df.insert(1, 'a', None)
  653. # df.insert(9, 'op', None)
  654. # df = df[['v', 'a', 'vw', 'o', 'c', 'h', 'l', 't', 'n', 'op']]
  655.  
  656. #df.columns = ['conditions', 'id', 'price', 'sequence_number',
  657. # 'size', 'sip_timestamp', 'exchange', 'participant_timestamp', 'tape']
  658. df.insert(0, 'symbol', symbol)
  659. #df.insert(3, 'total_volume', None)
  660. #df.insert(3, 'vwap', None)
  661. #df.insert(3, 'avg_trade_size', None)
  662. #df.insert(3, 'time_beg', None)
  663. #df.drop('a', axis=1, inplace=True)
  664. #df.drop('n', axis=1, inplace=True)
  665. #print(df['sip_timestamp'])
  666.  
  667. #if len(str(df['sip_timestamp'])) == 13:
  668. df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
  669. df['save_date'] = datetime.utcnow()
  670. df = df[['symbol', 'sip_timestamp', 'participant_timestamp', 'sequence_number', 'conditions', 'bid_price', 'bid_size', 'bid_exchange',
  671. 'ask_price', 'ask_size', 'ask_exchange', 'tape', 'tdate', 'save_date']]
  672. #pprint.pprint(df)
  673. #else:
  674. # print('its empty quotes ', requestdate, ' ', symbol)
  675.  
  676. #if len(df) > 0:
  677. # pprint.pprint(df)
  678. else:
  679. df=None
  680. except Exception as exe:
  681. print(exe)
  682. traceback.print_exc()
  683. time.sleep(10)
  684. df = None
  685. return df
  686.  
  687. def get_current_stocks_snapshot(symbols=None):
  688. #def get_historic_trades(symbol, requestdate, timestamp, reverse=True, limit=5000):
  689. try:
  690. #pg_client = Historical_Data()
  691. s = stocks.StocksPolygon
  692. z = datetime.today()
  693. #print(z)
  694. #endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
  695. #resp = pg_client.get_response(
  696. # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
  697. if symbols is None:
  698. resp = s.get_snapshot_all()
  699. else:
  700. resp = s.get_snapshot_all(symbols=symbols)
  701.  
  702. #resp = s.get_trades(symbol=symbol, requestdate=requestdate, timestamp=timestamp, reverse=reverse, limit=limit)
  703. #print('resp=')
  704. #print(resp)
  705. #return
  706. #if resp == 'results':
  707.  
  708. global_dict = {}
  709. daydict = None
  710. lastQuotedict = None
  711. lastTradedict = None
  712. minuteBardict = None
  713. prevDaydict = None
  714. i=0
  715. if resp is None:
  716. df = None
  717.  
  718. else:
  719. #if 'results' in resp:
  720. if resp['count'] > 0:
  721. #df = pd.DataFrame.from_dict(resp['tickers'])
  722. #df = pd.DataFrame.from_dict(resp['tickers'], index='symbol', orient='index')
  723. #df = pd.concat({
  724. # k: pd.DataFrame.from_dict(v, 'index') for k, v in resp.items()}, axis=0)
  725. #pprint.pprint(df[:5])
  726.  
  727. #if 'c' in df.columns:
  728. #x = ndict({'key1': ndict({'attr1':1, 'attr2':2})})
  729. #print(resp[0]['day'])
  730.  
  731. res = defaultdict(list)
  732. big_df = pd.DataFrame()
  733. joined_dict = {}
  734.  
  735.  
  736. #daydict = defaultdict(list)
  737. #lastQuotedict = defaultdict(list)
  738. #lastTradedict = defaultdict(list)
  739. #minuteBardict = defaultdict(list)
  740. #prevDaydict = defaultdict(list)
  741.  
  742. daydict = {}
  743. lastQuotedict = {}
  744. lastTradedict = {}
  745. minuteBardict = {}
  746. prevDaydict = {}
  747.  
  748.  
  749. #daydict = defaultdict(dict)
  750. #lastQuotedict = defaultdict(dict)
  751. #lastTradedict = defaultdict(dict)
  752. #minuteBardict = defaultdict(dict)
  753. #prevDaydict = defaultdict(dict)
  754.  
  755.  
  756. for sub in resp['tickers']:
  757. #joined_df = pd.DataFrame()
  758. #daydict = defaultdict(list)
  759. #lastQuotedict = defaultdict(list)
  760. #lastTradedict = defaultdict(list)
  761. #minuteBardict = defaultdict(list)
  762. #prevDaydict = defaultdict(list)
  763. #ticker = ''
  764. #todaysChange = ''
  765. #todaysChangePerc = ''
  766. #updated = ''
  767.  
  768. #for k in sub:
  769. #res[k].append(sub[k])
  770. #print(sub)
  771. #print(k)
  772. #print(sub[k])
  773.  
  774. daydict['symbol'] = sub['ticker']
  775. daydict['todaysChange'] = sub['todaysChange']
  776. daydict['todaysChangePerc'] = sub['todaysChangePerc']
  777. daydict['updated'] = sub['updated']
  778.  
  779. #daydict.update('close', sub['day']['c'])
  780. #daydict.update('high', sub['day']['h'])
  781. #daydict.update('low', sub['day']['l'])
  782. #daydict.update('open', sub['day']['o'])
  783. #daydict.update('volume', sub['day']['v'])
  784. #daydict.update('vwap', sub['day']['vw'])
  785.  
  786. daydict['close'] = sub['day']['c']
  787. daydict['high'] = sub['day']['h']
  788. daydict['low'] = sub['day']['l']
  789. daydict['open'] = sub['day']['o']
  790. daydict['volume'] = sub['day']['v']
  791. daydict['vwap'] = sub['day']['vw']
  792.  
  793. #daydict['close'].append(sub['day']['c'])
  794. #daydict['high'].append(sub['day']['h'])
  795. #daydict['low'].append(sub['day']['l'])
  796. #daydict['open'].append(sub['day']['o'])
  797. #daydict['volume'].append(sub['day']['v'])
  798. #daydict['vwap'].append(sub['day']['vw'])
  799.  
  800.  
  801. lastQuotedict['lastQuote_ask_price'] = sub['lastQuote']['P']
  802. lastQuotedict['lastQuote_ask_size'] = sub['lastQuote']['S']
  803. lastQuotedict['lastQuote_bid_price'] = sub['lastQuote']['p']
  804. lastQuotedict['lastQuote_bid_size'] = sub['lastQuote']['s']
  805. lastQuotedict['lastQuote_timestamp'] = sub['lastQuote']['t']
  806.  
  807. lastTradedict['lastTrade_close'] = sub['lastTrade']['c']
  808. lastTradedict['lastTrade_trade_id'] = sub['lastTrade']['i']
  809. lastTradedict['lastTrade_price'] = sub['lastTrade']['p']
  810. lastTradedict['lastTrade_size'] = sub['lastTrade']['s']
  811. lastTradedict['lastTrade_time'] = sub['lastTrade']['t']
  812. lastTradedict['lastTrade_exch_id'] = sub['lastTrade']['x']
  813.  
  814.  
  815. minuteBardict['minuteBar_total_volume'] = sub['min']['av']
  816. minuteBardict['minuteBar_close'] = sub['min']['c']
  817. minuteBardict['minuteBar_high'] = sub['min']['h']
  818. minuteBardict['minuteBar_low'] = sub['min']['l']
  819. minuteBardict['minuteBar_open'] = sub['min']['o']
  820. minuteBardict['minuteBar_volume'] = sub['min']['v']
  821. minuteBardict['minuteBar_vwap'] = sub['min']['vw']
  822.  
  823.  
  824.  
  825. prevDaydict['prevDay_close'] = sub['prevDay']['c']
  826. prevDaydict['prevDay_high'] = sub['prevDay']['h']
  827. prevDaydict['prevDay_low'] = sub['prevDay']['l']
  828. prevDaydict['prevDay_open'] = sub['prevDay']['o']
  829. prevDaydict['prevDay_volume'] = sub['prevDay']['v']
  830. prevDaydict['prevDay_vwwap'] = sub['prevDay']['vw']
  831.  
  832.  
  833. #lastQuotedict['lastQuote_ask_price'].append(sub['lastQuote']['P'])
  834. #lastQuotedict['lastQuote_ask_size'].append(sub['lastQuote']['S'])
  835. #lastQuotedict['lastQuote_bid_price'].append(sub['lastQuote']['p'])
  836. #lastQuotedict['lastQuote_bid_size'].append(sub['lastQuote']['s'])
  837. #lastQuotedict['lastQuote_timestamp'].append(sub['lastQuote']['t'])
  838.  
  839. #lastTradedict['lastTrade_close'].append(sub['lastTrade']['c'])
  840. #lastTradedict['lastTrade_trade_id'].append(sub['lastTrade']['i'])
  841. #lastTradedict['lastTrade_price'].append(sub['lastTrade']['p'])
  842. #lastTradedict['lastTrade_size'].append(sub['lastTrade']['s'])
  843. #lastTradedict['lastTrade_time'].append(sub['lastTrade']['t'])
  844. #lastTradedict['lastTrade_exch_id'].append(sub['lastTrade']['x'])
  845.  
  846.  
  847. #minuteBardict['minuteBar_total_volume'].append(sub['min']['av'])
  848. #minuteBardict['minuteBar_close'].append(sub['min']['c'])
  849. #minuteBardict['minuteBar_high'].append(sub['min']['h'])
  850. #minuteBardict['minuteBar_low'].append(sub['min']['l'])
  851. #minuteBardict['minuteBar_open'].append(sub['min']['o'])
  852. #minuteBardict['minuteBar_volume'].append(sub['min']['v'])
  853. #minuteBardict['minuteBar_vwap'].append(sub['min']['vw'])
  854.  
  855.  
  856.  
  857. #prevDaydict['prevDay_close'].append(sub['prevDay']['c'])
  858. #prevDaydict['prevDay_high'].append(sub['prevDay']['h'])
  859. #prevDaydict['prevDay_low'].append(sub['prevDay']['l'])
  860. #prevDaydict['prevDay_open'].append(sub['prevDay']['o'])
  861. #prevDaydict['prevDay_volume'].append(sub['prevDay']['v'])
  862. #prevDaydict['prevDay_vwwap'].append(sub['prevDay']['vw'])
  863.  
  864.  
  865. #ticker = sub['ticker']
  866. #todaysChange = sub['todaysChange']
  867. #todaysChangePerc = sub['todaysChangePerc']
  868. #updated = sub['updated']
  869.  
  870. #d4 = dict(daydict.items() + lastQuotedict.items() + lastTradedict.items() + minuteBardict.items() + prevDaydict.items())
  871. d4 = dict(**daydict, **lastQuotedict, **lastTradedict, **minuteBardict, **prevDaydict)
  872. #print('i', i)
  873. #pprint.pprint(d4)
  874.  
  875. #for single_dict in d4:
  876. # global_dict.update(single_dict)
  877.  
  878. #print(' ************** ')
  879. #pprint.pprint(joined_dict)
  880. #joined_dict.update(d4)
  881. #joined_dict.merge(d4)
  882. #joined_dict = joined_dict | d4
  883.  
  884. #for key, value in d4.items():
  885. # joined_dict[key] = value
  886.  
  887. #joined_dict[i] = d4
  888. #joined_dict[i] = dict(d4)
  889. #joined_dict[i] = [d4]
  890. joined_dict[sub['ticker']] = d4
  891.  
  892. #print(datetime.today())
  893. #joined_dict.update(d4)
  894. #big_df = big_df.append(d4, ignore_index=True, sort=False)
  895.  
  896. #threading.Thread(target=big_df.append(d4, ignore_index=True, sort=False), args=[]).start()
  897.  
  898. #joined_dict = dict(joined_dict, **d4)
  899. #print(' --------------- ')
  900. #pprint.pprint(joined_dict)
  901. #for dictionary in d4:
  902. # joined_dict.update(dictionary)
  903. #joined_dict.append(d4, ignore_index=True)
  904. #joined_dict = joined_dict | d4
  905. #joined_dict.append(d4)
  906. #joined_df = pd.DataFrame.from_dict(d4)
  907. #big_df = dict(**d4, **big_df)
  908. i += 1
  909. #big_df = pd.DataFrame.from_dict(d4)
  910. #big_df = pd.DataFrame.from_dict(joined_dict)
  911. #print(datetime.today())
  912. #print(i)
  913. #print(d4)
  914. #big_df = pd.DataFrame.from_dict(joined_dict)
  915. #pprint.pprint(len(joined_dict))
  916. #pprint.pprint(joined_dict)
  917. #big_df = big_df.append(d4, ignore_index=True, sort=False)
  918. #pprint.pprint(joined_dict)
  919. #pprint.pprint(len(joined_dict))
  920. #print(len(big_df))
  921. #print(big_df)
  922. #pprint.pprint(joined_dict)
  923. big_df = pd.DataFrame.from_dict(joined_dict)
  924. big_df = big_df.T
  925. big_df.sort_values(by=['todaysChangePerc'], inplace=True, ascending=False)
  926. #pprint.pprint(big_df)
  927. #big_df.T.to_csv('snapshot1.csv')
  928. #big_df = big_df.append(joined_dict, ignore_index=True, sort=False)
  929. #big_df = big_df.append(d4, ignore_index=True, sort=False)
  930. ####big_df = big_df.T
  931. #print(len(big_df))
  932. #print(len(joined_dict))
  933. ####pprint.pprint(big_df)
  934. #results_dict = {}
  935. #results_dict['results'] = sorted(joined_dict, key='symbol')
  936. #results_dict['results'] = sorted(joined_dict.items(), key = lambda kv:(kv[1], kv[0]))
  937.  
  938. #print(results_dict)
  939. #redis_message('stock_snapshot', joined_dict)
  940. redis_dict_update(big_df)
  941. #redis_dict_update(joined_dict)
  942. #print(datetime.today())
  943. print(datetime.today() - z)
  944. #big_df.to_csv('c://Downloads//big_df.csv')
  945. #big_df.to_csv('big_df.csv')
  946. #return big_df
  947.  
  948. return None
  949. #print(z - time.localtime())
  950.  
  951. if len(big_df) > 0:
  952. #df = df[['t', 'y', 'q', 'c', 'p', 's', 'x', 'P', 'S', 'X', 'z']]
  953. #df.columns = ['sip_timestamp', 'participant_timestamp', 'sequence_number', 'conditions', 'bid_price', 'bid_size', 'bid_exchange',
  954. # 'ask_price', 'ask_size', 'ask_exchange', 'tape']
  955. #pass
  956. #else:
  957. # df.insert(1, 'a', None)
  958. # df.insert(9, 'op', None)
  959. # df = df[['v', 'a', 'vw', 'o', 'c', 'h', 'l', 't', 'n', 'op']]
  960.  
  961. #df.columns = ['conditions', 'id', 'price', 'sequence_number',
  962. # 'size', 'sip_timestamp', 'exchange', 'participant_timestamp', 'tape']
  963. #df.insert(0, 'symbol', symbol)
  964. #df.insert(3, 'total_volume', None)
  965. #df.insert(3, 'vwap', None)
  966. #df.insert(3, 'avg_trade_size', None)
  967. #df.insert(3, 'time_beg', None)
  968. #df.drop('a', axis=1, inplace=True)
  969. #df.drop('n', axis=1, inplace=True)
  970. #print(df['sip_timestamp'])
  971.  
  972. #if len(str(df['sip_timestamp'])) == 13:
  973. #big_df['t_lastTrade'] = big_df['lasttrade_sip_timestamp'].map(lambda x: unix_convert(x))
  974. #big_df['save_date'] = datetime.utcnow()
  975. #df = df[['symbol', 'sip_timestamp', 'participant_timestamp', 'sequence_number', 'conditions', 'bid_price', 'bid_size', 'bid_exchange',
  976. # 'ask_price', 'ask_size', 'ask_exchange', 'tape', 'tdate', 'save_date']]
  977. #pprint.pprint(df)
  978. #else:
  979. # print('its empty quotes ', requestdate, ' ', symbol)
  980.  
  981. #if len(df) > 0:
  982. pprint.pprint(len(big_df))
  983. pprint.pprint(big_df[:10])
  984.  
  985. else:
  986. df=None
  987. big_df=None
  988. # if symbols is not None:
  989. # for symbol in symbols:
  990. # big_df = pd.DataFrame()
  991. # doc = s.get_daily_open_close(symbol, requestdate='2021-11-05', adjusted=True)
  992. # #doc = s.get_daily_open_close(symbol, requestdate=date.today(), adjusted=True)
  993. # lastquote = s.get_last_quote(symbol)
  994. # lasttrade = s.get_last_trade(symbol)
  995. # minuteBar = s.get_aggregate_bars(symbol, startdate='2021-11-04', enddate='2021-11-04', limit=1, sort='desc')
  996. # prevDay = s.get_previous_close(symbol)
  997.  
  998. # #pprint.pprint('\ndaily open close = ')
  999. # #pprint.pprint(doc)
  1000. # #pprint.pprint('\nlastquote = ')
  1001. # #pprint.pprint(lastquote)
  1002. # #pprint.pprint('\nlasttrade = ')
  1003. # #pprint.pprint(lasttrade)
  1004. # #pprint.pprint('\nminuteBar = ')
  1005. # #pprint.pprint(minuteBar)
  1006. # #pprint.pprint('\nprevDay = ')
  1007. # #pprint.pprint(prevDay)
  1008.  
  1009. # #print(doc)
  1010.  
  1011.  
  1012. # #daydict = doc.to_dict()
  1013. # #print(daydict)
  1014. # #pd_day = pd.DataFrame.from_dict(doc, orient='columns')
  1015. # pd_day = pd.DataFrame(doc, index=[3])#, orient='columns', columns=['status', 'from', 'symbol', 'open', 'high', 'low', 'close', 'volume', 'afterHours', 'preMarket'])
  1016. # #pd_day.columns = ['status', 'from', 'symbol', 'open', 'high', 'low', 'close', 'volume', 'afterHours', 'preMarket']
  1017. # #pd_day.insert(0, 'symbol', ticker)
  1018. # #pd_day = pd_day.set_index('symbol')
  1019. # #pd_day.index = 'symbol'
  1020. # #pprint.pprint(pd_day)
  1021.  
  1022. # print(' ')
  1023. # #print(lastquote['results'])
  1024. # pd_lastQuote = pd.DataFrame(lastquote['results'], index=[9])
  1025. # #pd_lastQuote.columns = ['P', 'S', 'T', 'X', 'p', 'q', 's', 't', 'x', 'y', 'z']
  1026. # #pd_lastQuote.columns = ['ask', 'ask_size', 'symbol', 'ask_exch_id', 'bid', 'sequence_number', 'bid_size',
  1027. # # 'sip_timestamp', 'bid_exch_id', 'participant_timestamp', 'tape']
  1028. # pd_lastQuote.rename(columns={'P': 'lastquote_ask', 'S': 'lastquote_ask_size', 'T': 'symbol', 'X': 'lastquote_ask_exch_id',
  1029. # 'p': 'lastquote_bid', 'q': 'lastquote_sequence_number',
  1030. # 's': 'lastquote_bid_size', 't': 'lastquote_sip_timestamp', 'x': 'lastquote_bid_exch_id',
  1031. # 'y': 'lastquote_participant_timestamp', 'z': 'lastquote_tape'},
  1032. # errors="raise", inplace = True)
  1033. # #pd_lastQuote.insert(0, 'symbol', ticker)
  1034. # #pprint.pprint(pd_lastQuote)
  1035.  
  1036. # print(' ')
  1037. # #print(lasttrade['results'])
  1038. # lasttrade['results']['c'] = [lasttrade['results']['c']]
  1039. # pd_lastTrade = pd.DataFrame(lasttrade['results'])#, index=[7])
  1040. # pd_lastTrade.rename(columns={'c': 'lasttrade_conditions', 'p': 'lasttrade_price', 's': 'lasttrade_size', 'x': 'lasttrade_exch_id',
  1041. # 'z': 'tape', 'T': 'symbol',
  1042. # 't': 'lasttrade_sip_timestamp', 'y': 'lasttrade_participant_timestamp', 'q': 'lasttrade_sequence_number'},
  1043. # errors="raise", inplace = True)
  1044. # pd_lastTrade = pd_lastTrade.set_index('symbol')
  1045. # #pd_lastTrade = pd_lastTrade.groupby('symbol')
  1046. # ##pd_lastTrade.columns = ['conditions', 'trade_id', 'price', 'size', 't_trade', 'exch_id']
  1047. # ##pd_lastTrade.insert(0, 'symbol', ticker)
  1048. # #pprint.pprint(pd_lastTrade)
  1049.  
  1050. # #print(' ')
  1051. # #print(minuteBar['results'])
  1052. # pd_minuteBar = pd.DataFrame(minuteBar['results'])#, index=[3])
  1053. # pd_minuteBar.rename(columns={'v': 'minuteBar_volume', 'vw': 'minuteBar_vwap', 'a': 'minuteBar_adjusted_price',
  1054. # 'o': 'minuteBar_open', 'c': 'minuteBar_close', 'h': 'minuteBar_high',
  1055. # 'l': 'minuteBar_low', 't': 'minuteBar_sip_timestamp', 'n': 'minuteBar_transaction_count'},
  1056. # errors="raise", inplace = True)
  1057. # ##pd_minuteBar.columns = ['accumulated_volume', 'close', 'high', 'low', 'open', 'volume', 'vwap']
  1058. # pd_minuteBar.insert(0, 'symbol', minuteBar['ticker'])
  1059. # pd_minuteBar = pd_minuteBar.set_index('symbol')
  1060. # #pprint.pprint(pd_minuteBar)
  1061.  
  1062. # #print(' ')
  1063. # #print(prevDay['results'])
  1064. # pd_prevDaydict = pd.DataFrame(prevDay['results'])#, index=[3])
  1065. # pd_prevDaydict.rename(columns={'T': 'symbol', 'v': 'prev_volume', 'vw': 'prev_vwap', 'o': 'prev_open', 'c': 'prev_close', 'h': 'prev_high',
  1066. # 'l': 'prev_low', 't': 'prev_sip_timestamp', 'n': 'prev_transaction_count'},
  1067. # errors="raise", inplace = True)
  1068. # ##pd_prevDaydict.columns = ['close', 'high', 'low', 'open', 'volume', 'vwap']
  1069. # ##pd_prevDaydict.insert(0, 'symbol', ticker)
  1070. # pd_prevDaydict = pd_prevDaydict.set_index('symbol')
  1071. # #pprint.pprint(pd_prevDaydict)
  1072.  
  1073.  
  1074. # #print(pd_day)
  1075. # #print(pd_lastQuote)
  1076. # #print(pd_lastTrade)
  1077. # #print(pd_minuteBar)
  1078. # #print(pd_prevDaydict)
  1079. # #print(' ')
  1080. # #print(' ')
  1081. # #print(' ')
  1082.  
  1083.  
  1084. ##pd_day = pd.DataFrame.from_dict(daydict)2
  1085. ##pd_day = pd.DataFrame.from_dict(daydict)
  1086.  
  1087. # #big_df = pd.
  1088.  
  1089. # big_df = pd.merge(pd_day, pd_lastQuote, on='symbol', how='inner')#, suffixes=('_day', '_quote'))#, left_suffix='_day', right_suffix='_minuteBar')
  1090. # big_df = pd.merge(big_df, pd_lastTrade, on='symbol', how='inner')#, suffixes=('_quote', '_trade'))
  1091. # #big_df = pd.merge(big_df, pd_lastQuote, on='symbol', how='inner', suffixes=('_trade', '_quote'))
  1092. # big_df = pd.merge(big_df, pd_minuteBar, on='symbol', how='inner')#, suffixes=('_trade', '_min'))
  1093. # #big_df.join(pd_minuteBar, on='symbol', lsuffix='_day', rsuffix='_minuteBar', inplace=True)
  1094. # big_df = pd.merge(big_df, pd_prevDaydict, on='symbol', how='inner')#, suffixes=('_min', '_prev'))
  1095.  
  1096.  
  1097. # big_df.insert(3, 'per_chng', (big_df['close'] / big_df['prev_close']) * 100)
  1098. ##frames = [pd_day, pd_lastQuote, pd_lastTrade, pd_lastQuote, pd_minuteBar, pd_prevDaydict]
  1099.  
  1100. ##big_df = pd.concat(frames, axis=1, ignore_index=True)#join="inner")#.reindex(pd_day.index)
  1101.  
  1102. # print(' ')
  1103. # print(' ')
  1104. # print('big_df = ')
  1105. # print(' ')
  1106. # #pprint.pprint(big_df)
  1107. # print(big_df)
  1108. # print(' ')
  1109.  
  1110. if big_df is not None:
  1111. return big_df
  1112. else:
  1113. print('market closed')
  1114. time.sleep(10)
  1115. get_stocks_snapshot()
  1116.  
  1117. except Exception as exe:
  1118. print(exe)
  1119. traceback.print_exc()
  1120. time.sleep(10)
  1121. df = None
  1122. big_df=None
  1123. return df
  1124.  
  1125.  
  1126. def get_historic_stock_daily_open_close(symbol, requestdate, adjusted=False):
  1127. try:
  1128. #pg_client = Historical_Data()
  1129. s = stocks.StocksPolygon
  1130.  
  1131. #endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
  1132. #resp = pg_client.get_response(
  1133. # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
  1134. resp = s.get_daily_open_close(symbol, requestdate=requestdate, adjusted=adjusted)
  1135. #print('resp=')
  1136. #print(resp)
  1137. #if resp == 'results' or resp == 'message':
  1138. if resp['status'] == 'OK':
  1139. #df = pd.DataFrame.from_dict(resp, index=False)
  1140. big_dict = []
  1141. resp2 = dict(resp)
  1142. dict_keys = resp2.keys()
  1143. for k in list(dict_keys):
  1144. val = resp2[k]#.keys()
  1145. print(k, '=', val, '\n')
  1146. #for st in list(val):
  1147. # print(st)
  1148. #df = pd.DataFrame.from_dict(resp['results'])
  1149. #return
  1150. #if 'a' in df.columns:
  1151. if len(resp) > 0:
  1152. #df = resp[['afterHours', 'close', 'from', 'high', 'low', 'open', 'preMarket', 'symbol', 'volume']]
  1153. ###pass
  1154. #else:
  1155. #df.insert(1, 'a', None)
  1156. #df.insert(9, 'op', None)
  1157. #df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't', 'n',]]
  1158. #df = pd.DataFrame.from_dict(resp2, index=False)
  1159. df = pd.DataFrame.from_dict(resp['results'])
  1160. df.columns = ['afterHours', 'close', 'from', 'high', 'low', 'open', 'preMarket', 'symbol', 'volume']
  1161. #df.insert(0, 'symbol', symbol)
  1162. #df.insert(1, 'frequency', str(multiplier) + timespan)
  1163. #df.insert(3, 'total_volume', None)
  1164. #df.insert(3, 'vwap', None)
  1165. #df.insert(3, 'avg_trade_size', None)
  1166. #df.insert(3, 'time_beg', None)
  1167. #df.drop('a', axis=1, inplace=True)
  1168. #df.drop('n', axis=1, inplace=True)
  1169. #df['tdate'] = df['timestamp'].map(lambda x: unix_convert(x))
  1170. df['save_date'] = datetime.utcnow()
  1171. #df = df[['symbol', 'volume', 'open', 'close', 'high', 'low', 'vwap', 'timestamp', 'tdate', 'save_date']]
  1172. df = df[['afterHours', 'close', 'from', 'high', 'low', 'open', 'preMarket', 'symbol', 'volume', 'save_date']]
  1173. #else:
  1174. # print('its empty bars ', start_date, ' ', end_date, symbol)
  1175. else:
  1176. df=None
  1177. else:
  1178. df = None
  1179. except Exception as exe:
  1180. print(exe)
  1181. traceback.print_exc()
  1182. time.sleep(10)
  1183. df = None
  1184. return df['results']
  1185.  
  1186. def get_historic_option_trades(symbol, requestdate, adjusted=False):
  1187. try:
  1188. o = options.OptionsPolygon
  1189. resp = o.get_option_trades(symbol, requestdate=requestdate, limit=50000)
  1190. if resp is not None:
  1191. if 'results' in resp:
  1192. df = pd.DataFrame.from_dict(resp['results'])
  1193. if df is not None and df.empty != True:
  1194.  
  1195. df.columns = ['conditions', 'exchange', 'participant_timestamp', 'price', 'sip_timestamp', 'size']
  1196. #df.columns = ['conditions', 'exchange', 'price', 'sequence_number', 'sip_timestamp', 'size']
  1197. polygon_option_symbol = symbol
  1198. option_numbers = re.findall(r'\d+', polygon_option_symbol)
  1199. underlying_symbol = polygon_option_symbol[:polygon_option_symbol.index(option_numbers[0])]
  1200.  
  1201. option_type = str(polygon_option_symbol[polygon_option_symbol.index(option_numbers[1]) - 1:])[:1]
  1202.  
  1203. option_expiration = str(option_numbers[0])
  1204. #rint(df['price'])
  1205. option_strike = str(option_numbers[1])
  1206. #del df['sequence_number']
  1207. df.insert(0, 'symbol', symbol)
  1208. df.insert(1, 'underlying_symbol', underlying_symbol)
  1209. df.insert(2, 'option_type', option_type)
  1210. df.insert(3, 'option_expiration', option_expiration)
  1211. df.insert(4, 'option_strike', int(option_strike)/1000)
  1212.  
  1213. df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
  1214. df['save_date'] = datetime.utcnow()
  1215. #df = df[['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'sequence_number', 'size',
  1216. df = df[['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
  1217. 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']]
  1218.  
  1219. #return df.to_json(orient='records')[1:-1].replace('},{', '} {')
  1220.  
  1221. else:
  1222. df=None
  1223. else:
  1224. df = None
  1225. else:
  1226. df = None
  1227. except Exception as exe:
  1228. print(exe)
  1229. traceback.print_exc()
  1230. time.sleep(10)
  1231. df = None
  1232. return df
  1233.  
  1234.  
  1235. def get_conditions():
  1236. try:
  1237. #pg_client = Historical_Data()
  1238. #s = stocks.StocksPolygon
  1239.  
  1240. r = reference.ReferencePolygon
  1241. #from_date = '2021-10-26'
  1242. resp = r.get_conditions_vX()
  1243.  
  1244.  
  1245. if 'results' in resp:
  1246.  
  1247. messages = dict(resp)
  1248. cur = conn.cursor()
  1249. sio = io.StringIO()
  1250. writer = csv.writer(sio)
  1251. values = [message for message in messages]
  1252. #values = [[value for value in message.values()] for message in messages]
  1253. writer.writerows(values)
  1254. cols = ['abbreviation', 'asset_class', 'data_types', 'description', 'id', 'name', 'sip_mapping', 'type', 'update_rules']
  1255. #cols = ['symbol', 'tick_volume', 'total_volume', 'opening_price', 'tick_vwap', 'tick_open', 'tick_close',
  1256. # 'tick_high', 'tick_low', 'vwap', 'avg_trade_size', 'time_beg', 'time_end', 'tdate', 'save_date']
  1257. sio.seek(0)
  1258. cur.copy_from(file=sio, table="reference_conditions", sep=",", columns=cols, null='')
  1259. cur.close()
  1260.  
  1261. return
  1262.  
  1263. if 'results' in resp:
  1264. df = pd.DataFrame.from_dict(resp['results'])
  1265. if df is not None:
  1266. #print('writing to quotes ->' + str(len(temp_df)))
  1267. #df = pd.DataFrame.from_dict(dict(resp))
  1268. pprint.pprint(df)
  1269. #return
  1270. df = df[['abbreviation', 'asset_class', 'data_types', 'description', 'id', 'name', 'sip_mapping', 'type', 'update_rules']]#, 'consolidated', 'market_center']]
  1271. #df = df[['conditions', 'exchange', 'participant_timestamp', 'price', 'sip_timestamp', 'size']]
  1272. ###pass
  1273. #else:
  1274. #df.insert(1, 'a', None)
  1275. #df.insert(9, 'op', None)
  1276. #df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't', 'n',]]
  1277.  
  1278. df.columns = ['abbreviation', 'asset_class', 'data_types', 'description', 'id', 'name', 'sip_mapping', 'type', 'update_rules']#, 'consolidated', 'market_center']
  1279. #df.insert(0, 'symbol', symbol)
  1280. #df.insert(1, 'frequency', str(multiplier) + timespan)
  1281. #df.insert(3, 'total_volume', None)
  1282. #df.insert(3, 'vwap', None)
  1283. #df.insert(3, 'avg_trade_size', None)
  1284. #df.insert(3, 'time_beg', None)
  1285. #df.drop('a', axis=1, inplace=True)
  1286. #df.drop('n', axis=1, inplace=True)
  1287. #df['tdate'] = df['timestamp'].map(lambda x: unix_convert(x))
  1288. #df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
  1289. #df['save_date'] = datetime.utcnow()
  1290. #df = df[['symbol', 'volume', 'open', 'close', 'high', 'low', 'vwap', 'timestamp', 'tdate', 'save_date']]
  1291. df = df[['abbreviation', 'asset_class', 'data_types', 'description', 'id', 'name', 'sip_mapping', 'type', 'update_rules']]#, 'consolidated', 'market_center']]
  1292. df.to_sql('reference_conditions', engine, if_exists='append', index=False, method='multi')
  1293.  
  1294. else:
  1295. df=None
  1296. else:
  1297. df = None
  1298. except Exception as exe:
  1299. print(exe)
  1300. traceback.print_exc()
  1301. time.sleep(10)
  1302. df = None
  1303. return df
  1304.  
  1305.  
  1306. #async def get_historic_data_base(symbols, data_type: DataType, start, end,
  1307. #
  1308. #def get_bars(symbol, to_sql:bool=True):
  1309. def get_bars(symbol, start_date='2021, 11, 12', end_date='2021, 11, 12', adjusted=True, sort='asc', limit=50000, multiplier=1, timespan='minute'):
  1310. try:
  1311. global bars_df
  1312. #start_time2 = time.time()
  1313. # Date Info
  1314. #from_date = '2021-11-08'
  1315. #from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
  1316. #to_date = datetime.today().date() + timedelta(days=1)
  1317. ## Transform Dates
  1318. #temp_date_start = to_date - timedelta(days=60)
  1319. #temp_date_end = to_date
  1320. #print(f'getting data for {symbol}')
  1321.  
  1322.  
  1323. start_date = date(2021, 11, 12)
  1324. end_date = date(2021, 11, 12)
  1325. #delta = timedelta(days=1)
  1326.  
  1327.  
  1328. #while start_date <= end_date:
  1329. #print(symbol, start_date)
  1330. #future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
  1331. #future1 = executor.submit(get_bars, symbol)
  1332. #future2 = executor.submit(get_trades, symbol)
  1333. #future3 = executor.submit(get_quotes, symbol)
  1334. #future4 = executor.submit(get_daily_stock_open_close, symbol)
  1335. #temp_df = get_historic_trades(symbol=symbol, requestdate=temp_date_start, limit=50000)
  1336. temp_df = get_historic_bars(symbol, start_date, end_date, adjusted=True, sort='desc', limit=50000, multiplier=1, timespan='minute')
  1337. #start_date += delta
  1338.  
  1339. #while temp_date_start > from_date:
  1340. # start_time2 = time.time()
  1341. # temp_df = get_historic_bars(symbol, temp_date_start, temp_date_end)
  1342. # #print('thread 1', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
  1343. # #print(time.time() - start_time2, '\n')
  1344. # #print('thread 1', '\n', temp_df)
  1345. # temp_date_end = temp_date_end - timedelta(days=60)
  1346. # temp_date_start = temp_date_start - timedelta(days=60)
  1347. #if isinstance(type(temp_df), str):
  1348. # break
  1349. #else:
  1350. # Add df to database
  1351. #print(temp_df)
  1352. start_time2 = time.time()
  1353. to_sql = True
  1354. #if temp_df is not None or len(temp_df) > 0:
  1355. if temp_df is not None:
  1356. if to_sql == True:
  1357. print('writing to bars ->' + str(len(temp_df)))
  1358. temp_df.to_sql('stockdata_hist_bars', engine, if_exists='append', index=False, method='multi')
  1359. #time.sleep(0.1)
  1360. else:
  1361. #pprint.pprint(temp_df)
  1362. #bars_df.append(temp_df, ignore_index=True)
  1363. frames = [bars_df, temp_df]
  1364. bars_df = pd.concat(frames)
  1365. #print(bars_df)
  1366. #print(len(bars_df))
  1367. #bars_df
  1368. #print(temp_df)
  1369. temp_df=None
  1370.  
  1371. #print(time.time() - start_time2)
  1372. except Exception as exe:
  1373. print(exe)
  1374. traceback.print_exc()
  1375. time.sleep(10)
  1376. df = None
  1377. #return temp_df
  1378.  
  1379. def get_latest_bar(symbol, timespan='minute'):
  1380. try:
  1381. global latest_min_bar_df
  1382. #start_time2 = time.time()
  1383. # Date Info
  1384. #from_date = '2021-11-08'
  1385. #from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
  1386. #to_date = datetime.today().date() + timedelta(days=1)
  1387. ## Transform Dates
  1388. #temp_date_start = to_date - timedelta(days=60)
  1389. #temp_date_end = to_date
  1390. #print(f'getting data for {symbol}')
  1391.  
  1392.  
  1393. #start_date = date(2021, 11, 11)
  1394. #end_date = date(2021, 11, 11)
  1395. #delta = timedelta(days=1)
  1396.  
  1397.  
  1398. #while start_date <= end_date:
  1399. #print(symbol, start_date)
  1400. #future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
  1401. #future1 = executor.submit(get_bars, symbol)
  1402. #future2 = executor.submit(get_trades, symbol)
  1403. #future3 = executor.submit(get_quotes, symbol)
  1404. #future4 = executor.submit(get_daily_stock_open_close, symbol)
  1405. #temp_df = get_historic_trades(symbol=symbol, requestdate=temp_date_start, limit=50000)
  1406. temp_df = get_last_bar(symbol, timespan='minute')
  1407. #start_date += delta
  1408.  
  1409. #while temp_date_start > from_date:
  1410. # start_time2 = time.time()
  1411. # temp_df = get_historic_bars(symbol, temp_date_start, temp_date_end)
  1412. # #print('thread 1', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
  1413. # #print(time.time() - start_time2, '\n')
  1414. # #print('thread 1', '\n', temp_df)
  1415. # temp_date_end = temp_date_end - timedelta(days=60)
  1416. # temp_date_start = temp_date_start - timedelta(days=60)
  1417. #if isinstance(type(temp_df), str):
  1418. # break
  1419. #else:
  1420. # Add df to database
  1421. #print(temp_df)
  1422. start_time2 = time.time()
  1423. to_sql = False
  1424. #if temp_df is not None or len(temp_df) > 0:
  1425. if temp_df is not None:
  1426. if to_sql == True:
  1427. print('writing to bars ->' + str(len(temp_df)))
  1428. temp_df.to_sql('stockdata_hist_bars', engine, if_exists='append', index=False, method='multi')
  1429. time.sleep(0.1)
  1430. else:
  1431. #pprint.pprint(temp_df)
  1432. #bars_df.append(temp_df, ignore_index=True)
  1433. frames = [latest_min_bar_df, temp_df]
  1434. latest_min_bar_df = pd.concat(frames)
  1435. #print(bars_df)
  1436. #print(len(bars_df))
  1437. #bars_df
  1438. #print(temp_df)
  1439. temp_df=None
  1440.  
  1441. #print(time.time() - start_time2)
  1442. except Exception as exe:
  1443. print(exe)
  1444. traceback.print_exc()
  1445. time.sleep(10)
  1446. df = None
  1447. #return temp_df
  1448.  
  1449. def get_trades(symbol):
  1450. try:
  1451. #start_time2 = time.time()
  1452. conn = postgreSQL_pool.getconn()
  1453. # code that uses a connection
  1454. postgreSQL_pool.putconn(conn)
  1455.  
  1456. # Date Info
  1457. #from_date = '2021-01-01'
  1458. #from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
  1459. #to_date = datetime.today().date() + timedelta(days=1)
  1460. ## Transform Dates
  1461. #temp_date_start = to_date - timedelta(days=60)
  1462. #temp_date_end = to_date
  1463. ##print(f'getting data for {symbol}')
  1464. #while temp_date_start > from_date:
  1465. start_date = date(2021, 10, 25)
  1466. end_date = date(2021, 10, 29)
  1467. delta = timedelta(days=1)
  1468. get_bars(symbol)
  1469.  
  1470. while start_date <= end_date:
  1471. print(symbol, start_date)
  1472. future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
  1473. #future1 = executor.submit(get_bars, symbol)
  1474. #future2 = executor.submit(get_trades, symbol)
  1475. #future3 = executor.submit(get_quotes, symbol)
  1476. #future4 = executor.submit(get_daily_stock_open_close, symbol)
  1477. temp_df = get_historic_trades(symbol=symbol, requestdate=temp_date_start, limit=50000)
  1478. start_date += delta
  1479. start_time2 = time.time()
  1480. #temp_df = get_historic_trades(symbol=symbol, requestdate=temp_date_start, limit=50000)
  1481. #print('thread 2', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
  1482. #print(time.time() - start_time2, '\n')
  1483. #print('thread 2', '\n', temp_df)
  1484. #temp_date_end = temp_date_end - timedelta(days=60)
  1485. #temp_date_start = temp_date_start - timedelta(days=60)
  1486. if isinstance(type(temp_df), str):
  1487. return
  1488. #else:
  1489. # Add df to database
  1490. #print(temp_df)
  1491. #print('thread 2', '\n', temp_df)
  1492. #print('thread2')
  1493. if temp_df is not None or len(temp_df) > 0:
  1494. #print('writing to trades ->' + str(len(temp_df)))
  1495. temp_df.to_sql('stockdata_hist_trades', engine, if_exists='append', index=False, method='multi')
  1496. time.sleep(0.1)
  1497. temp_df=None
  1498.  
  1499. #print(time.time() - start_time2)
  1500. except Exception as exe:
  1501. print(exe)
  1502. traceback.print_exc()
  1503. time.sleep(10)
  1504. df = None
  1505. #print(time.time() - start_time2)
  1506.  
  1507. def get_quotes(symbol, requestdata):
  1508. try:
  1509. #start_time2 = time.time()
  1510. # Date Info
  1511. #from_date = '2021-01-01'
  1512. #from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
  1513. #to_date = datetime.today().date() + timedelta(days=1)
  1514. ## Transform Dates
  1515. #temp_date_start = to_date - timedelta(days=60)
  1516. #temp_date_end = to_date
  1517. ##print(f'getting data for {symbol}')
  1518. #while temp_date_start > from_date:
  1519. start_time2 = time.time()
  1520. temp_df = get_historic_quotes(symbol, requestdate=requestdata, limit=50000)
  1521. #print('thread 3', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
  1522. #print(time.time() - start_time2, '\n')
  1523. #print('thread 3', '\n', temp_df)
  1524. temp_date_end = temp_date_end - timedelta(days=60)
  1525. temp_date_start = temp_date_start - timedelta(days=2)
  1526. if isinstance(type(temp_df), str):
  1527. return
  1528. #else:
  1529. # Add df to database
  1530. #print(temp_df)
  1531. if temp_df is not None or len(temp_df) > 0:
  1532. #print('writing to quotes ->' + str(len(temp_df)))
  1533. temp_df.to_sql('stocksdata_hist_quotes', engine, if_exists='append', index=False, method='multi')
  1534. time.sleep(0.1)
  1535. temp_df=None
  1536.  
  1537. except Exception as exe:
  1538. print(exe)
  1539. traceback.print_exc()
  1540. time.sleep(10)
  1541. df = None
  1542. #print(time.time() - start_time2)
  1543.  
  1544. #stocks
  1545. def save_stock_ticks_to_redis(message):
  1546. try:
  1547. z = time.time()
  1548. keys = {'sym': 'symbol', 'x': 'exch_id', 'i': 'trade_id', 'z': 'tape', 'p': 'price', 's': 'trade_size', 'c': 'conditions', 't': 'trade_time'}
  1549. new_message = []
  1550. global stock_ticks_df
  1551.  
  1552. cst = pytz.timezone('US/Central')
  1553. #dst = pytz.timezone('America/Chicago')
  1554. UTC = pytz.utc
  1555. dt = datetime.now(cst)
  1556.  
  1557.  
  1558.  
  1559. l = ['sym', 'x', 'i', 'z', 'p', 's', 'c','t']
  1560. for d in message:
  1561. del d['ev'] # delete status
  1562. f = set(l) - d.keys() # Compare response with expected response
  1563. g = {k: 'NULL' for k in f} # Fill any blanks
  1564. d.update(g) # Update dict
  1565.  
  1566. d = {keys[name]: val for name, val in d.items()}
  1567.  
  1568. d['tdate'] = unix_convert(d['trade_time'])
  1569. #print('tdate=',d['tdate'])
  1570. #print('trade_time=',d['trade_time'])
  1571. #print(' ')
  1572. d['save_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  1573. cols = ['symbol', 'exch_id', 'trade_id', 'tape', 'price', 'trade_size', 'conditions', 'trade_time',
  1574. 'tdate', 'save_date']
  1575. #print(d)
  1576. d = {k: d[k] for k in cols}
  1577. new_message.append(d)
  1578. stock_ticks_df = stock_ticks_df.append(pd.DataFrame(new_message), ignore_index=True)
  1579. #df.to_csv('test3.csv')
  1580. #df.to_sql('stocksdata_trades', engine, if_exists='append', index=False, method='multi')
  1581. #redis_message(new_message)
  1582. #print(new_message)
  1583. #print(time.time()-z)
  1584. except Exception:
  1585. traceback.print_exc()
  1586. return None
  1587.  
  1588. def aggregate_candles(ticker: str, message, resolution: int = 1):
  1589. trade = message
  1590. struct = AGGREGATES[ticker]
  1591.  
  1592. # THE AGGREGATION
  1593. AGGREGATES[ticker]['open'] = struct['open'] if struct['open'] else trade['timestamp']
  1594. AGGREGATES[ticker]['close'] = trade['price']
  1595.  
  1596. AGGREGATES[ticker]['high'] = max(struct['high'], trade['price'])
  1597. AGGREGATES[ticker]['low'] = min(struct['low'], trade['price'])
  1598.  
  1599. AGGREGATES[ticker]['volume'] = struct['volume'] + trade['trade_size']
  1600. AGGREGATES[ticker]['timestamp'] = trade['timestamp']
  1601.  
  1602. if int(trade['t']) == int(struct['end']):
  1603. print(f'{ticker}: aggregated candle formed. Reached end of current timeframe...')
  1604. _struct = AGGREGATES[ticker]
  1605.  
  1606. # resetting struct for the ticker for next aggregation cycle time frame
  1607. AGGREGATES[ticker] = {'ticker': ticker, 'res': resolution, 'low': float('inf'), 'high': 0,
  1608. 'close': None, 'open': None, 'timestamp': None,
  1609. 'volume': 0, 'start': struct['end'],
  1610. 'end': struct['end'] + datetime.timedelta(minutes=resolution)}
  1611.  
  1612. return parse_struct(_struct)
  1613.  
  1614. elif int(trade['t']) < int(struct['end']):
  1615. print(f'{ticker}: timeframe end not reached yet. Candle aggregated...')
  1616. return False
  1617.  
  1618. else:
  1619. print(f'{ticker}: received timestamp: {int(trade["t"])} || end timestamp: {int(struct["end"])}')
  1620. return False
  1621.  
  1622.  
  1623. #columns in data frame
  1624. df_cols = ["symbol", "open", "high", "low", "close", "volume", "timestamp_tick"]
  1625.  
  1626. data_frame = pd.DataFrame(data=[],columns=df_cols, index=[])
  1627.  
  1628. def on_tick(message):
  1629.  
  1630. try:
  1631. z = time.time()
  1632. global big_df
  1633.  
  1634. keys = {'sym': 'symbol', 'x': 'exch_id', 'i': 'trade_id', 'z': 'tape', 'p': 'price', 'q': 'sequence', 's': 'trade_size', 'c': 'conditions', 't': 'trade_time'}
  1635. new_message = []
  1636.  
  1637. cst = pytz.timezone('US/Central')
  1638. #dst = pytz.timezone('America/Chicago')
  1639. UTC = pytz.utc
  1640. dt = datetime.now(cst)
  1641.  
  1642.  
  1643.  
  1644. l = ['sym', 'x', 'i', 'z', 'p', 'q', 's', 'c','t']
  1645. for d in message:
  1646. del d['ev'] # delete status
  1647. f = set(l) - d.keys() # Compare response with expected response
  1648. g = {k: 'NULL' for k in f} # Fill any blanks
  1649. d.update(g) # Update dict
  1650.  
  1651. d = {keys[name]: val for name, val in d.items()}
  1652.  
  1653. #resample('MarketMarker', d['symbol'], '1T', '1T', '1T', 'stocksdata_agg_sec', 'stocksdata_trades','1T', True)
  1654. #resample.resample_price(self)
  1655. d['tdate'] = unix_convert(d['trade_time'])
  1656. d['save_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  1657. cols = ['symbol', 'exch_id', 'trade_id', 'tape', 'price', 'sequence', 'trade_size', 'conditions', 'trade_time',
  1658. 'tdate', 'save_date']
  1659. #print(d)
  1660. d = {k: d[k] for k in cols}
  1661. new_message.append(d)
  1662. df = pd.DataFrame(new_message)
  1663. #big_df.append(df)
  1664. big_df = big_df.append(df, ignore_index=True, sort=False)
  1665. #df.to_csv('test3.csv')
  1666. #df.to_sql('stocksdata_trades', engine, if_exists='append', index=False, method='multi')
  1667. #redis_message("stock_trades_candles", new_message)
  1668. print('')
  1669. print(big_df)
  1670. #print(new_message)
  1671. #print(time.time()-z)
  1672. except Exception:
  1673. traceback.print_exc()
  1674. return None
  1675.  
  1676.  
  1677. #message = ticks
  1678.  
  1679.  
  1680. #new_message = []
  1681. ##if message is not None:
  1682. # #for d in message:
  1683. # # #del d['ev'] # delete status
  1684. # # #if 'op' not in d:
  1685. # # # d['op'] = None
  1686. # # d = {keys[name]: val for name, val in d.items()}
  1687. # # d['tdate'] = unix_convert(d['time_end'])
  1688. # # d['save_date'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
  1689. # # d['underlying_symbol'] = underlying_symbol
  1690. # # d['option_strike'] = int(strike) / 1000
  1691. # # d['option_type'] = option_type
  1692. # # d['symbol'] = option_symbol
  1693. # # d['option_expiration'] = option_expiration
  1694. # # cols = ['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
  1695. # # 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']
  1696. # # d = {k: d[k] for k in cols}
  1697. # # new_message.append(d)
  1698. # #redis_message('stock_trades_candles', new_message)
  1699.  
  1700.  
  1701.  
  1702.  
  1703. def test1():
  1704.  
  1705. global data_frame, df_cols
  1706.  
  1707. data = dict() #keeps extracted tick data
  1708.  
  1709. #for var in ticks:
  1710. # print (ticks.index(var),var)
  1711.  
  1712. #return
  1713. #for tick in ticks:
  1714. # print(ticks.index())
  1715. #sym = tick["sym"]
  1716. ##price = tick["p"]
  1717. #open = tick["p"]
  1718. #high = tick["p"]
  1719. #low = tick["p"]
  1720. #close = tick["p"]
  1721. #volume = tick["s"]
  1722. #timestamp_tick = datetime.utcfromtimestamp(tick["t"]/1000)
  1723. ##fix timestamp to be from message and not local
  1724. #timestamp = str(datetime.now().time())
  1725.  
  1726. ##data[timestamp] = [sym, price, volume, timestamp_tick]
  1727. #data[timestamp] = [sym, open, high, low, close, volume, timestamp_tick]
  1728.  
  1729. print(ticks)
  1730. #sym = ticks[1]["sym"]
  1731. ##price = tick["p"]
  1732. #open = ticks[1]["p"]
  1733. #high = ticks[1]["p"]
  1734. #low = ticks[1]["p"]
  1735. #close = ticks[1]["p"]
  1736. #volume = ticks[1]["s"]
  1737. #timestamp_tick = datetime.utcfromtimestamp(ticks[1]["t"]/1000)
  1738. #print(datetime.utcfromtimestamp(ticks[1]["t"]/1000))
  1739.  
  1740.  
  1741.  
  1742. sym = ticks[0]["sym"]
  1743. #price = tick["p"]
  1744. open = ticks[0]["p"]
  1745. high = ticks[0]["p"]
  1746. low = ticks[0]["p"]
  1747. close = ticks[0]["p"]
  1748. volume = ticks[0]["s"]
  1749. timestamp_tick = datetime.utcfromtimestamp(ticks[0]["t"]/1000)
  1750. print(datetime.utcfromtimestamp(ticks[0]["t"]/1000))
  1751. #ticks[1]['sym']
  1752. #data[timestamp_tick] = [token, ltp, volume]
  1753.  
  1754.  
  1755. ##data[timestamp] = [sym, price, volume, timestamp_tick]
  1756. data[timestamp_tick] = [sym, open, high, low, close, volume, timestamp_tick]
  1757.  
  1758. tick_df = pd.DataFrame(data.values(), columns=df_cols, index=data.keys()) #convert data to a DataFrame
  1759. data_frame = data_frame.append(tick_df) # append to existing
  1760. #data_frame.groupby(data_frame['symbol'])
  1761. #data_frame.set_index('Timestamp_Tick', inplace=True)
  1762. data_frame.set_index([pd.DatetimeIndex(data_frame["timestamp_tick"])], inplace=True)
  1763. aggregation = {'open' :'first',
  1764. 'high' :'max',
  1765. 'low' :'min',
  1766. 'close' :'last',
  1767. 'volume':'sum'}
  1768.  
  1769. #print("DataFrame: \n", data_frame)
  1770.  
  1771. df_1m = data_frame.groupby(data_frame['symbol']).resample('1T').agg(aggregation)
  1772. df_3m = data_frame.groupby(data_frame['symbol']).resample('3T').agg(aggregation)
  1773. #time.sleep(1)
  1774.  
  1775. #df_3m.dropna(thresh=2, inplace=True)
  1776.  
  1777. #print(trades)
  1778. print(df_1m)
  1779. #print(df_3m)
  1780.  
  1781. #test and fix below resample code
  1782. timeframe = '1min'
  1783.  
  1784. #tick_data['DATETIME'] = pd.to_datetime(tick_data['DATE'] + ' ' + tick_data['TIME'])
  1785. #tick_data.set_index('DATETIME', inplace=True)
  1786.  
  1787. #ohlcv_data = pd.DataFrame(columns=[
  1788. # 'SYMBOL_N',
  1789. # 'open',
  1790. # 'high',
  1791. # 'low',
  1792. # 'close',
  1793. # 'volume'])
  1794.  
  1795. #for symbol in tick_data['SYMBOL_N'].unique():
  1796. # ohlcv_symbol = tick_data.loc[tick_data['SYMBOL_N'] == symbol, 'PRICE'].resample(timeframe).ohlc()
  1797. # ohlcv_symbol['SYMBOL_N'] = symbol
  1798. # ohlcv_symbol['volume'] = (tick_data.loc[tick_data['SYMBOL_N'] == symbol, 'VOLUME'].resample(timeframe).max() -
  1799. # tick_data.loc[tick_data['SYMBOL_N'] == symbol, 'VOLUME'].resample(timeframe).max().shift(1))
  1800. # ohlcv_data = ohlcv_data.append(ohlcv_symbol, sort=False)
  1801.  
  1802. #print(ohlcv_data)
  1803.  
  1804.  
  1805. def save_candlesticks(message):
  1806. #global stock_ticks_df
  1807. #global one_minute_df
  1808.  
  1809.  
  1810.  
  1811. global current_tick, previous_tick, in_position
  1812. try:
  1813. previous_tick = current_tick
  1814. current_tick = message[0]
  1815. #current_tick = json.loads(message)[0]
  1816. symbol = current_tick['sym']
  1817.  
  1818. #print(current_tick)
  1819. #print(symbol)
  1820. #print("=== Received Tick ===")
  1821. #print("{} @ {} sym:{}".format(current_tick['t'], current_tick['p'], current_tick['sym']))
  1822. tick_datetime_object = datetime.utcfromtimestamp(current_tick['t']/1000)
  1823. tick_dt = tick_datetime_object.strftime('%Y-%m-%d %H:%M')
  1824. price = current_tick['p']
  1825. #price = 0
  1826. #previous_price = previous_tick['p']
  1827. previous_price = 0
  1828. tick_volume = current_tick['s']
  1829.  
  1830. #print(tick_datetime_object.minute)
  1831. #print(tick_dt)
  1832. #print(symbol)
  1833.  
  1834. #print('minutes_processed=',minutes_processed)
  1835. if not symbol in minutes_processed:
  1836. if not tick_dt in minutes_processed:
  1837. print("starting new candlestick")
  1838. minutes_processed[symbol, tick_dt] = True
  1839. #pprint.pprint(minutes_processed)
  1840.  
  1841. #if len(minute_candlesticks) > 0:
  1842. # minute_candlesticks[-1]['close'] = previous_price
  1843. vols = {}
  1844.  
  1845. vols[symbol, tick_dt] = 0
  1846. for current_tick in minute_candlesticks:
  1847. if symbol not in vols:
  1848. if tick_dt not in vols:
  1849. vols[symbol, tick_dt] = 0
  1850. vols[symbol, tick_dt] += int(current_tick['volume'])
  1851.  
  1852.  
  1853. #print('p=', current_tick['p'])
  1854. minute_candlesticks.append({
  1855. "symbol": symbol,
  1856. "minute": tick_dt,
  1857. "open": price,
  1858. "high": price,
  1859. "low": price,
  1860. "close": price,
  1861. "volume": tick_volume,
  1862. "total_volume": vols[symbol, tick_dt]
  1863. })
  1864. trades = pd.DataFrame.from_dict(minute_candlesticks)#.tail()
  1865. #trades.set_index(['symbol', pd.DatetimeIndex('minute')])
  1866. print(trades)
  1867.  
  1868.  
  1869. #trades.set_index(pd.DatetimeIndex(minute_candlesticks['minute'], unit='ms'), inplace=True)
  1870. #aggregation = {'open' :'first',
  1871. # 'high' :'max',
  1872. # 'low' :'min',
  1873. # 'close' :'last',
  1874. # 'volume':'sum'}
  1875.  
  1876. #df_1m = trades.resample('1T').agg(aggregation)
  1877. #df_3m = trades.resample('3T').agg(aggregation)
  1878.  
  1879.  
  1880. #df_3m.dropna(thresh=2, inplace=True)
  1881.  
  1882. #print(trades)
  1883. #print(df_1m)
  1884. #print(df_3m)
  1885.  
  1886.  
  1887.  
  1888. #if len(minute_candlesticks) > 0:
  1889. # current_candlestick = minute_candlesticks[-1]
  1890. # if price > current_candlestick['high']:
  1891. # current_candlestick['high'] = price
  1892. # if price < current_candlestick['low']:
  1893. # current_candlestick['low'] = price
  1894. #if current_tick['s'] > 0:
  1895. # current_candlestick['volume'] = [sum(current_tick['s'])]
  1896.  
  1897. #print("== Candlesticks ==")
  1898. #for candlestick in minute_candlesticks:
  1899. # print(candlestick)
  1900.  
  1901. #if len(minute_candlesticks) > 3:
  1902. # print("== there are more than 3 candlesticks, checking for pattern ==")
  1903. # last_candle = minute_candlesticks[-2]
  1904. # previous_candle = minute_candlesticks[-3]
  1905. # first_candle = minute_candlesticks[-4]
  1906.  
  1907. # print("== let's compare the last 3 candle closes ==")
  1908. # if last_candle['close'] > previous_candle['close'] and previous_candle['close'] > first_candle['close']:
  1909. # print("=== Three green candlesticks in a row, let's make a trade! ===")
  1910. # distance = last_candle['close'] - first_candle['open']
  1911. # print("Distance is {}".format(distance))
  1912. # profit_price = last_candle['close'] + (distance * 2)
  1913. # print("I will take profit at {}".format(profit_price))
  1914. # loss_price = first_candle['open']
  1915. # print("I will sell for a loss at {}".format(loss_price))
  1916.  
  1917. # if not in_position:
  1918. # print("== Placing order and setting in position to true ==")
  1919. # in_position = True
  1920. # place_order(profit_price, loss_price)
  1921. # sys.exit()
  1922. # else:
  1923. # print("No go")
  1924.  
  1925. except Exception as exe:
  1926. print(exe)
  1927. traceback.print_exc()
  1928.  
  1929. #one_minute_df = stock_ticks_df.assign(Timestamp = pd.to_datetime(stock_ticks_df['tdate'],unit='ms')).set_index('tdate')
  1930. #one_minute_df.resample('1min')['price', 'symbol'].ohlc()
  1931. #one_minute_df['volume'] = ticks_df['trade_size'].resample('1T').sum()
  1932. #print(one_minute_df)
  1933. #print(stock_ticks_df)
  1934.  
  1935.  
  1936. #resample_timeframe = '1T'
  1937. #rule = 's'
  1938. ##historic_data_table = historic_data_table
  1939. ##streaming_data_table = streaming_data_table
  1940. ##tick_rule = tick_rule
  1941. #is_origin = False
  1942.  
  1943. #one_minute_df = resample_price(rule, resample_timeframe, is_origin)
  1944.  
  1945. #if stock_ticks_df.empty != True:
  1946. # if len(stock_ticks_df) > 1000:
  1947. #data_ask = data_frame['Ask'].resample('15Min').ohlc()
  1948. #stock_ticks_df = stock_ticks_df.set_index(['tdate'], ['symbol'])
  1949. #print(stock_ticks_df['price'].resample('1Min').ohlc())
  1950. #one_minute_df = stock_ticks_df['price'].resample('1T').ohlc()
  1951. #one_minute_df['volume'] = stock_ticks_df['trade_size'].resample('1T').sum()
  1952.  
  1953. ## to forward fill no volume bars with last close, use:
  1954. #one_minute_df['volume'].fillna(0, inplace=True)
  1955. #one_minute_df['close'].ffill(inplace=True)
  1956. #one_minute_df['open'] = np.where(one_minute_df['volume'] <= 0, one_minute_df['close'], one_minute_df['open'])
  1957. #one_minute_df['high'] = np.where(one_minute_df['volume'] <= 0, one_minute_df['close'], one_minute_df['high'])
  1958. #one_minute_df['low'] = np.where(one_minute_df['volume'] <= 0, one_minute_df['close'], one_minute_df['low'])
  1959.  
  1960. ## otherwise, drop empty volume bars
  1961. #one_minute_df.dropna(inplace=True)
  1962.  
  1963. #one_minute_df.head()
  1964.  
  1965. #stock_ticks_df = stock_ticks_df.assign(tdate = pd.to_datetime(stock_ticks_df['trade_time'],unit='ms')).set_index(['tdate'], ['symbol'])
  1966. #one_minute_df = stock_ticks_df.resample('1min')['price'].ohlc()
  1967.  
  1968. #one_minute_df = one_minute_df.append(stock_ticks_df)
  1969. #one_minute_df.index = pd.to_datetime(one_minute_df.index, unit='ms')
  1970. #ggframe=one_minute_df.set_index(['tdate'], ['symbol'], ['trade_size'])
  1971. #candles=ggframe.groupby('symbol').resample('1min').agg({'LTP':'ohlc'})
  1972. #print(candles)
  1973.  
  1974. def stock_trades_process_message(ws, msg):
  1975. try:
  1976. message = json.loads(msg)
  1977. if message[0]['ev'] != 'status':
  1978. ###threading.Thread(target=save_stock_ticks_to_redis, args=[message]).start()
  1979. #threading.Thread(target=save_candlesticks, args=[message]).start()
  1980. threading.Thread(target=on_tick, args=[message]).start()
  1981.  
  1982. #print(datetime.now(tz=timezone.utc), "streaming: ", message[0]['sym'], '\t', message[0]['x'], '\t',
  1983. # message[0]['s'], '\t', message[0]['p'])
  1984. except Exception:
  1985. traceback.print_exc()
  1986. return None
  1987.  
  1988.  
  1989. def stock_trades_error_handler(ws, error):
  1990. #raise ValueError('an error happened:', error)
  1991. print("error ", error)
  1992. pass
  1993.  
  1994.  
  1995. def stock_trades_close_handler(ws, close_code, close_msg):
  1996. print("closed connection", close_code, close_msg)
  1997. main()
  1998. pass
  1999. #return None
  2000.  
  2001. def get_stocks_snapshot(symbols=None):
  2002. try:
  2003. #start_time2 = time.time()
  2004. # Date Info
  2005. #from_date = '2021-01-01'
  2006. #from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
  2007. #to_date = datetime.today().date() + timedelta(days=1)
  2008. ## Transform Dates
  2009. #temp_date_start = to_date - timedelta(days=60)
  2010. #temp_date_end = to_date
  2011. ##print(f'getting data for {symbol}')
  2012. #while temp_date_start > from_date:
  2013. #start_time2 = time.time()
  2014. if symbols is None:
  2015. temp_df = get_current_stocks_snapshot()
  2016. else:
  2017. temp_df = get_current_stocks_snapshot(symbols)
  2018. #print('thread 3', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
  2019. #print(time.time() - start_time2, '\n')
  2020. #print('thread 3', '\n', temp_df)
  2021. #temp_date_end = temp_date_end - timedelta(days=60)
  2022. #temp_date_start = temp_date_start - timedelta(days=2)
  2023. if isinstance(type(temp_df), str):
  2024. return
  2025. #else:
  2026. # Add df to database
  2027. #print(temp_df)
  2028. if temp_df is not None:# or len(temp_df) > 0:
  2029. #print('writing to quotes ->' + str(len(temp_df)))
  2030. #temp_df.to_sql('stocksdata_snapshots', engine, if_exists='append', index=False, method='multi')
  2031. time.sleep(0.1)
  2032. temp_df=None
  2033.  
  2034. except Exception as exe:
  2035. print(exe)
  2036. traceback.print_exc()
  2037. time.sleep(10)
  2038. df = None
  2039. #print(time.time() - start_time2)
  2040.  
  2041. def get_daily_stock_open_close(symbol):
  2042. try:
  2043. #start_time2 = time.time()
  2044. # Date Info
  2045. from_date = '2021-10-01'
  2046. from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
  2047. to_date = datetime.today().date() + timedelta(days=-1)
  2048. # Transform Dates
  2049. temp_date_start = to_date - timedelta(days=3)
  2050. temp_date_end = to_date
  2051. #print(f'getting data for {symbol}')
  2052.  
  2053. start_date = from_date
  2054. end_date = datetime.today().strftime('%Y-%m-%d')
  2055. #for single_date in daterange(start_date, end_date):
  2056. # print(single_date.strftime("%Y-%m-%d"))
  2057.  
  2058. #first_date = from_date
  2059. #duration = timedelta(days=10)
  2060. #for d in range(duration.days + 1):
  2061. # day = first_date + timedelta(days=d)
  2062. # start_time2 = time.time()
  2063. # temp_df = get_historic_stock_daily_open_close(symbol, requestdate=day)
  2064. #print(symbol)
  2065. #print(day)
  2066. #print(temp_df)
  2067.  
  2068. start_date = date(2021, 11, 1)
  2069. end_date = date(2021, 11, 4)
  2070. delta = timedelta(days=1)
  2071. #get_bars(symbol)
  2072.  
  2073. while start_date <= end_date:
  2074. print(symbol, start_date)
  2075. temp_df = get_historic_stock_daily_open_close(symbol, requestdate=temp_date_start)
  2076. #future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
  2077. #future1 = executor.submit(get_bars, symbol)
  2078. #future2 = executor.submit(get_trades, symbol)
  2079. #future3 = executor.submit(get_quotes, symbol)
  2080. #future4 = executor.submit(get_daily_stock_open_close, symbol)
  2081. #temp_df = get_historic_trades(symbol=symbol, requestdate=temp_date_start, limit=50000)
  2082. start_date += delta
  2083.  
  2084.  
  2085. #return
  2086. #while temp_date_start > from_date:
  2087. # start_time2 = time.time()
  2088. ##temp_df = get_historic_stock_daily_open_close(symbol, requestdate=requestdata)
  2089. #print(temp_df)
  2090. #print('thread 3', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
  2091. #print(time.time() - start_time2, '\n')
  2092. #print('thread 3', '\n', temp_df)
  2093. #temp_date_end = temp_date_end - timedelta(days=1)
  2094. #temp_date_start = temp_date_start - timedelta(days=1)
  2095. if isinstance(type(temp_df), str):
  2096. return
  2097. #else:
  2098. # Add df to database
  2099. #print(temp_df)
  2100. #if temp_df is not None or len(temp_df) > 0:
  2101. if temp_df is not None:
  2102. #print('writing to quotes ->' + str(len(temp_df)))
  2103. temp_df.to_sql('stocksdata_hist_quotes', engine, if_exists='append', index=False, method='multi')
  2104. time.sleep(0.1)
  2105. temp_df=None
  2106.  
  2107. except Exception as exe:
  2108. print(exe)
  2109. traceback.print_exc()
  2110. time.sleep(10)
  2111. df = None
  2112. #print(time.time() - start_time2)
  2113.  
  2114.  
  2115. def get_data(symbol):
  2116. start_time2 = time.time()
  2117. # Date Info
  2118. from_date = '2019-01-01'
  2119. from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
  2120. to_date = datetime.today().date() + timedelta(days=1)
  2121. # Transform Dates
  2122. temp_date_start = to_date - timedelta(days=60)
  2123. temp_date_end = to_date
  2124. print(f'getting data for {symbol}')
  2125. while temp_date_start > from_date:
  2126. temp_df = call_api(symbol, temp_date_start, temp_date_end)
  2127. temp_date_end = temp_date_end - timedelta(days=60)
  2128. temp_date_start = temp_date_start - timedelta(days=60)
  2129. if isinstance(type(temp_df), str):
  2130. break
  2131. #else:
  2132. # Add df to database
  2133. #print(temp_df)
  2134. #temp_df.to_sql('stockdata_hist', engine, if_exists='append', index=False, method='multi')
  2135. print(time.time() - start_time2)
  2136.  
  2137.  
  2138. def daterange(start_date, end_date):
  2139. for n in range(int ((end_date - start_date).days)):
  2140. yield start_date + timedelta(n)
  2141.  
  2142.  
  2143. def get_option_trades(option_symbol: str, timestamp=None, timestamp_lt=None, timestamp_lte=None,
  2144. timestamp_gt=None, timestamp_gte=None, limit: int = 50000, order='asc',
  2145. raw_response: bool = False):
  2146. try:
  2147. z = time.time()
  2148. o = options.OptionsPolygon
  2149.  
  2150. #from_date = '2021-10-28'
  2151. #print(option_symbol, timestamp)
  2152. df = get_historic_option_trades(option_symbol, requestdate=timestamp)
  2153. #message = get_historic_option_trades(option_symbol, requestdate=timestamp)
  2154.  
  2155. #temp_df = o.get_option_trades('O:TSLA211029C01150000', requestdate=from_date, limit=50000)
  2156. #temp_df = o.get_option_trades(option_symbol, requestdate=from_date, limit=50000)
  2157. #df = pd.DataFrame.from_dict(temp_df['results'])
  2158. #df = pd.DataFrame.from_dict(message['results'])
  2159. #return
  2160.  
  2161. if df is not None:
  2162.  
  2163. #cols = ['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
  2164. # 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']
  2165. #new_message = []
  2166. #df = {k: df[k] for k in cols}
  2167. #new_message.append(df)
  2168. #redis_message('historic_option_trades', new_message)
  2169. #df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
  2170. #df['save_date'] = datetime.utcnow()
  2171. #df = df[['symbol', 'price', 'size', 'sequence_number', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']]
  2172. print('\n', option_symbol, '\t', timestamp, '\t', len(df))
  2173. df.to_sql('optionsdata_hist_trades', engine, if_exists='append', index=False, method='multi')
  2174.  
  2175. #print(time.time()-z)
  2176. #first_date = from_date
  2177. #duration = timedelta(days=10)
  2178. #for d in range(duration.days + 1):
  2179. # day = first_date + timedelta(days=d)
  2180. # start_time2 = time.time()
  2181. # temp_df = get_trades(symbol, requestdate=day)
  2182. #pprint.pprint(message)
  2183. except Exception:
  2184. traceback.print_exc()
  2185. return None
  2186.  
  2187. def _get_response(path: str, params: dict = None,
  2188. raw_response: bool = True) -> Union[Response, dict]:
  2189. """
  2190. Get response on a path. Meant to be used internally but can be used if you know what you're doing
  2191.  
  2192. :param path: RESTful path for the endpoint. Available on the docs for the endpoint right above its name.
  2193. :param params: Query Parameters to be supplied with the request. These are mapped 1:1 with the endpoint.
  2194. :param raw_response: Whether or not to return the ``Response`` Object. Useful for when you need to check the
  2195. status code or inspect the headers. Defaults to True which returns the ``Response`` object.
  2196. :return: A Response object by default. Make ``raw_response=False`` to get JSON decoded Dictionary
  2197. """
  2198. BASE = 'https://api.polygon.io'
  2199. time_out_conf = httpx.Timeout(connect=10, read=10, pool=10,
  2200. write=10)
  2201. session = requests.session()
  2202. session.headers.update({'Authorization': f'Bearer {options_key}'})
  2203. _res = session.request('GET', BASE + path, params=params, timeout=10)
  2204. #_res = session.request('GET', BASE + path, params=params, timeout=time_out_conf)
  2205.  
  2206. if raw_response:
  2207. return _res
  2208.  
  2209. return _res.json()
  2210.  
  2211. #temporary
  2212. def get_options_aggregate_bars( option_symbol: str, from_date, to_date, adjusted: bool = True,
  2213. sort='asc', limit: int = 50000, multiplier: int = 1, timespan='day',
  2214. raw_response: bool = False) -> Union[Response, dict]:
  2215. """
  2216. Get aggregate bars for a stock over a given date range in custom time window sizes.
  2217. For example, if ``timespan = ‘minute’`` and ``multiplier = ‘5’`` then 5-minute bars will be returned.
  2218. `Official Docs
  2219. <https://polygon.io/docs/get_v2_aggs_ticker__stocksTicker__range__multiplier___timespan___from___to__anchor>`__
  2220.  
  2221. :param symbol: The ticker symbol of the stock/equity.
  2222. :param from_date: The start of the aggregate time window. Could be ``datetime`` or ``date`` or string
  2223. ``YYYY-MM-DD``
  2224. :param to_date: The end of the aggregate time window. Could be ``datetime`` or ``date`` or string ``YYYY-MM-DD``
  2225. :param adjusted: Whether or not the results are adjusted for splits. By default, results are adjusted. Set this
  2226. to false to get results that are NOT adjusted for splits.
  2227. :param sort: Sort the results by timestamp. See :class:`polygon.enums.SortOrder` for choices. ``asc`` default.
  2228. :param limit: Limits the number of base aggregates queried to create the aggregate results. Max 50000 and
  2229. Default 5000.
  2230. :param multiplier: The size of the timespan multiplier. Must be a positive whole number.
  2231. :param timespan: The size of the time window. See :class:`polygon.enums.Timespan` for choices. defaults to
  2232. ``day``
  2233. :param raw_response: Whether or not to return the ``Response`` Object. Useful for when you need to say check the
  2234. status code or inspect the headers. Defaults to False which returns the json decoded
  2235. dictionary.
  2236. :return: A JSON decoded Dictionary by default. Make ``raw_response=True`` to get underlying response object
  2237. """
  2238.  
  2239. if isinstance(from_date, date) or isinstance(from_date, datetime):
  2240. from_date = from_date.strftime('%Y-%m-%d')
  2241.  
  2242. if isinstance(to_date, date) or isinstance(to_date, datetime):
  2243. to_date = to_date.strftime('%Y-%m-%d')
  2244.  
  2245. #timespan, sort = _change_enum(timespan, str), _change_enum(sort, str)
  2246. option_symbol = str(option_symbol).upper()
  2247. #_path = '/v2/aggs/ticker/O:AA211112P00045000/range/1/minute/2021-11-08/2021-11-12?adjusted=true&sort=asc&limit=120&apiKey=iJbpOayAiB6_j3DIs6WbZ79ZG4SlV5eb'
  2248. _path = f'/v2/aggs/ticker/O:{option_symbol}/range/{multiplier}/{timespan}/{from_date}/{to_date}'
  2249. #_path = f'/v2/aggs/ticker/{option_symbol.upper()}/range/{multiplier}/{timespan}/{from_date}/{to_date}'
  2250.  
  2251. _data = {'adjusted': 'true' if adjusted else 'false',
  2252. 'sort': sort,
  2253. 'limit': limit}
  2254.  
  2255. _res = _get_response(_path)#, params=_data)
  2256.  
  2257. if raw_response:
  2258. return _res
  2259. #print(_res.json())
  2260. return _res.json()
  2261.  
  2262. def get_bars_options(option_symbol: str, timestamp=None, timestamp_lt=None, timestamp_lte=None,
  2263. timestamp_gt=None, timestamp_gte=None, limit: int = 50000, order='asc',
  2264. raw_response: bool = False):
  2265. try:
  2266. z = time.time()
  2267. o = options.OptionsPolygon
  2268.  
  2269. ref = reference.ReferencePolygon
  2270. if '_' in option_symbol:
  2271. option_symbol = ref.convert_tda_option_to_polygon(option_symbol)
  2272. #from_date = '2021-10-28'
  2273. #print(option_symbol, timestamp)
  2274.  
  2275.  
  2276. #start_date = date(2021, 11, 8)
  2277. #end_date = date(2021, 11, 12)
  2278.  
  2279. start_date = '2021-10-01'
  2280. end_date = '2021-11-19'
  2281.  
  2282. temp_df = get_historic_bars_options(option_symbol, start_date, end_date, adjusted=True, sort='desc', limit=50000, multiplier=1, timespan='minute')
  2283. #start_date += delta
  2284.  
  2285. #while temp_date_start > from_date:
  2286. # start_time2 = time.time()
  2287. # temp_df = get_historic_bars(symbol, temp_date_start, temp_date_end)
  2288. # #print('thread 1', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
  2289. # #print(time.time() - start_time2, '\n')
  2290. # #print('thread 1', '\n', temp_df)
  2291. # temp_date_end = temp_date_end - timedelta(days=60)
  2292. # temp_date_start = temp_date_start - timedelta(days=60)
  2293. #if isinstance(type(temp_df), str):
  2294. # break
  2295. #else:
  2296. # Add df to database
  2297. #print(temp_df)
  2298. start_time2 = time.time()
  2299. to_sql = True
  2300. #if temp_df is not None or len(temp_df) > 0:
  2301. if temp_df is not None:
  2302. if to_sql == True:
  2303. print('writing to bars -> ' + str(option_symbol) + ' ' + str(len(temp_df)))
  2304. temp_df.to_sql('optionsdata_hist_bars', engine, if_exists='append', index=False, method='multi')
  2305. #time.sleep(0.1)
  2306. else:
  2307. #pprint.pprint(temp_df)
  2308. #bars_df.append(temp_df, ignore_index=True)
  2309. frames = [bars_df, temp_df]
  2310. bars_df = pd.concat(frames)
  2311. #print(bars_df)
  2312. #print(len(bars_df))
  2313. #bars_df
  2314. #print(temp_df)
  2315. temp_df=None
  2316.  
  2317.  
  2318.  
  2319. except Exception:
  2320. traceback.print_exc()
  2321. return None
  2322.  
  2323. ## Does not work
  2324. def get_option_trades_redis(option_symbol: str, timestamp=None, timestamp_lt=None, timestamp_lte=None,
  2325. timestamp_gt=None, timestamp_gte=None, limit: int = 50000, order='asc',
  2326. raw_response: bool = False):
  2327. try:
  2328. z = time.time()
  2329. o = options.OptionsPolygon
  2330.  
  2331. #from_date = '2021-10-28'
  2332. print(option_symbol, timestamp)
  2333. #df = get_historic_option_trades(option_symbol, requestdate=timestamp)
  2334.  
  2335. o = options.OptionsPolygon
  2336. resp = o.get_option_trades(option_symbol, requestdate=timestamp, limit=50000)
  2337. #message = get_historic_option_trades(option_symbol, requestdate=timestamp)
  2338. message = resp
  2339.  
  2340.  
  2341. new_message = []
  2342. if message is not None:
  2343. for d in message:
  2344. #del d['ev'] # delete status
  2345. #if 'op' not in d:
  2346. # d['op'] = None
  2347. d = {keys[name]: val for name, val in d.items()}
  2348. d['tdate'] = unix_convert(d['time_end'])
  2349. d['save_date'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
  2350. d['underlying_symbol'] = underlying_symbol
  2351. d['option_strike'] = int(strike) / 1000
  2352. d['option_type'] = option_type
  2353. d['symbol'] = option_symbol
  2354. d['option_expiration'] = option_expiration
  2355. cols = ['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
  2356. 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']
  2357. d = {k: d[k] for k in cols}
  2358. new_message.append(d)
  2359. redis_message('historic_option_trades', new_message)
  2360.  
  2361. #if 'results' in resp:
  2362. # df = pd.DataFrame.from_dict(resp['results'])
  2363. # if df is not None and df.empty != True:
  2364.  
  2365. # df.columns = ['conditions', 'exchange', 'participant_timestamp', 'price', 'sip_timestamp', 'size']
  2366. # #df.columns = ['conditions', 'exchange', 'price', 'sequence_number', 'sip_timestamp', 'size']
  2367. # polygon_option_symbol = symbol
  2368. # option_numbers = re.findall(r'\d+', polygon_option_symbol)
  2369. # underlying_symbol = polygon_option_symbol[:polygon_option_symbol.index(option_numbers[0])]
  2370.  
  2371. # option_type = str(polygon_option_symbol[polygon_option_symbol.index(option_numbers[1]) - 1:])[:1]
  2372.  
  2373. # option_expiration = str(option_numbers[0])
  2374. # #rint(df['price'])
  2375. # option_strike = str(option_numbers[1])
  2376. # #del df['sequence_number']
  2377. # df.insert(0, 'symbol', symbol)
  2378. # df.insert(1, 'underlying_symbol', underlying_symbol)
  2379. # df.insert(2, 'option_type', option_type)
  2380. # df.insert(3, 'option_expiration', option_expiration)
  2381. # df.insert(4, 'option_strike', int(option_strike)/1000)
  2382.  
  2383. # df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
  2384. # df['save_date'] = datetime.utcnow()
  2385. # #df = df[['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'sequence_number', 'size',
  2386. # df = df[['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
  2387. # 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']]
  2388.  
  2389. # return df.to_json(orient='records')[1:-1].replace('},{', '} {')
  2390.  
  2391. # else:
  2392. # df=None
  2393. #else:
  2394. # df = None
  2395.  
  2396.  
  2397. #temp_df = o.get_option_trades('O:TSLA211029C01150000', requestdate=from_date, limit=50000)
  2398. #temp_df = o.get_option_trades(option_symbol, requestdate=from_date, limit=50000)
  2399. #df = pd.DataFrame.from_dict(temp_df['results'])
  2400. #df = pd.DataFrame.from_dict(message['results'])
  2401. #return
  2402.  
  2403. #for d in message:
  2404.  
  2405.  
  2406. #if df is not None:
  2407.  
  2408. # cols = ['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
  2409. # 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']
  2410. # new_message = []
  2411. # df = {k: df[k] for k in cols}
  2412. # new_message.append(df)
  2413. # redis_message('historic_option_trades', new_message)
  2414. #df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
  2415. #df['save_date'] = datetime.utcnow()
  2416. #df = df[['symbol', 'price', 'size', 'sequence_number', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']]
  2417. #print(len(df))
  2418. #df.to_sql('optionsdata_hist_trades', engine, if_exists='append', index=False, method='multi')
  2419.  
  2420. #print(time.time()-z)
  2421. #first_date = from_date
  2422. #duration = timedelta(days=10)
  2423. #for d in range(duration.days + 1):
  2424. # day = first_date + timedelta(days=d)
  2425. # start_time2 = time.time()
  2426. # temp_df = get_trades(symbol, requestdate=day)
  2427. #pprint.pprint(message)
  2428. except Exception:
  2429. traceback.print_exc()
  2430. return None
  2431.  
  2432.  
  2433. def save_data3(message):
  2434. try:
  2435. z = time.time()
  2436. keys = {'price', 'size', 'sequence_number', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date'}
  2437. new_message = []
  2438. new_dict = message.to_dict('results')
  2439. sql_function_options(new_dict)
  2440. return
  2441. #for d in message:
  2442. for d in new_dict:
  2443. #del d['ev'] # delete status
  2444. #if 'op' not in d:
  2445. # d['op'] = None
  2446. d = {keys[name]: val for name, val in d.items()}
  2447. #d['tdate'] = unix_convert(d['time_end'])
  2448. d['save_date'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
  2449. cols = ['price', 'size', 'sip_timestamp', 'conditions', 'exchange', 'participant_timestamp', 'save_date']
  2450. d = {k: d[k] for k in cols}
  2451. new_message.append(d)
  2452. redis_message(new_message)
  2453. print(time.time()-z)
  2454. except Exception:
  2455. traceback.print_exc()
  2456. return None
  2457.  
  2458. def sql_function_options(messages):
  2459. cur = conn.cursor()
  2460. sio = io.StringIO()
  2461. writer = csv.writer(sio)
  2462. values = [[value for value in message.values()] for message in messages]
  2463. writer.writerows(values)
  2464. cols = ['price', 'size', 'sequence_number', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']
  2465. #cols = ['symbol', 'tick_volume', 'total_volume', 'opening_price', 'tick_vwap', 'tick_open', 'tick_close',
  2466. # 'tick_high', 'tick_low', 'vwap', 'avg_trade_size', 'time_beg', 'time_end', 'tdate', 'save_date']
  2467. sio.seek(0)
  2468. cur.copy_from(file=sio, table="optionsdata_trades2", sep=",", columns=cols, null='')
  2469. cur.close()
  2470. return None
  2471.  
  2472. def get_historical_data(symbols):
  2473.  
  2474. z = time.time()
  2475. ref = reference.ReferencePolygon
  2476. #for symbol in symbols:
  2477. # get_bars_options(ref.convert_tda_option_to_polygon(symbol))
  2478. with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count() * 20) as executor:
  2479. #with concurrent.futures.ThreadPoolExecutor(10) as executor:
  2480. #executor.map(get_data1, symbols)
  2481.  
  2482. # #for future in concurrent.futures.as_completed(futures):
  2483. #future1 = executor.map(get_bars, symbols)
  2484. #future1 = executor.map(get_bars_options, symbols)
  2485. for symbol in symbols:
  2486. future1 = executor.submit(get_bars_options, symbol)
  2487.  
  2488. #future2 = executor.map(get_trades, symbols)
  2489. #future3 = executor.map(get_quotes, symbols)
  2490. #for symbol in symbols:
  2491. # future1 = executor.submit(get_bars, symbol)
  2492.  
  2493. #symbol = 'TSLA_102921C1100'
  2494. #for symbol in symbols:
  2495. # #get_option_trades(ref.convert_tda_option_to_polygon(symbol))
  2496.  
  2497. # start_date = date(2021, 11, 8)
  2498. # end_date = date(2021, 11, 11)
  2499. # delta = timedelta(days=1)
  2500. # future1 = executor.submit(get_bars, symbol)
  2501. #get_bars(symbol, start_date, end_date, adjusted=True, sort='desc', limit=50000, multiplier=1, timespan='minute')
  2502.  
  2503. print(time.time()-z)
  2504.  
  2505.  
  2506. #future4 = executor.submit(get_daily_stock_open_close, symbol)
  2507.  
  2508. #while start_date <= end_date:
  2509. # #future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
  2510. # #future1 = executor.submit(get_bars, symbol)
  2511. # #future2 = executor.submit(get_trades, symbol)
  2512. # #future3 = executor.submit(get_quotes, symbol)
  2513. # future4 = executor.submit(get_daily_stock_open_close, symbol)
  2514. # start_date += delta
  2515.  
  2516. def resample_price(rule, resample_timeframe, is_origin):
  2517. # Fetch the results for the specific ticker form the historic_data table
  2518. #hist_data = pd.read_sql_query("select * from {} where ticker = '{}'".format(self.historic_data_table + "_" + self.base_timeframe.replace(" ", "_"), self.tickers[0]),
  2519. # con=self.db).sort_values("date_time", ascending=True)
  2520. #hist_data = hist_data.set_index(['date_time'])
  2521. #hist_data.index = pd.to_datetime(hist_data.index, unit='ms')
  2522.  
  2523. # Call the function responsible for fetching tick data and converting it to the base timeframe.
  2524. # Then concat the historic df and streaming df
  2525. tick_data = convert_tick_ohlc(resample_timeframe)
  2526.  
  2527. #data = pd.concat([hist_data, tick_data])
  2528. #df.reset_index(level=0, inplace=True)
  2529.  
  2530. #return tick_data
  2531.  
  2532. #price_ohlc = pd.DataFrame()
  2533. #if not df.empty:
  2534. # # Resample lower time frame to to higher time fra me OHLC candles
  2535. # # Drop the NA and reset index
  2536. # origin = ''
  2537. # if is_origin:
  2538. # origin = df['tdate'][0]
  2539.  
  2540. # price_ohlc = df.groupby(['symbol']).resample(rule=rule, label='left', on='tdate', origin=origin).agg({'price': 'first', 'price': 'max', 'price': 'min', 'price': 'last', 'trade_size': 'sum'})
  2541. # price_ohlc = price_ohlc.dropna()
  2542. # price_ohlc.reset_index(level=0, inplace=True)
  2543.  
  2544. return tick_data#price_ohlc
  2545.  
  2546. def convert_tick_ohlc(resample_timeframe):
  2547. # Fetch the results for the specific ticker form the streaming_data table
  2548. # Create dataframe and set date_time as index and convert it to a python datetime object
  2549. # Resample them to "base timeframe" OHLC candles and drop the NA
  2550. #data = pd.read_sql_query(
  2551. # "select * from {} where ticker = '{}'".format(self.streaming_data_table, self.tickers[0]),
  2552. # con=self.db).sort_values("date_time", ascending=True)
  2553. #data = df
  2554. global stock_ticks_df
  2555.  
  2556. data = stock_ticks_df
  2557. data_ask = pd.DataFrame()
  2558. if not data.empty:
  2559. #data = data.set_index(['symbol'])
  2560. print('1',data.index.name)
  2561. data.set_index(['tdate'], inplace=True)
  2562. print('2',data.index.name)
  2563. #data = data.set_index(['tdate'])
  2564. #data['tdate'] = pd.to_datetime(data['tdate'])
  2565. print(data['tdate'])
  2566. data['tdate'] = pd.to_datetime(data['tdate'], unit='ms')
  2567. #data['tdate'] = pd.to_datetime(data.index, unit='s')
  2568. #data = data.set_index(['symbol'])
  2569. #data.index = pd.to_datetime(data['tdate'], unit='s')
  2570. #data.index = data['tdate']
  2571. #data.index = pd.to_datetime(data.index, unit='s')
  2572. #data.groupby(['symbol', 'tdate'])
  2573.  
  2574. data_ask = data.groupby(['symbol']).resample(resample_timeframe).agg({'price': 'ohlc', 'trade_size': 'sum'}).reset_index()
  2575. #data_ask = data.resample(resample_timeframe).agg({'price': 'ohlc', 'trade_size': 'sum'}).reset_index()
  2576. data_ask = data_ask.dropna()
  2577.  
  2578. # Flattening the multi-index dataframe to a single level dataframe
  2579. data_ask.columns = data_ask.columns.to_series().str.join('')
  2580.  
  2581. # Renaming the columns for the dataframe
  2582. data_ask = data_ask.rename(columns={"priceopen": "open",
  2583. "pricehigh": "high",
  2584. "pricelow": "low",
  2585. "priceclose": "close",
  2586. "trade_sizetrade_size": "volume"})
  2587.  
  2588. # Reset the index and append ticker/timeframe columns to the dataframe.
  2589. # Convert the dataframe to dictionary.
  2590. # data_ask.reset_index(level=0, inplace=True)
  2591. #print(data_ask)
  2592. #data_ask["symbol"] = tickers#[0]
  2593.  
  2594. return data_ask
  2595.  
  2596.  
  2597. #wp = jp.WebPage(delete_flag=False)
  2598. #clock_div = jp.Span(text='Loading...', classes='text-5xl m-1 p-1 bg-gray-300 font-mono', a=wp)
  2599.  
  2600. #async def clock_counter():
  2601. # while True:
  2602. # clock_div.text = time.strftime("%a, %d %b %Y, %H:%M:%S", time.localtime())
  2603. # jp.run_task(wp.update())
  2604. # await asyncio.sleep(1)
  2605.  
  2606. #async def clock_init():
  2607. # jp.run_task(clock_counter())
  2608.  
  2609. #async def clock_test():
  2610. # return wp
  2611.  
  2612.  
  2613.  
  2614. #button_classes = 'm-2 p-2 text-red-700 bg-white hover:bg-red-200 hover:text-red-500 border focus:border-red-500 focus:outline-none'
  2615.  
  2616. #async def count_down(self, msg):
  2617. # self.show = False
  2618. # if hasattr(msg.page, 'd'):
  2619. # msg.page.remove(msg.page.d)
  2620. # bomb_icon = jp.Icon(icon='bomb', classes='inline-block text-5xl ml-1 mt-1', a=msg.page)
  2621. # d = jp.Div(classes='text-center m-4 p-4 text-6xl text-red-600 bg-blue-500 faster', a=msg.page, animation=self.count_animation)
  2622. # msg.page.d = d
  2623. # for i in range(self.start_num, 0 , -1):
  2624. # d.text = str(i)
  2625. # await msg.page.update()
  2626. # await asyncio.sleep(1)
  2627. # d.text = 'Boom!'
  2628. # d.animation = 'zoomIn'
  2629. # d.set_classes('text-red-500 bg-white')
  2630. # bomb_icon.set_class('text-red-700')
  2631. # self.show = True
  2632.  
  2633. #def count_test(request):
  2634. # start_num = int(request.query_params.get('num', 10))
  2635. # animation = request.query_params.get('animation', 'flip')
  2636. # wp = jp.WebPage()
  2637. # count_button = jp.Button(text='Start Countdown', classes=button_classes, a=wp, click=count_down)
  2638. # count_button.start_num = start_num
  2639. # count_button.count_animation = animation
  2640. # return wp
  2641.  
  2642.  
  2643.  
  2644. #input_classes = 'm-2 bg-gray-200 font-mono appearance-none border-2 border-gray-200 rounded py-2 px-4 text-gray-700 focus:outline-none focus:bg-white focus:border-red-500'
  2645. #button_classes = 'm-2 p-2 text-red-700 bg-white hover:bg-red-200 hover:text-red-500 border focus:border-red-500 focus:outline-none'
  2646. #message_classes = 'ml-4 p-2 text-lg bg-red-500 text-white overflow-auto font-mono rounded-lg'
  2647.  
  2648. #shared_div = jp.Div(classes='m-2 h-1/2 border overflow-auto', delete_flag=False)
  2649. #header = jp.Div(text='Simple Message Board', classes='bg-red-100 border-l-4 border-red-500 text-red-700 p-4 text-3xl', delete_flag=False)
  2650. #button_icon = jp.Icon(icon='paper-plane', classes='text-2xl', delete_flag=False)
  2651. #button_text = jp.Div(text='Send', classes='text-sm', delete_flag=False)
  2652. #message_icon = jp.Icon(icon='comments', classes='text-2xl text-green-600', delete_flag=False)
  2653.  
  2654. #def message_initialize():
  2655. # # Called once on startup
  2656. # d = jp.Div(a=shared_div, classes='flex m-2 border')
  2657. # time_stamp = jp.P(text=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), classes='text-xs ml-2 flex-shrink-0')
  2658. # p = jp.Pre(text='Welcome to the simple message board!', classes=message_classes)
  2659. # d.add(message_icon, time_stamp, p)
  2660.  
  2661. #async def send_message(self, msg):
  2662. # if self.message.value:
  2663. # d = jp.Div(classes='flex m-2 border')
  2664. # time_stamp = jp.P(text=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), classes='text-xs ml-2 flex-shrink-0')
  2665. # p = jp.Pre(text=self.message.value, classes=message_classes)
  2666. # d.add(message_icon, time_stamp, p)
  2667. # shared_div.add_component(d, 0)
  2668. # self.message.value = '' # Clear message box after message is sent
  2669. # await shared_div.update()
  2670.  
  2671. #def message_demo():
  2672. # wp = jp.WebPage()
  2673. # outer_div = jp.Div(classes='flex flex-col h-screen', a=wp)
  2674. # outer_div.add(header)
  2675. # d = jp.Div(classes='flex', a=outer_div)
  2676. # message = jp.Textarea(placeholder='Enter message here', a=d, classes=input_classes, debounce=500)
  2677. # send_button = jp.Button(a=d, click=send_message, classes=button_classes)
  2678. # send_button.add(button_icon, button_text)
  2679. # outer_div.add(shared_div)
  2680. # shared_div.add_page(wp)
  2681. # send_button.message = message
  2682. # return wp
  2683.  
  2684.  
  2685. #wp = jp.WebPage(delete_flag=False)
  2686. #wp.reload_interval = 2.5
  2687. #count_div = jp.Div(a=wp, classes='text-center m-4 p-4 text-white bg-blue-500', style='font-size: 200px')
  2688.  
  2689. #async def increment_counter(start):
  2690. # count_div.counter = start
  2691. # while True:
  2692. # count_div.counter += 1
  2693. # count_div.text = str(count_div.counter)
  2694. # await asyncio.sleep(1)
  2695.  
  2696. #def start_counting():
  2697. # jp.run_task(increment_counter(500))
  2698.  
  2699. #def reload_demo():
  2700. # return wp
  2701.  
  2702.  
  2703.  
  2704. #epoch = datetime(1970, 1, 1)
  2705.  
  2706.  
  2707. #def convert_date(date_string):
  2708. # date = datetime.strptime(date_string, '%Y-%m-%d')
  2709. # return (date - epoch).total_seconds()*1000
  2710.  
  2711.  
  2712. #def stock_test(request):
  2713. # wp = jp.WebPage()
  2714. # ticker = request.query_params.get('ticker', 'MSFT')
  2715. # if ticker not in ['AAPL', 'IBM', 'INTC', 'MSFT']:
  2716. # ticker = 'MSFT'
  2717. # data = pd.read_csv(f'https://elimintz.github.io/stocks/{ticker.upper()}.csv')
  2718. # chart = jp.HighStock(a=wp, classes='m-1 p-2 border w-10/12')
  2719. # o = chart.options
  2720. # o.title.text = 'Historical Stock Price'
  2721. # o.legend = {'enabled': True, 'align': 'right', 'layout': 'proximate'}
  2722. # o.rangeSelector.selected = 4 # Set default range to 1 year
  2723. # x = list(data['Date'].map(convert_date))
  2724. # y = data['Adj Close'].to_list()
  2725. # s = jp.Dict({'name': ticker.upper(), 'data': jp.make_pairs_list(x, y)})
  2726. # o.series = [s]
  2727. # s.tooltip.valueDecimals = 2 # Price displayed by tooltip will have 2 decimal values
  2728. # return wp
  2729.  
  2730.  
  2731.  
  2732. #epoch = datetime(1970, 1, 1)
  2733. #grouping_units = [['week', [1]], ['month', [1, 2, 3, 4, 6]]]
  2734.  
  2735. #chart_dict = {
  2736. # 'rangeSelector': {'selected': 1},
  2737. # 'yAxis': [
  2738. # {'labels': {'align': 'right', 'x': -3}, 'title': {'text': 'OHLC'}, 'height': '60%', 'lineWidth': 2, 'resize': {'enabled': True}},
  2739. # {'labels': {'align': 'right', 'x': -3}, 'title': {'text': 'Volume'}, 'top': '65%', 'height': '35%', 'offset': 0, 'lineWidth': 2}
  2740. # ],
  2741. # 'tooltip': {'split': True},
  2742. # 'series': [
  2743. # {'type': 'candlestick', 'tooltip': {'valueDecimals': 2}, 'dataGrouping': {'units': grouping_units}},
  2744. # {'type': 'column', 'name': 'Volume', 'yAxis': 1, 'dataGrouping': {'units': grouping_units}}
  2745. # ]
  2746. #}
  2747.  
  2748.  
  2749. #def convert_date(date_string):
  2750. # date = datetime.strptime(date_string, '%Y-%m-%d')
  2751. # return (date - epoch).total_seconds()*1000
  2752.  
  2753.  
  2754. #async def stock_test(request):
  2755. # wp = jp.WebPage(highcharts_theme='grid')
  2756. # ticker = request.query_params.get('ticker', 'MSFT').upper()
  2757. # if ticker not in ['AAPL', 'IBM', 'INTC', 'MSFT']:
  2758. # ticker = 'MSFT'
  2759. # data = await jp.JustPy.loop.run_in_executor(None, pd.read_csv, f'https://elimintz.github.io/stocks/{ticker}.csv')
  2760. # chart = jp.HighStock(a=wp, classes='m-1 p-2 border w-10/12', options=chart_dict, style='height: 600px')
  2761. # o = chart.options
  2762. # o.title.text = f'{ticker} Historical Prices'
  2763. # x = list(data['Date'].map(convert_date))
  2764. # o.series[0].data = list(zip(x, data['Open'], data['High'], data['Low'], data['Close']))
  2765. # o.series[0].name = ticker
  2766. # o.series[1].data = list(zip(x, data['Volume']))
  2767. # return wp
  2768.  
  2769.  
  2770. #from random import randrange
  2771.  
  2772.  
  2773. #chart_dict = {
  2774. # 'title': {'text': 'Updating Chart'},
  2775. # 'series': [
  2776. # {'name': 'Random Column', 'type': 'column', 'animation': False, 'data': [randrange(100) for i in range(50)]},
  2777. # {'name': 'Random Scatter', 'type': 'scatter', 'animation': False, 'data': [randrange(100) for i in range(50)]}
  2778. # ],
  2779. # }
  2780.  
  2781. #wp = jp.WebPage(delete_flag=False)
  2782. #chart = jp.HighCharts(a=wp, options=chart_dict, classes='m-1 p-2 border w-10/12')
  2783.  
  2784.  
  2785. #async def chart_updater():
  2786. # while True:
  2787. # await asyncio.sleep(1)
  2788. # for i in range(0,2):
  2789. # chart.options.series[i].data.pop(0)
  2790. # chart.options.series[i].data.append(randrange(100))
  2791. # jp.run_task(wp.update())
  2792.  
  2793.  
  2794. #async def chart_init():
  2795. # jp.run_task(chart_updater())
  2796.  
  2797. #async def chart_test():
  2798. # return wp
  2799.  
  2800.  
  2801.  
  2802.  
  2803. #iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
  2804. #iris_stats = iris.describe().round(3)
  2805. #iris_stats.insert(loc=0, column='stats', value=iris_stats.index)
  2806. #iris_species = list(iris['species'].unique())
  2807.  
  2808. ## Create a dictionary of frames per iris species
  2809. #iris_species_frames = {}
  2810. #for s in iris_species:
  2811. # iris_species_frames[s] = iris.loc[iris['species'] == s]
  2812.  
  2813. #async def click_point(self, msg):
  2814. # print(msg)
  2815. # return await self.select_point([{'id': chart_id, 'series': msg.series_index, 'point': msg.point_index} for chart_id in self.chart_list if self.id != chart_id], msg.websocket)
  2816.  
  2817.  
  2818. #async def tooltip_formatter(self, msg):
  2819. # # print(msg)
  2820. # tooltip_html = f"""
  2821. # <div style="color: {msg.color}"><span>&#x25CF;</span> {msg.series_name}</div>
  2822. # <div style="color: {msg.color}">{self.col2}: {msg.x}</div>
  2823. # <div style="color: {msg.color}">{self.col1}: {msg.y}</div>
  2824. # """
  2825. # await self.draw_crosshair([{'id': chart_id, 'series': msg.series_index, 'point': msg.point_index} for chart_id in self.chart_list], msg.websocket)
  2826. # return await self.tooltip_update(tooltip_html, msg.websocket)
  2827.  
  2828.  
  2829. #def iris_data():
  2830. # wp = jp.WebPage(highcharts_theme='gray', title='Iris Dataset')
  2831. # jp.Div(text='Iris Dataset', classes='text-3xl m-2 p-2 font-medium tracking-wider text-yellow-300 bg-gray-800 text-center', a=wp)
  2832. # d1 = jp.Div(classes='m-2 p-2 border-2', a=wp)
  2833. # chart_list = []
  2834. # for i, col1 in enumerate(iris.columns[:4]):
  2835. # d2 = jp.Div(classes='flex', a=d1)
  2836. # for j, col2 in enumerate(iris.columns[:4]):
  2837. # if i != j: # Not on the diagonal
  2838. # chart = jp.HighCharts(a=d2, style='width: 300px; height: 300px', classes='flex-grow m-1')
  2839. # chart_list.append(chart.id)
  2840. # chart.chart_list = chart_list
  2841. # chart.on('tooltip', tooltip_formatter)
  2842. # chart.tooltip_y = 85
  2843. # chart.on('point_click', click_point)
  2844. # chart.col1 = col1
  2845. # chart.col2 = col2
  2846. # o = chart.options
  2847. # o.chart.type = 'scatter'
  2848. # o.chart.zoomType = 'xy'
  2849. # o.title.text = ''
  2850. # o.legend.enabled = False
  2851. # o.credits.enabled = False if i<3 or j<3 else True # https://api.highcharts.com/highcharts/credits.enabled
  2852. # o.xAxis.title.text = col2 if i==3 else ''
  2853. # o.yAxis.title.text = col1 if j==0 else ''
  2854. # o.xAxis.crosshair = o.yAxis.crosshair = True
  2855. # for k, v in iris_species_frames.items():
  2856. # s = jp.Dict()
  2857. # s.name = k
  2858. # s.allowPointSelect = True # https://api.highcharts.com/highcharts/series.scatter.allowPointSelect
  2859. # s.marker.states.select.radius = 8
  2860. # s.data = list(zip(v.iloc[:, j], v.iloc[:, i]))
  2861. # o.series.append(s)
  2862. # else:
  2863. # chart = jp.Histogram(list(iris.iloc[:, j]),a=d2, style='width: 300px; height: 300px', classes='flex-grow m-1')
  2864. # o = chart.options
  2865. # o.title.text = ''
  2866. # o.legend.enabled = False
  2867. # o.xAxis[0].title.text = col2 if i==3 else ''
  2868. # o.xAxis[1].title.text = ''
  2869. # o.yAxis[0].title.text = col1 if j == 0 else ''
  2870. # o.yAxis[1].title.text = ''
  2871. # o.credits.enabled = False if i < 3 or j < 3 else True
  2872.  
  2873. # # Add two grids, first with the data and second with statistics describing the data
  2874. # iris.jp.ag_grid(a=wp, classes='m-2 p-2', style='height: 500px; width: 800px', auto_size=True, theme='ag-theme-balham-dark')
  2875. # iris_stats.jp.ag_grid(a=wp, classes='m-2 p-2 border', style='height: 500px; width: 950px', auto_size=True, theme='ag-theme-material')
  2876. # return wp
  2877.  
  2878.  
  2879.  
  2880.  
  2881.  
  2882. #class MyPie(jp.HighCharts):
  2883.  
  2884. # _options = """
  2885. #{
  2886. # chart: {
  2887. # type: 'pie'
  2888. # },
  2889. # title: {
  2890. # text: 'Pie Chart'
  2891. # },
  2892. # tooltip: {
  2893. # pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
  2894. # },
  2895. # plotOptions: {
  2896. # pie: {
  2897. # allowPointSelect: true,
  2898. # cursor: 'pointer',
  2899. # dataLabels: {
  2900. # enabled: true,
  2901. # format: '<b>{point.name}</b>: {point.percentage:.1f}%',
  2902. # }
  2903. # }
  2904. # },
  2905. # series: []
  2906. #}
  2907. # """
  2908.  
  2909. # def __init__(self, data, **kwargs):
  2910. # self.labels = []
  2911. # super().__init__(**kwargs)
  2912. # self.load_json(self._options)
  2913. # pie_series = jp.Dict()
  2914. # pie_series.data = []
  2915. # for i, value in enumerate(data):
  2916. # c = jp.Dict()
  2917. # try:
  2918. # c.name = self.labels[i]
  2919. # except:
  2920. # c.name = str(value)
  2921. # c.y = value
  2922. # pie_series.data.append(c)
  2923. # self.options.series.append(pie_series)
  2924.  
  2925.  
  2926. #def pie_test(request):
  2927. # wp = jp.WebPage()
  2928. # chart = MyPie([2,3,4,5], labels=['Apples', 'Pears', 'Bananas', 'Melons'], a=wp, classes='m-2 p-2 border w-1/2')
  2929. # chart.options.title.text = 'Fruit Distribution'
  2930. # chart.options.series[0].name = 'Fruits'
  2931. # return wp
  2932.  
  2933.  
  2934.  
  2935. #import random
  2936. #import numpy
  2937.  
  2938. #class Histogram(jp.HighCharts):
  2939.  
  2940. # _options = """
  2941. #{
  2942. # title: {
  2943. # text: 'Highcharts Histogram'
  2944. # },
  2945. # xAxis: [{
  2946. # title: { text: 'Data' },
  2947. # alignTicks: false
  2948. # }, {
  2949. # title: { text: 'Histogram' },
  2950. # alignTicks: false,
  2951. # opposite: true
  2952. # }],
  2953.  
  2954. # yAxis: [{
  2955. # title: { text: 'Data' }
  2956. # }, {
  2957. # title: { text: 'Histogram' },
  2958. # opposite: true
  2959. # }],
  2960.  
  2961. # series: [{
  2962. # name: 'Histogram',
  2963. # type: 'histogram',
  2964. # xAxis: 1,
  2965. # yAxis: 1,
  2966. # baseSeries: 's1',
  2967. # zIndex: -1
  2968. # }, {
  2969. # name: 'Data',
  2970. # type: 'scatter',
  2971. # data: [],
  2972. # id: 's1',
  2973. # marker: {
  2974. # radius: 1.5
  2975. # }
  2976. # }]
  2977. #}
  2978.  
  2979. # """
  2980.  
  2981. # def __init__(self, data, **kwargs):
  2982. # super().__init__(**kwargs)
  2983. # self.load_json(self._options)
  2984. # self.options.series[1].data = list(data)
  2985.  
  2986. #def histogram_test(request):
  2987. # wp = jp.WebPage()
  2988. # # Uniform distribution
  2989. # data = [random.randrange(10) for i in range(100)]
  2990. # chart = jp.Histogram(data, a=wp, classes='m-2 border w-1/2')
  2991. # chart.options.title.text = 'Uniform Distribution Histogram'
  2992. # # Normal distribution
  2993. # data = [numpy.random.normal() for i in range(1000)]
  2994. # chart = jp.Histogram(data, a=wp, classes='m-2 border w-1/2')
  2995. # chart.options.title.text = 'Normal Distribution Histogram'
  2996. # return wp
  2997.  
  2998.  
  2999.  
  3000.  
  3001. #import numpy as np
  3002.  
  3003. #class ScatterWithRegression(jp.Scatter):
  3004.  
  3005. # def __init__(self, x, y, **kwargs):
  3006. # super().__init__(x, y, **kwargs)
  3007. # x = np.asarray(x)
  3008. # y = np.asarray(y)
  3009. # m = (len(x) * np.sum(x * y) - np.sum(x) * np.sum(y)) / (len(x) * np.sum(x * x) - np.sum(x) ** 2)
  3010. # b = (np.sum(y) - m * np.sum(x)) / len(x)
  3011. # s = jp.Dict() # The new series
  3012. # s.type = 'line'
  3013. # s.marker.enabled = False
  3014. # s.enableMouseTracking = False
  3015. # min = float(x.min())
  3016. # max = float(x.max())
  3017. # s.data = [[min, m * min + b], [max, m * max + b]]
  3018. # s.name = f'Regression, m: {round(m, 3)}, b: {round(b, 3)}'
  3019. # self.options.series.append(s)
  3020.  
  3021.  
  3022. #def scatter_test(request):
  3023. # wp = jp.WebPage(highcharts_theme='grid-light')
  3024. # x = [108,19,13,124,40,57,23,14,45,10,5,48,11,23,7,2,24,6,3,23,6,9,9,3,29,7,4,20,7,4,0,25,6,5,22,11,61,12,4,16,13,60,41,37,55,41,11,27,8,3,17,13,13,15,8,29,30,24,9,31,14,53,26]
  3025. # y = [392.5,46.2,15.7,422.2,119.4,170.9,56.9,77.5,214,65.3,20.9,248.1,23.5,39.6,48.8,6.6,134.9,50.9,4.4,113,14.8,48.7,52.1,13.2,103.9,77.5,11.8,98.1,27.9,38.1,0,69.2,14.6,40.3,161.5,57.2,217.6,58.1,12.6,59.6,89.9,202.4,181.3,152.8,162.8,73.4,21.3,92.6,76.1,39.9,142.1,93,31.9,32.1,55.6,133.3,194.5,137.9,87.4,209.8,95.5,244.6,187.5]
  3026. # jp.Scatter(x, y, a=wp, classes='m-2 w-1/2 border', style='height: 300px')
  3027. # sr = ScatterWithRegression(x, y, a=wp, classes='m-2 w-1/2 border', style='height: 300px')
  3028. # sr.options.title.text = 'Scatter Chart with Regression'
  3029. # return wp
  3030.  
  3031.  
  3032.  
  3033. #grid_options = """
  3034. #{
  3035. # defaultColDef: {
  3036. # filter: true,
  3037. # sortable: true,
  3038. # resizable: true,
  3039. # cellStyle: {textAlign: 'center'},
  3040. # headerClass: 'font-bold'
  3041. # },
  3042. # columnDefs: [
  3043. # {headerName: "Make", field: "make"},
  3044. # {headerName: "Model", field: "model"},
  3045. # {headerName: "Price", field: "price"}
  3046. # ],
  3047. # rowData: [
  3048. # {make: "Toyota", model: "Celica", price: 35000},
  3049. # {make: "Ford", model: "Mondeo", price: 32000},
  3050. # {make: "Porsche", model: "Boxter", price: 72000}
  3051. # ]
  3052. #}
  3053. #"""
  3054.  
  3055. ##def grid_test():
  3056. ## wp = jp.WebPage()
  3057. ## grid = jp.AgGrid(a=wp, options=grid_options)
  3058. ## return wp
  3059.  
  3060. #def grid_test():
  3061. # wp = jp.WebPage()
  3062. # grid = jp.AgGrid(a=wp, options=grid_options, style='height: 200px; width: 300px; margin: 0.25em')
  3063. # for col_def in grid.options.columnDefs:
  3064. # col_def.editable = True
  3065. # grid.options.columnDefs[1].cellClass = ['text-2xl','text-red-500','hover:bg-blue-500']
  3066. # return wp
  3067.  
  3068.  
  3069.  
  3070.  
  3071. #grid_options = {
  3072. # 'rowHeight': 200,
  3073. # 'columnDefs': [
  3074. # {'headerName': "Make", 'field': "make"},
  3075. # {'headerName': "Model", 'field': "model"},
  3076. # {'headerName': "Price", 'field': "price"},
  3077. # ],
  3078. # 'rowData': [
  3079. # {'make': "Toyota", 'model': "Celica", 'price': 4},
  3080. # {'make': "Ford", 'model': "Mondeo", 'price': '<div class="m-2 text-red-500 text-5xl">3</div>'},
  3081. # {'make': "Porsche", 'model': "Boxter", 'price': '<img src="https://www.python.org/static/community_logos/python-powered-h-140x182.png">'}
  3082. # ],
  3083. #}
  3084.  
  3085. #def grid_test():
  3086. # wp = jp.WebPage()
  3087. # grid = jp.AgGrid(a=wp, options=grid_options)
  3088. # grid.html_columns = [2]
  3089. # return wp
  3090.  
  3091.  
  3092.  
  3093. #wm_df = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
  3094.  
  3095. #def grid_test():
  3096. # wp = jp.WebPage()
  3097. # grid = jp.AgGrid(a=wp)
  3098. # grid.load_pandas_frame(wm_df)
  3099. # return wp
  3100.  
  3101.  
  3102.  
  3103. #wm_df = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
  3104.  
  3105. #def grid_test():
  3106. # wp = jp.WebPage()
  3107. # wm_df.jp.ag_grid(a=wp)
  3108. # return wp
  3109.  
  3110.  
  3111.  
  3112.  
  3113. #wm_df = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
  3114.  
  3115. #def grid_test():
  3116. # wp = jp.WebPage()
  3117. # grid = wm_df.jp.ag_grid(a=wp)
  3118. # grid.options.pagination = True
  3119. # grid.options.paginationAutoPageSize = True
  3120. # grid.options.columnDefs[0].cellClass = ['text-white', 'bg-blue-500', 'hover:bg-blue-200']
  3121. # for col_def in grid.options.columnDefs[1:]:
  3122. # col_def.cellClassRules = {
  3123. # 'font-bold': 'x < 20',
  3124. # 'bg-red-300': 'x < 20',
  3125. # 'bg-yellow-300': 'x >= 20 && x < 50',
  3126. # 'bg-green-300': 'x >= 50'
  3127. # }
  3128. # return wp
  3129.  
  3130.  
  3131.  
  3132. grid_options = """
  3133. {
  3134. rowSelection: 'multiple',
  3135. defaultColDef: {
  3136. filter: true,
  3137. sortable: true,
  3138. resizable: true,
  3139. cellStyle: {textAlign: 'center'},
  3140. headerClass: 'font-bold'
  3141. },
  3142. columnDefs: [
  3143. {headerName: "Make", field: "make"},
  3144. {headerName: "Model", field: "model"},
  3145. {headerName: "Price", field: "price"}
  3146. ],
  3147. rowData: [
  3148. {make: "Toyota", model: "Celica", price: 35000},
  3149. {make: "Ford", model: "Mondeo", price: 32000},
  3150. {make: "Porsche", model: "Boxter", price: 72000}
  3151. ]
  3152. }
  3153. """
  3154.  
  3155. def row_selected(self, msg):
  3156. wp = msg.page
  3157. if msg.selected:
  3158. wp.selected_rows[msg.rowIndex] = msg.data
  3159. else:
  3160. wp.selected_rows.pop(msg.rowIndex)
  3161. s = f'Selected rows {sorted(list(wp.selected_rows.keys()))}'
  3162. for i in sorted(wp.selected_rows):
  3163. s = f'{s}\n Row {i} Data: {wp.selected_rows[i]}'
  3164. if wp.selected_rows:
  3165. wp.rows_div.text = s
  3166. else:
  3167. wp.rows_div.text = 'No row selected'
  3168.  
  3169.  
  3170. async def select_all_rows(self, msg):
  3171. await self.grid.run_api('selectAll()', msg.page)
  3172.  
  3173.  
  3174. async def deselect_rows(self, msg):
  3175. await self.grid.run_api('deselectAll()', msg.page)
  3176.  
  3177.  
  3178. def grid_test():
  3179. wp = jp.WebPage()
  3180. wp.selected_rows = {} # Dictionary holding selected rows
  3181. grid = jp.AgGrid(a=wp, options=grid_options, style='height: 200px; width: 300px; margin: 0.25em')
  3182. grid.options.columnDefs[0].checkboxSelection = True
  3183. grid.on('rowSelected', row_selected)
  3184. wp.rows_div = jp.Pre(text='Data will go here when you select rows', classes='border text-lg', a=wp)
  3185. btn_deselect = jp.Button(text='Deselect rows', classes=jp.Styles.button_simple+' m-2', a=wp, click=deselect_rows)
  3186. btn_deselect.grid = grid
  3187. btn_select_all = jp.Button(text='Select all rows', classes=jp.Styles.button_simple+' m-2', a=wp, click=select_all_rows)
  3188. btn_select_all.grid = grid
  3189. return wp
  3190.  
  3191.  
  3192. # Load data showing percent of women in different majors per year
  3193. #wm = pd.read_csv('./snapshot1.csv')
  3194. #wm = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
  3195.  
  3196. def grid_test():
  3197. wp = jp.WebPage()
  3198. wm.jp.ag_grid(a=wp) # a=wp adds the grid to WebPage wp
  3199. #while True:
  3200. # jp.run_task(wp.update())
  3201. # #time.sleep(5)
  3202. return wp
  3203.  
  3204. class AggregationPeriod(str, Enum):
  3205. min_1 = "1min"
  3206. min_2 = "2min"
  3207. min_3 = "3min"
  3208. min_5 = "5min"
  3209. min_10 = "10min"
  3210. min_15 = "15min"
  3211. min_20 = "20min"
  3212. min_30 = "30min"
  3213. min_39 = "39min"
  3214. min_78 = "78min"
  3215. min_130 = "130min"
  3216. min_195 = "195min"
  3217. hour_1 = "1H"
  3218. hour_2 = "2H"
  3219. hour_4 = "4H"
  3220.  
  3221. def bar_start_end(request_datetime, market_start_datetime='2021-11-12 8:30:00', market_end_datetime='2021-11-12 15:00:00', resolution = AggregationPeriod.min_1):
  3222.  
  3223. date_rng = pd.date_range(start=market_start_datetime, end=market_end_datetime, freq=resolution)
  3224.  
  3225.  
  3226. for i in range(len(date_rng)):
  3227. if i >= 1:
  3228. if (request_datetime in DateTimeRange(date_rng[i - 1], (date_rng[i] - timedelta(seconds = 1)))):
  3229. return str(date_rng[i - 1]), str((date_rng[i] - timedelta(seconds = 1)))
  3230.  
  3231.  
  3232. #def between_periods(request_datetime, resolution):
  3233. # print(request_datetime)
  3234. # global date_rng
  3235. # bar_start_end(startdatetime='2021-11-12 8:30:00', enddatetime='2021-11-12 15:00:00', resolution=resolution)
  3236. # print(' --- ')
  3237.  
  3238.  
  3239. # for i in range(len(date_rng)):
  3240. # if i >= 1:
  3241. # #print(request_datetime in DateTimeRange(date_rng[i - 1], (date_rng[i] - timedelta(seconds = 1))))
  3242. # if (request_datetime in DateTimeRange(date_rng[i - 1], (date_rng[i] - timedelta(seconds = 1)))):
  3243. # #if time.strptime(request_datetime, '%Y-%m-%d %H:%M:%S') >= date_rng[i - 1] and time.strptime(request_datetime, '%Y-%m-%d %H:%M:%S') <= (date_rng[i] - timedelta(seconds = 1)):
  3244. # return str(date_rng[i - 1]), str((date_rng[i] - timedelta(seconds = 1)))
  3245. # #print(date_rng[i - 1], ' - ', date_rng[i] - timedelta(seconds = 1))
  3246.  
  3247.  
  3248. #def between_periods2(request_datetime, day_start_datetime='2021-11-12 8:30:00', day_end_datetime='2021-11-12 15:00:00', resolution = AggregationPeriod.min_1):
  3249. # print(request_datetime)
  3250. # global date_rng
  3251. # bar_start_end(startdatetime='2021-11-12 8:30:00', enddatetime='2021-11-12 15:00:00', resolution=resolution)
  3252. # print(' --- ')
  3253.  
  3254.  
  3255. # for i in range(len(date_rng)):
  3256. # if i >= 1:
  3257. # #print(request_datetime in DateTimeRange(date_rng[i - 1], (date_rng[i] - timedelta(seconds = 1))))
  3258. # if (request_datetime in DateTimeRange(date_rng[i - 1], (date_rng[i] - timedelta(seconds = 1)))):
  3259. # #if time.strptime(request_datetime, '%Y-%m-%d %H:%M:%S') >= date_rng[i - 1] and time.strptime(request_datetime, '%Y-%m-%d %H:%M:%S') <= (date_rng[i] - timedelta(seconds = 1)):
  3260. # return str(date_rng[i - 1]), str((date_rng[i] - timedelta(seconds = 1)))
  3261. # #print(date_rng[i - 1], ' - ', date_rng[i] - timedelta(seconds = 1))
  3262.  
  3263.  
  3264.  
  3265. def main():
  3266.  
  3267.  
  3268. #stocks_client = polygon.StocksClient(stocks_key)
  3269.  
  3270. #current_price = stocks_client.get_current_price('AMD')
  3271.  
  3272. #print(current_price)
  3273. #return
  3274. #print('min_1')
  3275. #print(bar_start_end('2021-11-12 8:38:59', market_start_datetime='11/12/2021 8:30:00', market_end_datetime='11/12/2021 15:00:00', resolution=AggregationPeriod.min_1))
  3276. #print('')
  3277. #print('min_5')
  3278. #print(bar_start_end('2021-11-12 8:38:59', market_start_datetime='11/12/2021 8:30:00', market_end_datetime='11/12/2021 15:00:00', resolution=AggregationPeriod.min_5))
  3279. #print('')
  3280. #print('min_39')
  3281. #print(bar_start_end('2021-11-12 8:38:59', market_start_datetime='11/12/2021 8:30:00', market_end_datetime='11/12/2021 15:00:00', resolution=AggregationPeriod.min_39))
  3282. #print('')
  3283. #print('min_78')
  3284. #print(bar_start_end('2021-11-12 8:38:59', market_start_datetime='11/12/2021 3:00:00', market_end_datetime='11/12/2021 19:00:00', resolution=AggregationPeriod.min_78))
  3285. #print('')
  3286. #print('min_130')
  3287. #print(bar_start_end('2021-11-12 8:38:59', market_start_datetime='11/12/2021 8:30:00', market_end_datetime='11/12/2021 15:00:00', resolution=AggregationPeriod.min_130))
  3288. #print('')
  3289. #print('min_195')
  3290. #print(bar_start_end('2021-11-12 8:38:59', market_start_datetime='11/12/2021 8:30:00', market_end_datetime='11/12/2021 15:00:00', resolution=AggregationPeriod.min_195))
  3291. #print('')
  3292. #print('hour_1')
  3293. #print(bar_start_end('2021-11-12 8:38:59', market_start_datetime='11/12/2021 8:30:00', market_end_datetime='11/12/2021 15:00:00', resolution=AggregationPeriod.hour_1))
  3294. #print('')
  3295. #print('hour_2')
  3296. #print(bar_start_end('2021-11-12 8:38:59', market_start_datetime='11/12/2021 8:30:00', market_end_datetime='11/12/2021 15:00:00', resolution=AggregationPeriod.hour_2))
  3297. #print('')
  3298. #print('hour_4')
  3299. #print(bar_start_end('2021-11-12 8:38:59', market_start_datetime='11/12/2021 8:30:00', market_end_datetime='11/12/2021 15:00:00', resolution=AggregationPeriod.hour_4))
  3300. #print('')
  3301.  
  3302. #return
  3303. #jp.justpy(grid_test)
  3304. #return
  3305. #jp.justpy(clock_test, startup=clock_init)
  3306. #jp.justpy(count_test)
  3307. #jp.justpy(message_demo, startup=message_initialize)
  3308. #jp.justpy(reload_demo, startup=start_counting, websockets=False)
  3309. #jp.justpy(stock_test)
  3310. #jp.justpy(chart_test, startup=chart_init)
  3311. #jp.justpy(iris_data)
  3312. #jp.justpy(pie_test)
  3313. #jp.justpy(histogram_test)
  3314. #jp.justpy(scatter_test)
  3315. #jp.justpy(grid_test)
  3316. #return
  3317. # Format database and empty previous values
  3318. #df = pd.DataFrame([['delete_this_row', 0, 0, 0, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0, 0, 0, datetime.today(), datetime.today()]],
  3319. # columns=['symbol', 'tick_volume',
  3320. # 'total_volume', 'opening_price', 'tick_vwap', 'tick_open', 'tick_close', 'tick_high',
  3321. # 'tick_low', 'vwap', 'avg_trade_size', 'time_beg', 'time_end', 'tdate', 'save_date'])
  3322.  
  3323. #s = stocks.StocksPolygon
  3324. #pprint.pprint(s.get_daily_stock_open_close('TSLA'))
  3325. #return
  3326.  
  3327. #ref = reference.ReferencePolygon
  3328. #get_option_trades(ref.convert_tda_option_to_polygon('TSLA_021822P1950'), timestamp='2021-10-28')
  3329. #return
  3330. # Backup table
  3331. #print("backing up table")
  3332. # df.to_sql('stockdata_backup', engine, if_exists='replace', index=False)
  3333. # query1 = text("DELETE FROM stockdata_backup WHERE symbol = 'delete_this_row';")
  3334. #query1 = text("DROP TABLE IF EXISTS stockdata_backup;")
  3335. #query2 = text("create table stockdata_backup as (select * from stockdata_hist);")
  3336. #with engine.connect() as conn:
  3337. # conn.execute(query1)
  3338. # conn.execute(query2)
  3339.  
  3340. #Create main table
  3341. #df.to_sql('stockdata_hist', engine, if_exists='replace', index=False)
  3342. #query2 = text("DELETE FROM stockdata_hist WHERE symbol = 'delete_this_row';")
  3343. ##with engine.connect() as conn:
  3344. ## conn.execute(query2)
  3345.  
  3346. # Get new data
  3347. #with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count()) as executor:
  3348. ## #executor.map(get_data1, symbols)
  3349. ### #for future in concurrent.futures.as_completed(futures):
  3350. # #future1 = executor.map(get_bars, symbols)
  3351. # #future2 = executor.map(get_trades, symbols)
  3352. # #future3 = executor.map(get_quotes, symbols)
  3353. # for symbol in symbols:
  3354. # future1 = executor.submit(get_bars, symbol)
  3355. #future2 = executor.submit(get_trades, symbol)
  3356. #future3 = executor.submit(get_quotes, symbol)
  3357. #future4 = executor.submit(get_daily_stock_open_close, symbol)
  3358. #future5 = executor.submit(get_trades, symbol)
  3359. #start_date = date(2021, 10, 25)
  3360. #end_date = date(2021, 10, 29)
  3361. #delta = timedelta(days=1)
  3362.  
  3363. #while start_date <= end_date:
  3364. # print(start_date)
  3365. # start_date += delta
  3366.  
  3367. #return
  3368.  
  3369. #ref = reference.ReferencePolygon
  3370. #symbols_df = pd.read_sql_query('select distinct symbol from option_chain where tdate >= \'2021-11-15\' order by symbol ', con=conn)
  3371. ####symbols_df = pd.read_csv('data/polygon/options_symbols.csv')
  3372. ####symbols = symbols_df['symbol'].to_list()
  3373. #####symbols = 'TSLA_102921C1100'
  3374. #####symbols_list1 = "TSLA,AAPL"
  3375. #####symbols_list1 = symbols
  3376. #####get_stocks_snapshot(symbols_list1.split(','))
  3377. #####get_stocks_snapshot(symbols)
  3378. #####redis_dict_update()
  3379. #####return
  3380. #####get_stocks_snapshot()
  3381. #####return
  3382.  
  3383. #####jp.justpy(comp_test)
  3384. #####jp.justpy(grid_test)
  3385. #####while True:
  3386. #get_stocks_snapshot()
  3387. #####get_historical_data(symbols)
  3388. #####return
  3389.  
  3390.  
  3391. ##trades_df = pd.read_sql_query('SELECT symbol as sym, price as p, trade_size as s, trade_time as t FROM public.stocksdata_trades order by trade_time-- limit 10000', con=conn)
  3392. ###symbols_df = pd.read_csv('data/polygon/options_symbols.csv')
  3393. ##i = 1
  3394. ##for trade in trades_df.iterrows():
  3395. ## print(i)
  3396. ## i+=1
  3397. ## on_tick(trade)
  3398.  
  3399. #return
  3400.  
  3401. z = time.time()
  3402.  
  3403.  
  3404. my_client = polygon.StreamClient(stocks_key, polygon.enums.StreamCluster('stocks'), on_message=stock_trades_process_message,
  3405. on_close=stock_trades_close_handler, on_error=stock_trades_error_handler)
  3406. try:
  3407. my_client.start_stream_thread()
  3408. my_client.subscribe_stock_trades()
  3409. #my_client.subscribe_stock_trades(list('TSLA'))
  3410.  
  3411. print(time.time()-z)
  3412. return
  3413.  
  3414. except Exception:
  3415. traceback.print_exc()
  3416. my_client.unsubscribe_stock_trades()
  3417. return
  3418.  
  3419. #with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count() * 20) as executor:
  3420. with concurrent.futures.ThreadPoolExecutor(max_workers=450) as executor:
  3421. #executor.map(get_data1, symbols)
  3422. # #for future in concurrent.futures.as_completed(futures):
  3423. #future1 = executor.map(get_bars, symbols)
  3424. #future2 = executor.map(get_trades, symbols)
  3425. #future3 = executor.map(get_quotes, symbols)
  3426. #for symbol in symbols:
  3427. # future1 = executor.submit(get_bars, symbol)
  3428.  
  3429. #symbol = 'TSLA_102921C1100'
  3430. for symbol in symbols:
  3431. #get_option_trades(ref.convert_tda_option_to_polygon(symbol))
  3432.  
  3433. #start_date = date(2021, 11, 8)
  3434. #end_date = date(2021, 11, 11)
  3435. #delta = timedelta(days=1)
  3436. future1 = executor.submit(get_latest_bar, symbol, 'minute')
  3437.  
  3438. print(latest_min_bar_df)
  3439. print(time.time()-z)
  3440. #print(time.time()-z)
  3441.  
  3442.  
  3443. ##with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count() * 20) as executor:
  3444. #with concurrent.futures.ThreadPoolExecutor(49) as executor:
  3445. # #executor.map(get_data1, symbols)
  3446. ## #for future in concurrent.futures.as_completed(futures):
  3447. # #future1 = executor.map(get_bars, symbols)
  3448. # #future2 = executor.map(get_trades, symbols)
  3449. # #future3 = executor.map(get_quotes, symbols)
  3450. # #for symbol in symbols:
  3451. # # future1 = executor.submit(get_bars, symbol)
  3452. # for symbol in symbols:
  3453. # #get_option_trades(ref.convert_tda_option_to_polygon(symbol))
  3454.  
  3455. # start_date = date(2021, 10, 25)
  3456. # end_date = date(2021, 10, 29)
  3457. # delta = timedelta(days=1)
  3458.  
  3459. # while start_date <= end_date:
  3460. # print(symbol, start_date)
  3461. # future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
  3462. # #future1 = executor.submit(get_bars, symbol)
  3463. # #future2 = executor.submit(get_trades, symbol)
  3464. # #future3 = executor.submit(get_quotes, symbol)
  3465. # #future4 = executor.submit(get_daily_stock_open_close, symbol)
  3466. # start_date += delta
  3467.  
  3468.  
  3469. #get_option_trades('TSLA211029C001150000')
  3470.  
  3471. #get_conditions()
  3472.  
  3473. #pprint.pprint(future4)
  3474.  
  3475. #big_df = pd.Dataframe()
  3476. #temp_df = future1#function_that_gets_temp_df()
  3477. #big_df = pd.concat([temp_df, big_df])
  3478. #big_df.to_sql('stockdata_hist_bars', engine, if_exists='append', index=False, method='multi')
  3479.  
  3480. #s = stocks.StocksPolygon
  3481. #threading.Thread(target=get_data1, args=[symbols]).start()
  3482. #threading.Thread(target=get_data2, args=[symbols]).start()
  3483. #threading.Thread(target=get_data3, args=[symbols]).start()
  3484.  
  3485.  
  3486. #await get_historic_bars(symbols, start, end, timeframe)
  3487. #await get_historic_trades(symbols, start, end, timeframe)
  3488. #await get_historic_quotes(symbols, start, end, timeframe)
  3489.  
  3490. #get_data1(symbols)
  3491. #get_data2(symbols)
  3492. #get_data3(symbols)
  3493.  
  3494. #query3 = text("CREATE INDEX idx_sdh_tdate ON stockdata_hist (tdate);")
  3495. #query4 = text("CREATE INDEX idx_sdh_symbol ON stockdata_hist (symbol);")
  3496. ##with engine.connect() as conn:
  3497. ## conn.execute(query3)
  3498. ## conn.execute(query4)
  3499.  
  3500. def is_mkt_open(market):
  3501. now = datetime.now(pytz.utc)
  3502. TDate = date.today() # get today's date
  3503. mkt = mcal.get_calendar(market)
  3504. tradingDay = mkt.schedule(start_date=TDate, end_date=TDate)
  3505. # print(tradingDay)
  3506. try:
  3507. Mopen = tradingDay.iloc[0]
  3508. Mclose = tradingDay.iloc[0]
  3509. Mopen = Mopen[0]
  3510. Mclose = Mclose[1]
  3511. if now > Mopen:
  3512. if now < Mclose:
  3513. market_open = True
  3514. else:
  3515. market_open = False
  3516. else:
  3517. market_open = False
  3518. except Exception as exe:
  3519. market_open = False
  3520. # market_open = True # Force True for testing
  3521. return market_open
  3522.  
  3523.  
  3524. if __name__ == '__main__':
  3525. #is_mkt_open('DJIA')
  3526. start_time = time.time()
  3527. main()
  3528. print(time.time() - start_time)
  3529. time_hr = (time.time() - start_time)/3600
  3530. print(time_hr, " hrs")
  3531.  
  3532. class ndict(dict):
  3533. def __getitem__(self, key):
  3534. if key in self: return self.get(key)
  3535. return self.setdefault(key, ndict())
Advertisement
Add Comment
Please, Sign In to add comment