Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pandas as pd
- from enum import Enum
- from psycopg2 import pool
- from sqlalchemy import create_engine, text
- from datetime import date, datetime, timedelta, timezone
- import concurrent.futures
- import requests as rq
- import requests
- import time
- #import .config.config
- import os
- import sys
- sys.path.append(os.path.abspath('config/'))
- import config
- #from config.config import config
- import traceback
- import stocks
- import options
- import reference
- import multiprocessing
- import threading
- import pprint
- import pytz
- import pandas_market_calendars as mcal
- import json
- import redis
- import io
- import csv
- import re
- import pickle
- from collections import defaultdict
- import asyncio
- #import justpy as jp
- from redis_dict import RedisDict
- #import unittest
- import dateutil.parser
- from datetimerange import DateTimeRange
- import polygon
- from polygon import enums, cred
- from requests.models import Response
- from httpx import Response as HttpxResponse
- from typing import Union
- import httpx
- sys.path.append(os.path.abspath('big/'))
- from resample_price_indicators import resample
- options_key = config.polygon_key_options
- #stocks_key = config.polygon_key_stocks
- stocks_key = cred.KEY
- pd.set_option('display.max_columns', None)
- #pd.set_option('display.max_rows', None)
- # Key
- key = config.polygon_key_stocks
- r = redis.Redis(host=config.redis_host, port=config.redis_port, charset="utf-8", decode_responses=True)
- r_dict = RedisDict(host=config.redis_host, port=config.redis_port, charset="utf-8")
- ## Input
- #multiplier = 1
- #timespan = 'minute'
- #adjusted = 'true'
- #sort = 'desc'
- #limit = 50000
- # Database / Get list of tickers
- engine = create_engine(config.psql, pool_size=400, max_overflow=75)
- postgreSQL_pool = pool.ThreadedConnectionPool(200, 295, host=config.psql_host, database=config.psql_db,
- user=config.psql_user, password=config.psql_pw)
- #engine = create_engine(postgreSQL_pool)
- conn = postgreSQL_pool.getconn()
- # code that uses a connection
- postgreSQL_pool.putconn(conn)
- #engine = conn
- #symbols_df = pd.read_sql_query('select ticker from companies where active = true', con=conn)
- #symbols = symbols_df['ticker'].to_list()
- #print(symbols)
- #print(multiprocessing.cpu_count())
- stock_ticks_df = pd.DataFrame()
- one_minute_df = pd.DataFrame()
- bars_df = pd.DataFrame()
- latest_min_bar_df = pd.DataFrame()
- minutes_processed = {}
- minute_candlesticks = []
- current_tick = None
- previous_tick = None
- in_position = False
- big_df = pd.DataFrame()
- class DataType(str, Enum):
- Bars = "Bars"
- Trades = "Trades"
- Quotes = "Quotes"
- def get_data_method(data_type: DataType):
- if data_type == DataType.Bars:
- return rest.get_bars_async
- elif data_type == DataType.Trades:
- return rest.get_trades_async
- elif data_type == DataType.Quotes:
- return rest.get_quotes_async
- else:
- raise Exception(f"Unsupoported data type: {data_type}")
- class Historical_Data:
- def __init__(self):
- self.KEY = key # your key
- self.BASE = 'https://api.polygon.io'
- self.session = rq.session()
- self.session.headers.update({'Authorization': 'Bearer %s' % self.KEY})
- def get_response(self, path: str, params: dict = None):
- return self.session.request('GET', self.BASE + path, params=params).json()
- def get_next_page(self, url: str):
- return self.session.request('GET', url).json()
- def redis_message(list, messages):
- #print(messages)
- #print(type(messages))
- #print(messages)
- #print( json.dumps(messages))
- #return
- #for message in messages:
- # print(message)
- #return
- #r.hmset(list, json.dumps(messages))
- #r.hmgetall(list)
- #return
- #p_mydict = pickle.dumps(messages)
- #r.set('mydict',p_mydict)
- #read_dict = r.get('mydict')
- #yourdict = pickle.loads(read_dict)
- #print(yourdict)
- #return
- #r.hmset(list, json.dumps(messages))
- #r.hgetall(list)
- #return
- try:
- for message in messages:
- #print(message)
- r.rpush(list, json.dumps(message))
- #r.rpush('stock-list', json.dumps(message))
- except Exception:
- traceback.print_exc()
- return None
- def redis_dict_update(messages):
- #redis_dic = self.create_redis_dict()
- #dic = dict()
- #input_values = {
- # "int": 1,
- # "float": 0.9,
- # "str": "im a string",
- # "bool": True,
- # "None": None,
- #}
- print(' ')
- print(' ')
- print(' ')
- pprint.pprint(messages['todaysChangePerc'][:10])
- #pprint.pprint(messages['todaysChangePerc'], messages['symbol'])
- #self.assertEqual(len(redis_dic), 0)
- #self.assertEqual(len(dic), 0)
- #self.assertEqual(len(input_values), 5)
- ###r_dict.update('abc', messages)
- #dic.update(input_values)
- #assertEqual(len(r_dict), 5)
- #assertEqual(len(dic), 5)
- #assertEqual(len(input_values), 5)
- #print(len(r_dict))
- ##print(len(dic))
- ##print(len(input_values))
- #print(len(messages))
- #message_count = len(r_dict)
- #print('message count = ', message_count)
- ##for expected_key, expected_value in input_values.items():
- ##for expected_key, expected_value in messages.items():
- ## print(r_dict[expected_key], expected_value)
- # #print(dic[expected_key], expected_value)
- ##pprint.pprint(sorted(r_dict))
- ##expected = [dic.popitem() for _ in range(5)]
- ##result = [r_dict.popitem() for _ in range(7)]
- ##result = [r_dict.popitem() for _ in range(7)]
- ##i = 1
- ##for k in r_dict: #range(7)
- ## print(i)
- ## print(k)
- ## i += 1
- ## result = r_dict.popitem()
- ##for i, key in enumerate(r_dict.keys(), start=1):
- ## #expected = dic.pop(key)
- ## result = r_dict.pop(key)
- ## #pprint.pprint(result)
- ## #print(i)
- #copied_dict = r_dict.copy()
- #r_dict.clear()
- #print(len(r_dict))
- #print(len(copied_dict))
- ##for i, key in enumerate(copied_dict.keys(), start=1):
- ##i = 1
- ##for key in list(r_dict):
- ## #expected = dic.pop(key)
- ## result = r_dict.pop(key)
- ## #pprint.pprint(result)
- ## i += 1
- ## #print(i)
- ##print(i)
- #i = 1
- #for key in list(copied_dict):
- # #expected = dic.pop(key)
- # result = copied_dict.pop(key)
- # #pprint.pprint(result)
- # i += 1
- # #print(i)
- #print(i)
- #result = [r_dict.popitem() for _ in range(message_count)]
- #pprint.pprint(result)
- #self.assertEqual(sorted(map(str, expected)), sorted(map(str, result)))
- #pprint.pprint(sorted(map(str, result)))
- #sorted_dict = sorted(map(str, result))
- #pprint.pprint(sorted_dict)
- #for key in sorted_dict:
- # print(key)
- #print(sorted_dict[key])
- #self.assertEqual(len(dic), 0)
- #self.assertEqual(len(redis_dic), 0)
- #print(len(r_dict))
- #with self.assertRaises(KeyError):
- # dic.popitem()
- #with self.assertRaises(KeyError):
- # redis_dic.popitem()
- #wp = jp.WebPage(delete_flag=False)
- #my_paragraph_design = "w-64 bg-blue-500 m-2 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
- #for i in range(1,11):
- # jp.P(text=f'{i}) Hello World!', a=wp, classes=my_paragraph_design)
- #def my_click(self, msg):
- # self.text = 'I was clicked'
- #def event_demo():
- # wp = jp.WebPage()
- # d = jp.Div(text='Not clicked yet', a=wp, classes='w-48 text-xl m-2 p-1 bg-blue-500 text-white')
- # d.on('click', my_click)
- # return wp
- #def my_click(self, msg):
- # self.text = 'I was clicked'
- # self.set_class('bg-blue-500')
- #def my_mouseenter(self, msg):
- # self.text = 'Mouse entered'
- # self.set_class('bg-red-500')
- #def my_mouseleave(self, msg):
- # self.text = 'Mouse left'
- # self.set_class('bg-teal-500')
- #def event_demo():
- # wp = jp.WebPage()
- # d = jp.Div(text='Not clicked yet', a=wp, classes='w-64 text-2xl m-2 p-2 bg-blue-500 text-white',
- # click=my_click, mouseenter=my_mouseenter, mouseleave=my_mouseleave)
- # return wp
- #def button_click(self, msg):
- # self.num_clicked += 1
- # # self.message.text = f'{self.text} clicked. Number of clicks: {self.num_clicked}'
- # p = jp.P(text=f'{self.text} clicked. Number of clicks: {self.num_clicked}')
- # self.message.add_component(p, 0)
- # for button in msg.page.button_list:
- # button.set_class('bg-blue-500')
- # button.set_class('bg-blue-700', 'hover')
- # self.set_class('bg-red-500')
- # self.set_class('bg-red-700', 'hover')
- #def event_demo():
- # number_of_buttons = 25
- # wp = jp.WebPage()
- # button_div = jp.Div(classes='flex m-4 flex-wrap', a=wp)
- # 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'
- # message = jp.Div(classes='text-lg border m-2 p-2 overflow-auto h-64', a=wp)
- # message.add(jp.P(text='No button clicked yet'))
- # button_list = []
- # for i in range(1, number_of_buttons + 1):
- # b = jp.Button(text=f'Button {i}', a=button_div, classes=button_classes, click=button_click)
- # b.message = message
- # b.num_clicked = 0
- # button_list.append(b)
- # wp.button_list = button_list # The list will now be referenced by the WebPage instance attribute
- # return wp
- def comp_test():
- wp = jp.WebPage()
- d = jp.Div(text='hello1',
- click='self.text="clicked"',
- mouseenter='self.text="entered"; self.set_class("text-5xl"); msg.page.add(Div(text=f"{len(msg.page)} Additional Div"))',
- mouseleave='self.text="left"; self.set_class("text-xl")',
- classes='text-2xl border p-2 m-2', a=wp )
- d = jp.Div(text='hello2', click='self.text="clicked"', mouseenter='self.text="entered"', classes='text-2xl border p-2 m-2', a=wp )
- d = jp.Div(text='hello3', click='self.text="clicked"', mouseenter='self.text="entered"', classes='text-2xl border p-2 m-2', a=wp )
- return wp
- def hello_world():
- #wp = jp.WebPage()
- ##for i in range(1,11):
- ## 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"
- #my_paragraph_design = "w-64 bg-blue-500 m-2 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
- #for i in range(1,11):
- # jp.P(text=f'{i}) Hello World!', a=wp, classes=my_paragraph_design)
- return wp
- def grid_test():
- #try:
- wp = jp.WebPage()
- wm_df = symbols_df
- #wm_df = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
- if wm_df.empty != True:
- grid = wm_df.jp.ag_grid(a=wp)
- grid.options.pagination = True
- grid.options.paginationAutoPageSize = True
- grid.options.columnDefs[0].cellClass = ['text-white', 'bg-blue-500', 'hover:bg-blue-200']
- for col_def in grid.options.columnDefs[1:]:
- col_def.cellClassRules = {
- 'font-bold': 'x < 20',
- 'bg-red-300': 'x < 20',
- 'bg-yellow-300': 'x >= 20 && x < 50',
- 'bg-green-300': 'x >= 50'
- }
- #except Exception as exe:
- # print(exe)
- # traceback.print_exc()
- ##else:
- ## return None
- return wp
- def unix_convert(ts):
- if len(str(ts)) == 13:
- ts = int(ts/1000)
- else:
- ts = int(ts/1000000000)
- tdate = datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S.%f')
- return tdate
- def get_historic_bars(symbol, start_date, end_date, adjusted=True, sort='desc', limit=50000, multiplier=1, timespan='minute'):
- try:
- #multiplier = 1
- #timespan = 'minute'
- #adjusted = 'true'
- #sort = 'desc'
- #limit = 50000
- #pg_client = Historical_Data()
- s = stocks.StocksPolygon
- endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
- #resp = pg_client.get_response(
- # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
- resp = s.get_aggregate_bars(symbol, start_date, end_date, adjusted, sort, limit, multiplier, timespan)
- #print('resp=')
- #print(resp)
- if resp == 'results':
- df = None
- else:
- if 'results' in resp:
- df = pd.DataFrame.from_dict(resp['results'])
- #if 'a' in df.columns:
- if len(df) > 0:
- df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't']]
- pass
- #else:
- #df.insert(1, 'a', None)
- #df.insert(9, 'op', None)
- #df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't', 'n',]]
- df.columns = ['volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp']
- df.insert(0, 'symbol', symbol)
- df.insert(1, 'frequency', str(multiplier) + timespan)
- #df.insert(3, 'total_volume', None)
- #df.insert(3, 'vwap', None)
- #df.insert(3, 'avg_trade_size', None)
- #df.insert(3, 'time_beg', None)
- #df.drop('a', axis=1, inplace=True)
- #df.drop('n', axis=1, inplace=True)
- df['tdate'] = df['timestamp'].map(lambda x: unix_convert(x))
- df['save_date'] = datetime.utcnow()
- #df = df[['symbol', 'volume', 'open', 'close', 'high', 'low', 'vwap', 'timestamp', 'tdate', 'save_date']]
- df = df[['symbol', 'frequency', 'volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp', 'tdate', 'save_date']]
- #else:
- # print('its empty bars ', start_date, ' ', end_date, symbol)
- else:
- df=None
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- return df
- def get_historic_bars_options(option_symbol, start_date, end_date, adjusted=True, sort='desc', limit=50000, multiplier=1, timespan='minute'):
- try:
- #multiplier = 1
- #timespan = 'minute'
- #adjusted = 'true'
- #sort = 'desc'
- #limit = 50000
- #pg_client = Historical_Data()
- s = stocks.StocksPolygon
- endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
- #resp = pg_client.get_response(
- # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
- #resp = s.get_aggregate_bars(symbol, start_date, end_date, adjusted, sort, limit, multiplier, timespan)
- resp = get_options_aggregate_bars(option_symbol, start_date, end_date, adjusted=True, sort='asc', limit=50000, multiplier=1, timespan='minute')
- #print('resp=')
- #print(resp)
- if resp == 'results':
- df = None
- else:
- if 'results' in resp:
- df = pd.DataFrame.from_dict(resp['results'])
- #if 'a' in df.columns:
- if len(df) > 0:
- df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't']]
- pass
- #else:
- #df.insert(1, 'a', None)
- #df.insert(9, 'op', None)
- #df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't', 'n',]]
- df.columns = ['volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp']
- df.insert(0, 'symbol', option_symbol)
- df.insert(1, 'frequency', str(multiplier) + timespan)
- #df.insert(3, 'total_volume', None)
- #df.insert(3, 'vwap', None)
- #df.insert(3, 'avg_trade_size', None)
- #df.insert(3, 'time_beg', None)
- #df.drop('a', axis=1, inplace=True)
- #df.drop('n', axis=1, inplace=True)
- df['tdate'] = df['timestamp'].map(lambda x: unix_convert(x))
- df['save_date'] = datetime.utcnow()
- #df = df[['symbol', 'volume', 'open', 'close', 'high', 'low', 'vwap', 'timestamp', 'tdate', 'save_date']]
- df = df[['symbol', 'frequency', 'volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp', 'tdate', 'save_date']]
- #else:
- # print('its empty bars ', start_date, ' ', end_date, symbol)
- else:
- df=None
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- return df
- def get_last_bar(symbol, timespan='minute'):
- try:
- #multiplier = 1
- #timespan = 'minute'
- #adjusted = 'true'
- #sort = 'desc'
- #limit = 50000
- #pg_client = Historical_Data()
- s = stocks.StocksPolygon
- #endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
- #resp = pg_client.get_response(
- # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
- resp = s.get_aggregate_bars(symbol, date.today(), date.today(), adjusted=True, sort='desc', limit=1, multiplier=1, timespan=timespan)
- #print('resp=')
- #print(resp)
- if resp == 'results':
- df = None
- else:
- if 'results' in resp:
- df = pd.DataFrame.from_dict(resp['results'])
- #if 'a' in df.columns:
- if len(df) > 0:
- df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't']]
- pass
- #else:
- #df.insert(1, 'a', None)
- #df.insert(9, 'op', None)
- #df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't', 'n',]]
- df.columns = ['volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp']
- df.insert(0, 'symbol', symbol)
- df.insert(1, 'frequency', str(1) + timespan)
- #df.insert(3, 'total_volume', None)
- #df.insert(3, 'vwap', None)
- #df.insert(3, 'avg_trade_size', None)
- #df.insert(3, 'time_beg', None)
- #df.drop('a', axis=1, inplace=True)
- #df.drop('n', axis=1, inplace=True)
- df['tdate'] = df['timestamp'].map(lambda x: unix_convert(x))
- df['save_date'] = datetime.utcnow()
- #df = df[['symbol', 'volume', 'open', 'close', 'high', 'low', 'vwap', 'timestamp', 'tdate', 'save_date']]
- df = df[['symbol', 'frequency', 'volume', 'vwap', 'open', 'close', 'high', 'low', 'timestamp', 'tdate', 'save_date']]
- #else:
- # print('its empty bars ', start_date, ' ', end_date, symbol)
- else:
- df=None
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- return df
- def get_historic_trades(symbol, requestdate, reverse=True, limit=5000):
- #def get_historic_trades(symbol, requestdate, timestamp, reverse=True, limit=5000):
- try:
- #pg_client = Historical_Data()
- s = stocks.StocksPolygon
- #endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
- #resp = pg_client.get_response(
- # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
- resp = s.get_trades(symbol=symbol, requestdate=requestdate, reverse=reverse, limit=limit)
- #resp = s.get_trades(symbol=symbol, requestdate=requestdate, timestamp=timestamp, reverse=reverse, limit=limit)
- #print('resp=')
- #print(resp)
- if resp == 'results':
- df = None
- else:
- if 'results' in resp:
- df = pd.DataFrame.from_dict(resp['results'])
- #pprint.pprint(df[:5])
- #if 'c' in df.columns:
- if len(df) > 0:
- df = df[['c', 'i', 'p', 'q', 's', 't', 'x', 'y', 'z']]
- df.columns = ['conditions', 'id', 'price', 'sequence_number',
- 'size', 'sip_timestamp', 'exchange', 'participant_timestamp', 'tape']
- #pass
- #else:
- # df.insert(1, 'a', None)
- # df.insert(9, 'op', None)
- # df = df[['v', 'a', 'vw', 'o', 'c', 'h', 'l', 't', 'n', 'op']]
- #df.columns = ['conditions', 'id', 'price', 'sequence_number',
- # 'size', 'sip_timestamp', 'exchange', 'participant_timestamp', 'tape']
- df.insert(0, 'symbol', symbol)
- #df.insert(3, 'total_volume', None)
- #df.insert(3, 'vwap', None)
- #df.insert(3, 'avg_trade_size', None)
- #df.insert(3, 'time_beg', None)
- #df.drop('a', axis=1, inplace=True)
- #df.drop('n', axis=1, inplace=True)
- df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
- df['save_date'] = datetime.utcnow()
- df.columns = ['symbol', 'conditions', 'id', 'price', 'sequence_number',
- 'size', 'sip_timestamp', 'exchange', 'participant_timestamp', 'tape', 'tdate', 'save_date']
- #pprint.pprint(df)
- #else:
- # print('its empty trades ', requestdate, ' ', symbol)
- #if len(df) > 0:
- # pprint.pprint(df)
- else:
- df=None
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- return df
- def get_historic_quotes(symbol, requestdate, reverse=True, limit=5000):
- #def get_historic_trades(symbol, requestdate, timestamp, reverse=True, limit=5000):
- try:
- #pg_client = Historical_Data()
- s = stocks.StocksPolygon
- #endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
- #resp = pg_client.get_response(
- # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
- resp = s.get_quotes(symbol=symbol, requestdate=requestdate, reverse=reverse, limit=limit)
- #resp = s.get_trades(symbol=symbol, requestdate=requestdate, timestamp=timestamp, reverse=reverse, limit=limit)
- #print('resp=')
- #print(resp)
- if resp == 'results':
- df = None
- else:
- if 'results' in resp:
- df = pd.DataFrame.from_dict(resp['results'])
- #pprint.pprint(df[:5])
- #if 'c' in df.columns:
- if len(df) > 0:
- df = df[['t', 'y', 'q', 'c', 'p', 's', 'x', 'P', 'S', 'X', 'z']]
- df.columns = ['sip_timestamp', 'participant_timestamp', 'sequence_number', 'conditions', 'bid_price', 'bid_size', 'bid_exchange',
- 'ask_price', 'ask_size', 'ask_exchange', 'tape']
- #pass
- #else:
- # df.insert(1, 'a', None)
- # df.insert(9, 'op', None)
- # df = df[['v', 'a', 'vw', 'o', 'c', 'h', 'l', 't', 'n', 'op']]
- #df.columns = ['conditions', 'id', 'price', 'sequence_number',
- # 'size', 'sip_timestamp', 'exchange', 'participant_timestamp', 'tape']
- df.insert(0, 'symbol', symbol)
- #df.insert(3, 'total_volume', None)
- #df.insert(3, 'vwap', None)
- #df.insert(3, 'avg_trade_size', None)
- #df.insert(3, 'time_beg', None)
- #df.drop('a', axis=1, inplace=True)
- #df.drop('n', axis=1, inplace=True)
- #print(df['sip_timestamp'])
- #if len(str(df['sip_timestamp'])) == 13:
- df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
- df['save_date'] = datetime.utcnow()
- df = df[['symbol', 'sip_timestamp', 'participant_timestamp', 'sequence_number', 'conditions', 'bid_price', 'bid_size', 'bid_exchange',
- 'ask_price', 'ask_size', 'ask_exchange', 'tape', 'tdate', 'save_date']]
- #pprint.pprint(df)
- #else:
- # print('its empty quotes ', requestdate, ' ', symbol)
- #if len(df) > 0:
- # pprint.pprint(df)
- else:
- df=None
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- return df
- def get_current_stocks_snapshot(symbols=None):
- #def get_historic_trades(symbol, requestdate, timestamp, reverse=True, limit=5000):
- try:
- #pg_client = Historical_Data()
- s = stocks.StocksPolygon
- z = datetime.today()
- #print(z)
- #endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
- #resp = pg_client.get_response(
- # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
- if symbols is None:
- resp = s.get_snapshot_all()
- else:
- resp = s.get_snapshot_all(symbols=symbols)
- #resp = s.get_trades(symbol=symbol, requestdate=requestdate, timestamp=timestamp, reverse=reverse, limit=limit)
- #print('resp=')
- #print(resp)
- #return
- #if resp == 'results':
- global_dict = {}
- daydict = None
- lastQuotedict = None
- lastTradedict = None
- minuteBardict = None
- prevDaydict = None
- i=0
- if resp is None:
- df = None
- else:
- #if 'results' in resp:
- if resp['count'] > 0:
- #df = pd.DataFrame.from_dict(resp['tickers'])
- #df = pd.DataFrame.from_dict(resp['tickers'], index='symbol', orient='index')
- #df = pd.concat({
- # k: pd.DataFrame.from_dict(v, 'index') for k, v in resp.items()}, axis=0)
- #pprint.pprint(df[:5])
- #if 'c' in df.columns:
- #x = ndict({'key1': ndict({'attr1':1, 'attr2':2})})
- #print(resp[0]['day'])
- res = defaultdict(list)
- big_df = pd.DataFrame()
- joined_dict = {}
- #daydict = defaultdict(list)
- #lastQuotedict = defaultdict(list)
- #lastTradedict = defaultdict(list)
- #minuteBardict = defaultdict(list)
- #prevDaydict = defaultdict(list)
- daydict = {}
- lastQuotedict = {}
- lastTradedict = {}
- minuteBardict = {}
- prevDaydict = {}
- #daydict = defaultdict(dict)
- #lastQuotedict = defaultdict(dict)
- #lastTradedict = defaultdict(dict)
- #minuteBardict = defaultdict(dict)
- #prevDaydict = defaultdict(dict)
- for sub in resp['tickers']:
- #joined_df = pd.DataFrame()
- #daydict = defaultdict(list)
- #lastQuotedict = defaultdict(list)
- #lastTradedict = defaultdict(list)
- #minuteBardict = defaultdict(list)
- #prevDaydict = defaultdict(list)
- #ticker = ''
- #todaysChange = ''
- #todaysChangePerc = ''
- #updated = ''
- #for k in sub:
- #res[k].append(sub[k])
- #print(sub)
- #print(k)
- #print(sub[k])
- daydict['symbol'] = sub['ticker']
- daydict['todaysChange'] = sub['todaysChange']
- daydict['todaysChangePerc'] = sub['todaysChangePerc']
- daydict['updated'] = sub['updated']
- #daydict.update('close', sub['day']['c'])
- #daydict.update('high', sub['day']['h'])
- #daydict.update('low', sub['day']['l'])
- #daydict.update('open', sub['day']['o'])
- #daydict.update('volume', sub['day']['v'])
- #daydict.update('vwap', sub['day']['vw'])
- daydict['close'] = sub['day']['c']
- daydict['high'] = sub['day']['h']
- daydict['low'] = sub['day']['l']
- daydict['open'] = sub['day']['o']
- daydict['volume'] = sub['day']['v']
- daydict['vwap'] = sub['day']['vw']
- #daydict['close'].append(sub['day']['c'])
- #daydict['high'].append(sub['day']['h'])
- #daydict['low'].append(sub['day']['l'])
- #daydict['open'].append(sub['day']['o'])
- #daydict['volume'].append(sub['day']['v'])
- #daydict['vwap'].append(sub['day']['vw'])
- lastQuotedict['lastQuote_ask_price'] = sub['lastQuote']['P']
- lastQuotedict['lastQuote_ask_size'] = sub['lastQuote']['S']
- lastQuotedict['lastQuote_bid_price'] = sub['lastQuote']['p']
- lastQuotedict['lastQuote_bid_size'] = sub['lastQuote']['s']
- lastQuotedict['lastQuote_timestamp'] = sub['lastQuote']['t']
- lastTradedict['lastTrade_close'] = sub['lastTrade']['c']
- lastTradedict['lastTrade_trade_id'] = sub['lastTrade']['i']
- lastTradedict['lastTrade_price'] = sub['lastTrade']['p']
- lastTradedict['lastTrade_size'] = sub['lastTrade']['s']
- lastTradedict['lastTrade_time'] = sub['lastTrade']['t']
- lastTradedict['lastTrade_exch_id'] = sub['lastTrade']['x']
- minuteBardict['minuteBar_total_volume'] = sub['min']['av']
- minuteBardict['minuteBar_close'] = sub['min']['c']
- minuteBardict['minuteBar_high'] = sub['min']['h']
- minuteBardict['minuteBar_low'] = sub['min']['l']
- minuteBardict['minuteBar_open'] = sub['min']['o']
- minuteBardict['minuteBar_volume'] = sub['min']['v']
- minuteBardict['minuteBar_vwap'] = sub['min']['vw']
- prevDaydict['prevDay_close'] = sub['prevDay']['c']
- prevDaydict['prevDay_high'] = sub['prevDay']['h']
- prevDaydict['prevDay_low'] = sub['prevDay']['l']
- prevDaydict['prevDay_open'] = sub['prevDay']['o']
- prevDaydict['prevDay_volume'] = sub['prevDay']['v']
- prevDaydict['prevDay_vwwap'] = sub['prevDay']['vw']
- #lastQuotedict['lastQuote_ask_price'].append(sub['lastQuote']['P'])
- #lastQuotedict['lastQuote_ask_size'].append(sub['lastQuote']['S'])
- #lastQuotedict['lastQuote_bid_price'].append(sub['lastQuote']['p'])
- #lastQuotedict['lastQuote_bid_size'].append(sub['lastQuote']['s'])
- #lastQuotedict['lastQuote_timestamp'].append(sub['lastQuote']['t'])
- #lastTradedict['lastTrade_close'].append(sub['lastTrade']['c'])
- #lastTradedict['lastTrade_trade_id'].append(sub['lastTrade']['i'])
- #lastTradedict['lastTrade_price'].append(sub['lastTrade']['p'])
- #lastTradedict['lastTrade_size'].append(sub['lastTrade']['s'])
- #lastTradedict['lastTrade_time'].append(sub['lastTrade']['t'])
- #lastTradedict['lastTrade_exch_id'].append(sub['lastTrade']['x'])
- #minuteBardict['minuteBar_total_volume'].append(sub['min']['av'])
- #minuteBardict['minuteBar_close'].append(sub['min']['c'])
- #minuteBardict['minuteBar_high'].append(sub['min']['h'])
- #minuteBardict['minuteBar_low'].append(sub['min']['l'])
- #minuteBardict['minuteBar_open'].append(sub['min']['o'])
- #minuteBardict['minuteBar_volume'].append(sub['min']['v'])
- #minuteBardict['minuteBar_vwap'].append(sub['min']['vw'])
- #prevDaydict['prevDay_close'].append(sub['prevDay']['c'])
- #prevDaydict['prevDay_high'].append(sub['prevDay']['h'])
- #prevDaydict['prevDay_low'].append(sub['prevDay']['l'])
- #prevDaydict['prevDay_open'].append(sub['prevDay']['o'])
- #prevDaydict['prevDay_volume'].append(sub['prevDay']['v'])
- #prevDaydict['prevDay_vwwap'].append(sub['prevDay']['vw'])
- #ticker = sub['ticker']
- #todaysChange = sub['todaysChange']
- #todaysChangePerc = sub['todaysChangePerc']
- #updated = sub['updated']
- #d4 = dict(daydict.items() + lastQuotedict.items() + lastTradedict.items() + minuteBardict.items() + prevDaydict.items())
- d4 = dict(**daydict, **lastQuotedict, **lastTradedict, **minuteBardict, **prevDaydict)
- #print('i', i)
- #pprint.pprint(d4)
- #for single_dict in d4:
- # global_dict.update(single_dict)
- #print(' ************** ')
- #pprint.pprint(joined_dict)
- #joined_dict.update(d4)
- #joined_dict.merge(d4)
- #joined_dict = joined_dict | d4
- #for key, value in d4.items():
- # joined_dict[key] = value
- #joined_dict[i] = d4
- #joined_dict[i] = dict(d4)
- #joined_dict[i] = [d4]
- joined_dict[sub['ticker']] = d4
- #print(datetime.today())
- #joined_dict.update(d4)
- #big_df = big_df.append(d4, ignore_index=True, sort=False)
- #threading.Thread(target=big_df.append(d4, ignore_index=True, sort=False), args=[]).start()
- #joined_dict = dict(joined_dict, **d4)
- #print(' --------------- ')
- #pprint.pprint(joined_dict)
- #for dictionary in d4:
- # joined_dict.update(dictionary)
- #joined_dict.append(d4, ignore_index=True)
- #joined_dict = joined_dict | d4
- #joined_dict.append(d4)
- #joined_df = pd.DataFrame.from_dict(d4)
- #big_df = dict(**d4, **big_df)
- i += 1
- #big_df = pd.DataFrame.from_dict(d4)
- #big_df = pd.DataFrame.from_dict(joined_dict)
- #print(datetime.today())
- #print(i)
- #print(d4)
- #big_df = pd.DataFrame.from_dict(joined_dict)
- #pprint.pprint(len(joined_dict))
- #pprint.pprint(joined_dict)
- #big_df = big_df.append(d4, ignore_index=True, sort=False)
- #pprint.pprint(joined_dict)
- #pprint.pprint(len(joined_dict))
- #print(len(big_df))
- #print(big_df)
- #pprint.pprint(joined_dict)
- big_df = pd.DataFrame.from_dict(joined_dict)
- big_df = big_df.T
- big_df.sort_values(by=['todaysChangePerc'], inplace=True, ascending=False)
- #pprint.pprint(big_df)
- #big_df.T.to_csv('snapshot1.csv')
- #big_df = big_df.append(joined_dict, ignore_index=True, sort=False)
- #big_df = big_df.append(d4, ignore_index=True, sort=False)
- ####big_df = big_df.T
- #print(len(big_df))
- #print(len(joined_dict))
- ####pprint.pprint(big_df)
- #results_dict = {}
- #results_dict['results'] = sorted(joined_dict, key='symbol')
- #results_dict['results'] = sorted(joined_dict.items(), key = lambda kv:(kv[1], kv[0]))
- #print(results_dict)
- #redis_message('stock_snapshot', joined_dict)
- redis_dict_update(big_df)
- #redis_dict_update(joined_dict)
- #print(datetime.today())
- print(datetime.today() - z)
- #big_df.to_csv('c://Downloads//big_df.csv')
- #big_df.to_csv('big_df.csv')
- #return big_df
- return None
- #print(z - time.localtime())
- if len(big_df) > 0:
- #df = df[['t', 'y', 'q', 'c', 'p', 's', 'x', 'P', 'S', 'X', 'z']]
- #df.columns = ['sip_timestamp', 'participant_timestamp', 'sequence_number', 'conditions', 'bid_price', 'bid_size', 'bid_exchange',
- # 'ask_price', 'ask_size', 'ask_exchange', 'tape']
- #pass
- #else:
- # df.insert(1, 'a', None)
- # df.insert(9, 'op', None)
- # df = df[['v', 'a', 'vw', 'o', 'c', 'h', 'l', 't', 'n', 'op']]
- #df.columns = ['conditions', 'id', 'price', 'sequence_number',
- # 'size', 'sip_timestamp', 'exchange', 'participant_timestamp', 'tape']
- #df.insert(0, 'symbol', symbol)
- #df.insert(3, 'total_volume', None)
- #df.insert(3, 'vwap', None)
- #df.insert(3, 'avg_trade_size', None)
- #df.insert(3, 'time_beg', None)
- #df.drop('a', axis=1, inplace=True)
- #df.drop('n', axis=1, inplace=True)
- #print(df['sip_timestamp'])
- #if len(str(df['sip_timestamp'])) == 13:
- #big_df['t_lastTrade'] = big_df['lasttrade_sip_timestamp'].map(lambda x: unix_convert(x))
- #big_df['save_date'] = datetime.utcnow()
- #df = df[['symbol', 'sip_timestamp', 'participant_timestamp', 'sequence_number', 'conditions', 'bid_price', 'bid_size', 'bid_exchange',
- # 'ask_price', 'ask_size', 'ask_exchange', 'tape', 'tdate', 'save_date']]
- #pprint.pprint(df)
- #else:
- # print('its empty quotes ', requestdate, ' ', symbol)
- #if len(df) > 0:
- pprint.pprint(len(big_df))
- pprint.pprint(big_df[:10])
- else:
- df=None
- big_df=None
- # if symbols is not None:
- # for symbol in symbols:
- # big_df = pd.DataFrame()
- # doc = s.get_daily_open_close(symbol, requestdate='2021-11-05', adjusted=True)
- # #doc = s.get_daily_open_close(symbol, requestdate=date.today(), adjusted=True)
- # lastquote = s.get_last_quote(symbol)
- # lasttrade = s.get_last_trade(symbol)
- # minuteBar = s.get_aggregate_bars(symbol, startdate='2021-11-04', enddate='2021-11-04', limit=1, sort='desc')
- # prevDay = s.get_previous_close(symbol)
- # #pprint.pprint('\ndaily open close = ')
- # #pprint.pprint(doc)
- # #pprint.pprint('\nlastquote = ')
- # #pprint.pprint(lastquote)
- # #pprint.pprint('\nlasttrade = ')
- # #pprint.pprint(lasttrade)
- # #pprint.pprint('\nminuteBar = ')
- # #pprint.pprint(minuteBar)
- # #pprint.pprint('\nprevDay = ')
- # #pprint.pprint(prevDay)
- # #print(doc)
- # #daydict = doc.to_dict()
- # #print(daydict)
- # #pd_day = pd.DataFrame.from_dict(doc, orient='columns')
- # pd_day = pd.DataFrame(doc, index=[3])#, orient='columns', columns=['status', 'from', 'symbol', 'open', 'high', 'low', 'close', 'volume', 'afterHours', 'preMarket'])
- # #pd_day.columns = ['status', 'from', 'symbol', 'open', 'high', 'low', 'close', 'volume', 'afterHours', 'preMarket']
- # #pd_day.insert(0, 'symbol', ticker)
- # #pd_day = pd_day.set_index('symbol')
- # #pd_day.index = 'symbol'
- # #pprint.pprint(pd_day)
- # print(' ')
- # #print(lastquote['results'])
- # pd_lastQuote = pd.DataFrame(lastquote['results'], index=[9])
- # #pd_lastQuote.columns = ['P', 'S', 'T', 'X', 'p', 'q', 's', 't', 'x', 'y', 'z']
- # #pd_lastQuote.columns = ['ask', 'ask_size', 'symbol', 'ask_exch_id', 'bid', 'sequence_number', 'bid_size',
- # # 'sip_timestamp', 'bid_exch_id', 'participant_timestamp', 'tape']
- # pd_lastQuote.rename(columns={'P': 'lastquote_ask', 'S': 'lastquote_ask_size', 'T': 'symbol', 'X': 'lastquote_ask_exch_id',
- # 'p': 'lastquote_bid', 'q': 'lastquote_sequence_number',
- # 's': 'lastquote_bid_size', 't': 'lastquote_sip_timestamp', 'x': 'lastquote_bid_exch_id',
- # 'y': 'lastquote_participant_timestamp', 'z': 'lastquote_tape'},
- # errors="raise", inplace = True)
- # #pd_lastQuote.insert(0, 'symbol', ticker)
- # #pprint.pprint(pd_lastQuote)
- # print(' ')
- # #print(lasttrade['results'])
- # lasttrade['results']['c'] = [lasttrade['results']['c']]
- # pd_lastTrade = pd.DataFrame(lasttrade['results'])#, index=[7])
- # pd_lastTrade.rename(columns={'c': 'lasttrade_conditions', 'p': 'lasttrade_price', 's': 'lasttrade_size', 'x': 'lasttrade_exch_id',
- # 'z': 'tape', 'T': 'symbol',
- # 't': 'lasttrade_sip_timestamp', 'y': 'lasttrade_participant_timestamp', 'q': 'lasttrade_sequence_number'},
- # errors="raise", inplace = True)
- # pd_lastTrade = pd_lastTrade.set_index('symbol')
- # #pd_lastTrade = pd_lastTrade.groupby('symbol')
- # ##pd_lastTrade.columns = ['conditions', 'trade_id', 'price', 'size', 't_trade', 'exch_id']
- # ##pd_lastTrade.insert(0, 'symbol', ticker)
- # #pprint.pprint(pd_lastTrade)
- # #print(' ')
- # #print(minuteBar['results'])
- # pd_minuteBar = pd.DataFrame(minuteBar['results'])#, index=[3])
- # pd_minuteBar.rename(columns={'v': 'minuteBar_volume', 'vw': 'minuteBar_vwap', 'a': 'minuteBar_adjusted_price',
- # 'o': 'minuteBar_open', 'c': 'minuteBar_close', 'h': 'minuteBar_high',
- # 'l': 'minuteBar_low', 't': 'minuteBar_sip_timestamp', 'n': 'minuteBar_transaction_count'},
- # errors="raise", inplace = True)
- # ##pd_minuteBar.columns = ['accumulated_volume', 'close', 'high', 'low', 'open', 'volume', 'vwap']
- # pd_minuteBar.insert(0, 'symbol', minuteBar['ticker'])
- # pd_minuteBar = pd_minuteBar.set_index('symbol')
- # #pprint.pprint(pd_minuteBar)
- # #print(' ')
- # #print(prevDay['results'])
- # pd_prevDaydict = pd.DataFrame(prevDay['results'])#, index=[3])
- # pd_prevDaydict.rename(columns={'T': 'symbol', 'v': 'prev_volume', 'vw': 'prev_vwap', 'o': 'prev_open', 'c': 'prev_close', 'h': 'prev_high',
- # 'l': 'prev_low', 't': 'prev_sip_timestamp', 'n': 'prev_transaction_count'},
- # errors="raise", inplace = True)
- # ##pd_prevDaydict.columns = ['close', 'high', 'low', 'open', 'volume', 'vwap']
- # ##pd_prevDaydict.insert(0, 'symbol', ticker)
- # pd_prevDaydict = pd_prevDaydict.set_index('symbol')
- # #pprint.pprint(pd_prevDaydict)
- # #print(pd_day)
- # #print(pd_lastQuote)
- # #print(pd_lastTrade)
- # #print(pd_minuteBar)
- # #print(pd_prevDaydict)
- # #print(' ')
- # #print(' ')
- # #print(' ')
- ##pd_day = pd.DataFrame.from_dict(daydict)2
- ##pd_day = pd.DataFrame.from_dict(daydict)
- # #big_df = pd.
- # big_df = pd.merge(pd_day, pd_lastQuote, on='symbol', how='inner')#, suffixes=('_day', '_quote'))#, left_suffix='_day', right_suffix='_minuteBar')
- # big_df = pd.merge(big_df, pd_lastTrade, on='symbol', how='inner')#, suffixes=('_quote', '_trade'))
- # #big_df = pd.merge(big_df, pd_lastQuote, on='symbol', how='inner', suffixes=('_trade', '_quote'))
- # big_df = pd.merge(big_df, pd_minuteBar, on='symbol', how='inner')#, suffixes=('_trade', '_min'))
- # #big_df.join(pd_minuteBar, on='symbol', lsuffix='_day', rsuffix='_minuteBar', inplace=True)
- # big_df = pd.merge(big_df, pd_prevDaydict, on='symbol', how='inner')#, suffixes=('_min', '_prev'))
- # big_df.insert(3, 'per_chng', (big_df['close'] / big_df['prev_close']) * 100)
- ##frames = [pd_day, pd_lastQuote, pd_lastTrade, pd_lastQuote, pd_minuteBar, pd_prevDaydict]
- ##big_df = pd.concat(frames, axis=1, ignore_index=True)#join="inner")#.reindex(pd_day.index)
- # print(' ')
- # print(' ')
- # print('big_df = ')
- # print(' ')
- # #pprint.pprint(big_df)
- # print(big_df)
- # print(' ')
- if big_df is not None:
- return big_df
- else:
- print('market closed')
- time.sleep(10)
- get_stocks_snapshot()
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- big_df=None
- return df
- def get_historic_stock_daily_open_close(symbol, requestdate, adjusted=False):
- try:
- #pg_client = Historical_Data()
- s = stocks.StocksPolygon
- #endpoint = '/v2/aggs/ticker/%s/range/%d/%s/%s/%s?adjusted=%s&sort=%s&limit=%d'
- #resp = pg_client.get_response(
- # endpoint % (symbol, multiplier, timespan, start_date, end_date, adjusted, sort, limit))
- resp = s.get_daily_open_close(symbol, requestdate=requestdate, adjusted=adjusted)
- #print('resp=')
- #print(resp)
- #if resp == 'results' or resp == 'message':
- if resp['status'] == 'OK':
- #df = pd.DataFrame.from_dict(resp, index=False)
- big_dict = []
- resp2 = dict(resp)
- dict_keys = resp2.keys()
- for k in list(dict_keys):
- val = resp2[k]#.keys()
- print(k, '=', val, '\n')
- #for st in list(val):
- # print(st)
- #df = pd.DataFrame.from_dict(resp['results'])
- #return
- #if 'a' in df.columns:
- if len(resp) > 0:
- #df = resp[['afterHours', 'close', 'from', 'high', 'low', 'open', 'preMarket', 'symbol', 'volume']]
- ###pass
- #else:
- #df.insert(1, 'a', None)
- #df.insert(9, 'op', None)
- #df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't', 'n',]]
- #df = pd.DataFrame.from_dict(resp2, index=False)
- df = pd.DataFrame.from_dict(resp['results'])
- df.columns = ['afterHours', 'close', 'from', 'high', 'low', 'open', 'preMarket', 'symbol', 'volume']
- #df.insert(0, 'symbol', symbol)
- #df.insert(1, 'frequency', str(multiplier) + timespan)
- #df.insert(3, 'total_volume', None)
- #df.insert(3, 'vwap', None)
- #df.insert(3, 'avg_trade_size', None)
- #df.insert(3, 'time_beg', None)
- #df.drop('a', axis=1, inplace=True)
- #df.drop('n', axis=1, inplace=True)
- #df['tdate'] = df['timestamp'].map(lambda x: unix_convert(x))
- df['save_date'] = datetime.utcnow()
- #df = df[['symbol', 'volume', 'open', 'close', 'high', 'low', 'vwap', 'timestamp', 'tdate', 'save_date']]
- df = df[['afterHours', 'close', 'from', 'high', 'low', 'open', 'preMarket', 'symbol', 'volume', 'save_date']]
- #else:
- # print('its empty bars ', start_date, ' ', end_date, symbol)
- else:
- df=None
- else:
- df = None
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- return df['results']
- def get_historic_option_trades(symbol, requestdate, adjusted=False):
- try:
- o = options.OptionsPolygon
- resp = o.get_option_trades(symbol, requestdate=requestdate, limit=50000)
- if resp is not None:
- if 'results' in resp:
- df = pd.DataFrame.from_dict(resp['results'])
- if df is not None and df.empty != True:
- df.columns = ['conditions', 'exchange', 'participant_timestamp', 'price', 'sip_timestamp', 'size']
- #df.columns = ['conditions', 'exchange', 'price', 'sequence_number', 'sip_timestamp', 'size']
- polygon_option_symbol = symbol
- option_numbers = re.findall(r'\d+', polygon_option_symbol)
- underlying_symbol = polygon_option_symbol[:polygon_option_symbol.index(option_numbers[0])]
- option_type = str(polygon_option_symbol[polygon_option_symbol.index(option_numbers[1]) - 1:])[:1]
- option_expiration = str(option_numbers[0])
- #rint(df['price'])
- option_strike = str(option_numbers[1])
- #del df['sequence_number']
- df.insert(0, 'symbol', symbol)
- df.insert(1, 'underlying_symbol', underlying_symbol)
- df.insert(2, 'option_type', option_type)
- df.insert(3, 'option_expiration', option_expiration)
- df.insert(4, 'option_strike', int(option_strike)/1000)
- df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
- df['save_date'] = datetime.utcnow()
- #df = df[['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'sequence_number', 'size',
- df = df[['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
- 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']]
- #return df.to_json(orient='records')[1:-1].replace('},{', '} {')
- else:
- df=None
- else:
- df = None
- else:
- df = None
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- return df
- def get_conditions():
- try:
- #pg_client = Historical_Data()
- #s = stocks.StocksPolygon
- r = reference.ReferencePolygon
- #from_date = '2021-10-26'
- resp = r.get_conditions_vX()
- if 'results' in resp:
- messages = dict(resp)
- cur = conn.cursor()
- sio = io.StringIO()
- writer = csv.writer(sio)
- values = [message for message in messages]
- #values = [[value for value in message.values()] for message in messages]
- writer.writerows(values)
- cols = ['abbreviation', 'asset_class', 'data_types', 'description', 'id', 'name', 'sip_mapping', 'type', 'update_rules']
- #cols = ['symbol', 'tick_volume', 'total_volume', 'opening_price', 'tick_vwap', 'tick_open', 'tick_close',
- # 'tick_high', 'tick_low', 'vwap', 'avg_trade_size', 'time_beg', 'time_end', 'tdate', 'save_date']
- sio.seek(0)
- cur.copy_from(file=sio, table="reference_conditions", sep=",", columns=cols, null='')
- cur.close()
- return
- if 'results' in resp:
- df = pd.DataFrame.from_dict(resp['results'])
- if df is not None:
- #print('writing to quotes ->' + str(len(temp_df)))
- #df = pd.DataFrame.from_dict(dict(resp))
- pprint.pprint(df)
- #return
- df = df[['abbreviation', 'asset_class', 'data_types', 'description', 'id', 'name', 'sip_mapping', 'type', 'update_rules']]#, 'consolidated', 'market_center']]
- #df = df[['conditions', 'exchange', 'participant_timestamp', 'price', 'sip_timestamp', 'size']]
- ###pass
- #else:
- #df.insert(1, 'a', None)
- #df.insert(9, 'op', None)
- #df = df[['v', 'vw', 'o', 'c', 'h', 'l', 't', 'n',]]
- df.columns = ['abbreviation', 'asset_class', 'data_types', 'description', 'id', 'name', 'sip_mapping', 'type', 'update_rules']#, 'consolidated', 'market_center']
- #df.insert(0, 'symbol', symbol)
- #df.insert(1, 'frequency', str(multiplier) + timespan)
- #df.insert(3, 'total_volume', None)
- #df.insert(3, 'vwap', None)
- #df.insert(3, 'avg_trade_size', None)
- #df.insert(3, 'time_beg', None)
- #df.drop('a', axis=1, inplace=True)
- #df.drop('n', axis=1, inplace=True)
- #df['tdate'] = df['timestamp'].map(lambda x: unix_convert(x))
- #df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
- #df['save_date'] = datetime.utcnow()
- #df = df[['symbol', 'volume', 'open', 'close', 'high', 'low', 'vwap', 'timestamp', 'tdate', 'save_date']]
- df = df[['abbreviation', 'asset_class', 'data_types', 'description', 'id', 'name', 'sip_mapping', 'type', 'update_rules']]#, 'consolidated', 'market_center']]
- df.to_sql('reference_conditions', engine, if_exists='append', index=False, method='multi')
- else:
- df=None
- else:
- df = None
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- return df
- #async def get_historic_data_base(symbols, data_type: DataType, start, end,
- #
- #def get_bars(symbol, to_sql:bool=True):
- def get_bars(symbol, start_date='2021, 11, 12', end_date='2021, 11, 12', adjusted=True, sort='asc', limit=50000, multiplier=1, timespan='minute'):
- try:
- global bars_df
- #start_time2 = time.time()
- # Date Info
- #from_date = '2021-11-08'
- #from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
- #to_date = datetime.today().date() + timedelta(days=1)
- ## Transform Dates
- #temp_date_start = to_date - timedelta(days=60)
- #temp_date_end = to_date
- #print(f'getting data for {symbol}')
- start_date = date(2021, 11, 12)
- end_date = date(2021, 11, 12)
- #delta = timedelta(days=1)
- #while start_date <= end_date:
- #print(symbol, start_date)
- #future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
- #future1 = executor.submit(get_bars, symbol)
- #future2 = executor.submit(get_trades, symbol)
- #future3 = executor.submit(get_quotes, symbol)
- #future4 = executor.submit(get_daily_stock_open_close, symbol)
- #temp_df = get_historic_trades(symbol=symbol, requestdate=temp_date_start, limit=50000)
- temp_df = get_historic_bars(symbol, start_date, end_date, adjusted=True, sort='desc', limit=50000, multiplier=1, timespan='minute')
- #start_date += delta
- #while temp_date_start > from_date:
- # start_time2 = time.time()
- # temp_df = get_historic_bars(symbol, temp_date_start, temp_date_end)
- # #print('thread 1', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
- # #print(time.time() - start_time2, '\n')
- # #print('thread 1', '\n', temp_df)
- # temp_date_end = temp_date_end - timedelta(days=60)
- # temp_date_start = temp_date_start - timedelta(days=60)
- #if isinstance(type(temp_df), str):
- # break
- #else:
- # Add df to database
- #print(temp_df)
- start_time2 = time.time()
- to_sql = True
- #if temp_df is not None or len(temp_df) > 0:
- if temp_df is not None:
- if to_sql == True:
- print('writing to bars ->' + str(len(temp_df)))
- temp_df.to_sql('stockdata_hist_bars', engine, if_exists='append', index=False, method='multi')
- #time.sleep(0.1)
- else:
- #pprint.pprint(temp_df)
- #bars_df.append(temp_df, ignore_index=True)
- frames = [bars_df, temp_df]
- bars_df = pd.concat(frames)
- #print(bars_df)
- #print(len(bars_df))
- #bars_df
- #print(temp_df)
- temp_df=None
- #print(time.time() - start_time2)
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- #return temp_df
- def get_latest_bar(symbol, timespan='minute'):
- try:
- global latest_min_bar_df
- #start_time2 = time.time()
- # Date Info
- #from_date = '2021-11-08'
- #from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
- #to_date = datetime.today().date() + timedelta(days=1)
- ## Transform Dates
- #temp_date_start = to_date - timedelta(days=60)
- #temp_date_end = to_date
- #print(f'getting data for {symbol}')
- #start_date = date(2021, 11, 11)
- #end_date = date(2021, 11, 11)
- #delta = timedelta(days=1)
- #while start_date <= end_date:
- #print(symbol, start_date)
- #future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
- #future1 = executor.submit(get_bars, symbol)
- #future2 = executor.submit(get_trades, symbol)
- #future3 = executor.submit(get_quotes, symbol)
- #future4 = executor.submit(get_daily_stock_open_close, symbol)
- #temp_df = get_historic_trades(symbol=symbol, requestdate=temp_date_start, limit=50000)
- temp_df = get_last_bar(symbol, timespan='minute')
- #start_date += delta
- #while temp_date_start > from_date:
- # start_time2 = time.time()
- # temp_df = get_historic_bars(symbol, temp_date_start, temp_date_end)
- # #print('thread 1', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
- # #print(time.time() - start_time2, '\n')
- # #print('thread 1', '\n', temp_df)
- # temp_date_end = temp_date_end - timedelta(days=60)
- # temp_date_start = temp_date_start - timedelta(days=60)
- #if isinstance(type(temp_df), str):
- # break
- #else:
- # Add df to database
- #print(temp_df)
- start_time2 = time.time()
- to_sql = False
- #if temp_df is not None or len(temp_df) > 0:
- if temp_df is not None:
- if to_sql == True:
- print('writing to bars ->' + str(len(temp_df)))
- temp_df.to_sql('stockdata_hist_bars', engine, if_exists='append', index=False, method='multi')
- time.sleep(0.1)
- else:
- #pprint.pprint(temp_df)
- #bars_df.append(temp_df, ignore_index=True)
- frames = [latest_min_bar_df, temp_df]
- latest_min_bar_df = pd.concat(frames)
- #print(bars_df)
- #print(len(bars_df))
- #bars_df
- #print(temp_df)
- temp_df=None
- #print(time.time() - start_time2)
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- #return temp_df
- def get_trades(symbol):
- try:
- #start_time2 = time.time()
- conn = postgreSQL_pool.getconn()
- # code that uses a connection
- postgreSQL_pool.putconn(conn)
- # Date Info
- #from_date = '2021-01-01'
- #from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
- #to_date = datetime.today().date() + timedelta(days=1)
- ## Transform Dates
- #temp_date_start = to_date - timedelta(days=60)
- #temp_date_end = to_date
- ##print(f'getting data for {symbol}')
- #while temp_date_start > from_date:
- start_date = date(2021, 10, 25)
- end_date = date(2021, 10, 29)
- delta = timedelta(days=1)
- get_bars(symbol)
- while start_date <= end_date:
- print(symbol, start_date)
- future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
- #future1 = executor.submit(get_bars, symbol)
- #future2 = executor.submit(get_trades, symbol)
- #future3 = executor.submit(get_quotes, symbol)
- #future4 = executor.submit(get_daily_stock_open_close, symbol)
- temp_df = get_historic_trades(symbol=symbol, requestdate=temp_date_start, limit=50000)
- start_date += delta
- start_time2 = time.time()
- #temp_df = get_historic_trades(symbol=symbol, requestdate=temp_date_start, limit=50000)
- #print('thread 2', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
- #print(time.time() - start_time2, '\n')
- #print('thread 2', '\n', temp_df)
- #temp_date_end = temp_date_end - timedelta(days=60)
- #temp_date_start = temp_date_start - timedelta(days=60)
- if isinstance(type(temp_df), str):
- return
- #else:
- # Add df to database
- #print(temp_df)
- #print('thread 2', '\n', temp_df)
- #print('thread2')
- if temp_df is not None or len(temp_df) > 0:
- #print('writing to trades ->' + str(len(temp_df)))
- temp_df.to_sql('stockdata_hist_trades', engine, if_exists='append', index=False, method='multi')
- time.sleep(0.1)
- temp_df=None
- #print(time.time() - start_time2)
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- #print(time.time() - start_time2)
- def get_quotes(symbol, requestdata):
- try:
- #start_time2 = time.time()
- # Date Info
- #from_date = '2021-01-01'
- #from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
- #to_date = datetime.today().date() + timedelta(days=1)
- ## Transform Dates
- #temp_date_start = to_date - timedelta(days=60)
- #temp_date_end = to_date
- ##print(f'getting data for {symbol}')
- #while temp_date_start > from_date:
- start_time2 = time.time()
- temp_df = get_historic_quotes(symbol, requestdate=requestdata, limit=50000)
- #print('thread 3', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
- #print(time.time() - start_time2, '\n')
- #print('thread 3', '\n', temp_df)
- temp_date_end = temp_date_end - timedelta(days=60)
- temp_date_start = temp_date_start - timedelta(days=2)
- if isinstance(type(temp_df), str):
- return
- #else:
- # Add df to database
- #print(temp_df)
- if temp_df is not None or len(temp_df) > 0:
- #print('writing to quotes ->' + str(len(temp_df)))
- temp_df.to_sql('stocksdata_hist_quotes', engine, if_exists='append', index=False, method='multi')
- time.sleep(0.1)
- temp_df=None
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- #print(time.time() - start_time2)
- #stocks
- def save_stock_ticks_to_redis(message):
- try:
- z = time.time()
- keys = {'sym': 'symbol', 'x': 'exch_id', 'i': 'trade_id', 'z': 'tape', 'p': 'price', 's': 'trade_size', 'c': 'conditions', 't': 'trade_time'}
- new_message = []
- global stock_ticks_df
- cst = pytz.timezone('US/Central')
- #dst = pytz.timezone('America/Chicago')
- UTC = pytz.utc
- dt = datetime.now(cst)
- l = ['sym', 'x', 'i', 'z', 'p', 's', 'c','t']
- for d in message:
- del d['ev'] # delete status
- f = set(l) - d.keys() # Compare response with expected response
- g = {k: 'NULL' for k in f} # Fill any blanks
- d.update(g) # Update dict
- d = {keys[name]: val for name, val in d.items()}
- d['tdate'] = unix_convert(d['trade_time'])
- #print('tdate=',d['tdate'])
- #print('trade_time=',d['trade_time'])
- #print(' ')
- d['save_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
- cols = ['symbol', 'exch_id', 'trade_id', 'tape', 'price', 'trade_size', 'conditions', 'trade_time',
- 'tdate', 'save_date']
- #print(d)
- d = {k: d[k] for k in cols}
- new_message.append(d)
- stock_ticks_df = stock_ticks_df.append(pd.DataFrame(new_message), ignore_index=True)
- #df.to_csv('test3.csv')
- #df.to_sql('stocksdata_trades', engine, if_exists='append', index=False, method='multi')
- #redis_message(new_message)
- #print(new_message)
- #print(time.time()-z)
- except Exception:
- traceback.print_exc()
- return None
- def aggregate_candles(ticker: str, message, resolution: int = 1):
- trade = message
- struct = AGGREGATES[ticker]
- # THE AGGREGATION
- AGGREGATES[ticker]['open'] = struct['open'] if struct['open'] else trade['timestamp']
- AGGREGATES[ticker]['close'] = trade['price']
- AGGREGATES[ticker]['high'] = max(struct['high'], trade['price'])
- AGGREGATES[ticker]['low'] = min(struct['low'], trade['price'])
- AGGREGATES[ticker]['volume'] = struct['volume'] + trade['trade_size']
- AGGREGATES[ticker]['timestamp'] = trade['timestamp']
- if int(trade['t']) == int(struct['end']):
- print(f'{ticker}: aggregated candle formed. Reached end of current timeframe...')
- _struct = AGGREGATES[ticker]
- # resetting struct for the ticker for next aggregation cycle time frame
- AGGREGATES[ticker] = {'ticker': ticker, 'res': resolution, 'low': float('inf'), 'high': 0,
- 'close': None, 'open': None, 'timestamp': None,
- 'volume': 0, 'start': struct['end'],
- 'end': struct['end'] + datetime.timedelta(minutes=resolution)}
- return parse_struct(_struct)
- elif int(trade['t']) < int(struct['end']):
- print(f'{ticker}: timeframe end not reached yet. Candle aggregated...')
- return False
- else:
- print(f'{ticker}: received timestamp: {int(trade["t"])} || end timestamp: {int(struct["end"])}')
- return False
- #columns in data frame
- df_cols = ["symbol", "open", "high", "low", "close", "volume", "timestamp_tick"]
- data_frame = pd.DataFrame(data=[],columns=df_cols, index=[])
- def on_tick(message):
- try:
- z = time.time()
- global big_df
- keys = {'sym': 'symbol', 'x': 'exch_id', 'i': 'trade_id', 'z': 'tape', 'p': 'price', 'q': 'sequence', 's': 'trade_size', 'c': 'conditions', 't': 'trade_time'}
- new_message = []
- cst = pytz.timezone('US/Central')
- #dst = pytz.timezone('America/Chicago')
- UTC = pytz.utc
- dt = datetime.now(cst)
- l = ['sym', 'x', 'i', 'z', 'p', 'q', 's', 'c','t']
- for d in message:
- del d['ev'] # delete status
- f = set(l) - d.keys() # Compare response with expected response
- g = {k: 'NULL' for k in f} # Fill any blanks
- d.update(g) # Update dict
- d = {keys[name]: val for name, val in d.items()}
- #resample('MarketMarker', d['symbol'], '1T', '1T', '1T', 'stocksdata_agg_sec', 'stocksdata_trades','1T', True)
- #resample.resample_price(self)
- d['tdate'] = unix_convert(d['trade_time'])
- d['save_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
- cols = ['symbol', 'exch_id', 'trade_id', 'tape', 'price', 'sequence', 'trade_size', 'conditions', 'trade_time',
- 'tdate', 'save_date']
- #print(d)
- d = {k: d[k] for k in cols}
- new_message.append(d)
- df = pd.DataFrame(new_message)
- #big_df.append(df)
- big_df = big_df.append(df, ignore_index=True, sort=False)
- #df.to_csv('test3.csv')
- #df.to_sql('stocksdata_trades', engine, if_exists='append', index=False, method='multi')
- #redis_message("stock_trades_candles", new_message)
- print('')
- print(big_df)
- #print(new_message)
- #print(time.time()-z)
- except Exception:
- traceback.print_exc()
- return None
- #message = ticks
- #new_message = []
- ##if message is not None:
- # #for d in message:
- # # #del d['ev'] # delete status
- # # #if 'op' not in d:
- # # # d['op'] = None
- # # d = {keys[name]: val for name, val in d.items()}
- # # d['tdate'] = unix_convert(d['time_end'])
- # # d['save_date'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
- # # d['underlying_symbol'] = underlying_symbol
- # # d['option_strike'] = int(strike) / 1000
- # # d['option_type'] = option_type
- # # d['symbol'] = option_symbol
- # # d['option_expiration'] = option_expiration
- # # cols = ['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
- # # 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']
- # # d = {k: d[k] for k in cols}
- # # new_message.append(d)
- # #redis_message('stock_trades_candles', new_message)
- def test1():
- global data_frame, df_cols
- data = dict() #keeps extracted tick data
- #for var in ticks:
- # print (ticks.index(var),var)
- #return
- #for tick in ticks:
- # print(ticks.index())
- #sym = tick["sym"]
- ##price = tick["p"]
- #open = tick["p"]
- #high = tick["p"]
- #low = tick["p"]
- #close = tick["p"]
- #volume = tick["s"]
- #timestamp_tick = datetime.utcfromtimestamp(tick["t"]/1000)
- ##fix timestamp to be from message and not local
- #timestamp = str(datetime.now().time())
- ##data[timestamp] = [sym, price, volume, timestamp_tick]
- #data[timestamp] = [sym, open, high, low, close, volume, timestamp_tick]
- print(ticks)
- #sym = ticks[1]["sym"]
- ##price = tick["p"]
- #open = ticks[1]["p"]
- #high = ticks[1]["p"]
- #low = ticks[1]["p"]
- #close = ticks[1]["p"]
- #volume = ticks[1]["s"]
- #timestamp_tick = datetime.utcfromtimestamp(ticks[1]["t"]/1000)
- #print(datetime.utcfromtimestamp(ticks[1]["t"]/1000))
- sym = ticks[0]["sym"]
- #price = tick["p"]
- open = ticks[0]["p"]
- high = ticks[0]["p"]
- low = ticks[0]["p"]
- close = ticks[0]["p"]
- volume = ticks[0]["s"]
- timestamp_tick = datetime.utcfromtimestamp(ticks[0]["t"]/1000)
- print(datetime.utcfromtimestamp(ticks[0]["t"]/1000))
- #ticks[1]['sym']
- #data[timestamp_tick] = [token, ltp, volume]
- ##data[timestamp] = [sym, price, volume, timestamp_tick]
- data[timestamp_tick] = [sym, open, high, low, close, volume, timestamp_tick]
- tick_df = pd.DataFrame(data.values(), columns=df_cols, index=data.keys()) #convert data to a DataFrame
- data_frame = data_frame.append(tick_df) # append to existing
- #data_frame.groupby(data_frame['symbol'])
- #data_frame.set_index('Timestamp_Tick', inplace=True)
- data_frame.set_index([pd.DatetimeIndex(data_frame["timestamp_tick"])], inplace=True)
- aggregation = {'open' :'first',
- 'high' :'max',
- 'low' :'min',
- 'close' :'last',
- 'volume':'sum'}
- #print("DataFrame: \n", data_frame)
- df_1m = data_frame.groupby(data_frame['symbol']).resample('1T').agg(aggregation)
- df_3m = data_frame.groupby(data_frame['symbol']).resample('3T').agg(aggregation)
- #time.sleep(1)
- #df_3m.dropna(thresh=2, inplace=True)
- #print(trades)
- print(df_1m)
- #print(df_3m)
- #test and fix below resample code
- timeframe = '1min'
- #tick_data['DATETIME'] = pd.to_datetime(tick_data['DATE'] + ' ' + tick_data['TIME'])
- #tick_data.set_index('DATETIME', inplace=True)
- #ohlcv_data = pd.DataFrame(columns=[
- # 'SYMBOL_N',
- # 'open',
- # 'high',
- # 'low',
- # 'close',
- # 'volume'])
- #for symbol in tick_data['SYMBOL_N'].unique():
- # ohlcv_symbol = tick_data.loc[tick_data['SYMBOL_N'] == symbol, 'PRICE'].resample(timeframe).ohlc()
- # ohlcv_symbol['SYMBOL_N'] = symbol
- # ohlcv_symbol['volume'] = (tick_data.loc[tick_data['SYMBOL_N'] == symbol, 'VOLUME'].resample(timeframe).max() -
- # tick_data.loc[tick_data['SYMBOL_N'] == symbol, 'VOLUME'].resample(timeframe).max().shift(1))
- # ohlcv_data = ohlcv_data.append(ohlcv_symbol, sort=False)
- #print(ohlcv_data)
- def save_candlesticks(message):
- #global stock_ticks_df
- #global one_minute_df
- global current_tick, previous_tick, in_position
- try:
- previous_tick = current_tick
- current_tick = message[0]
- #current_tick = json.loads(message)[0]
- symbol = current_tick['sym']
- #print(current_tick)
- #print(symbol)
- #print("=== Received Tick ===")
- #print("{} @ {} sym:{}".format(current_tick['t'], current_tick['p'], current_tick['sym']))
- tick_datetime_object = datetime.utcfromtimestamp(current_tick['t']/1000)
- tick_dt = tick_datetime_object.strftime('%Y-%m-%d %H:%M')
- price = current_tick['p']
- #price = 0
- #previous_price = previous_tick['p']
- previous_price = 0
- tick_volume = current_tick['s']
- #print(tick_datetime_object.minute)
- #print(tick_dt)
- #print(symbol)
- #print('minutes_processed=',minutes_processed)
- if not symbol in minutes_processed:
- if not tick_dt in minutes_processed:
- print("starting new candlestick")
- minutes_processed[symbol, tick_dt] = True
- #pprint.pprint(minutes_processed)
- #if len(minute_candlesticks) > 0:
- # minute_candlesticks[-1]['close'] = previous_price
- vols = {}
- vols[symbol, tick_dt] = 0
- for current_tick in minute_candlesticks:
- if symbol not in vols:
- if tick_dt not in vols:
- vols[symbol, tick_dt] = 0
- vols[symbol, tick_dt] += int(current_tick['volume'])
- #print('p=', current_tick['p'])
- minute_candlesticks.append({
- "symbol": symbol,
- "minute": tick_dt,
- "open": price,
- "high": price,
- "low": price,
- "close": price,
- "volume": tick_volume,
- "total_volume": vols[symbol, tick_dt]
- })
- trades = pd.DataFrame.from_dict(minute_candlesticks)#.tail()
- #trades.set_index(['symbol', pd.DatetimeIndex('minute')])
- print(trades)
- #trades.set_index(pd.DatetimeIndex(minute_candlesticks['minute'], unit='ms'), inplace=True)
- #aggregation = {'open' :'first',
- # 'high' :'max',
- # 'low' :'min',
- # 'close' :'last',
- # 'volume':'sum'}
- #df_1m = trades.resample('1T').agg(aggregation)
- #df_3m = trades.resample('3T').agg(aggregation)
- #df_3m.dropna(thresh=2, inplace=True)
- #print(trades)
- #print(df_1m)
- #print(df_3m)
- #if len(minute_candlesticks) > 0:
- # current_candlestick = minute_candlesticks[-1]
- # if price > current_candlestick['high']:
- # current_candlestick['high'] = price
- # if price < current_candlestick['low']:
- # current_candlestick['low'] = price
- #if current_tick['s'] > 0:
- # current_candlestick['volume'] = [sum(current_tick['s'])]
- #print("== Candlesticks ==")
- #for candlestick in minute_candlesticks:
- # print(candlestick)
- #if len(minute_candlesticks) > 3:
- # print("== there are more than 3 candlesticks, checking for pattern ==")
- # last_candle = minute_candlesticks[-2]
- # previous_candle = minute_candlesticks[-3]
- # first_candle = minute_candlesticks[-4]
- # print("== let's compare the last 3 candle closes ==")
- # if last_candle['close'] > previous_candle['close'] and previous_candle['close'] > first_candle['close']:
- # print("=== Three green candlesticks in a row, let's make a trade! ===")
- # distance = last_candle['close'] - first_candle['open']
- # print("Distance is {}".format(distance))
- # profit_price = last_candle['close'] + (distance * 2)
- # print("I will take profit at {}".format(profit_price))
- # loss_price = first_candle['open']
- # print("I will sell for a loss at {}".format(loss_price))
- # if not in_position:
- # print("== Placing order and setting in position to true ==")
- # in_position = True
- # place_order(profit_price, loss_price)
- # sys.exit()
- # else:
- # print("No go")
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- #one_minute_df = stock_ticks_df.assign(Timestamp = pd.to_datetime(stock_ticks_df['tdate'],unit='ms')).set_index('tdate')
- #one_minute_df.resample('1min')['price', 'symbol'].ohlc()
- #one_minute_df['volume'] = ticks_df['trade_size'].resample('1T').sum()
- #print(one_minute_df)
- #print(stock_ticks_df)
- #resample_timeframe = '1T'
- #rule = 's'
- ##historic_data_table = historic_data_table
- ##streaming_data_table = streaming_data_table
- ##tick_rule = tick_rule
- #is_origin = False
- #one_minute_df = resample_price(rule, resample_timeframe, is_origin)
- #if stock_ticks_df.empty != True:
- # if len(stock_ticks_df) > 1000:
- #data_ask = data_frame['Ask'].resample('15Min').ohlc()
- #stock_ticks_df = stock_ticks_df.set_index(['tdate'], ['symbol'])
- #print(stock_ticks_df['price'].resample('1Min').ohlc())
- #one_minute_df = stock_ticks_df['price'].resample('1T').ohlc()
- #one_minute_df['volume'] = stock_ticks_df['trade_size'].resample('1T').sum()
- ## to forward fill no volume bars with last close, use:
- #one_minute_df['volume'].fillna(0, inplace=True)
- #one_minute_df['close'].ffill(inplace=True)
- #one_minute_df['open'] = np.where(one_minute_df['volume'] <= 0, one_minute_df['close'], one_minute_df['open'])
- #one_minute_df['high'] = np.where(one_minute_df['volume'] <= 0, one_minute_df['close'], one_minute_df['high'])
- #one_minute_df['low'] = np.where(one_minute_df['volume'] <= 0, one_minute_df['close'], one_minute_df['low'])
- ## otherwise, drop empty volume bars
- #one_minute_df.dropna(inplace=True)
- #one_minute_df.head()
- #stock_ticks_df = stock_ticks_df.assign(tdate = pd.to_datetime(stock_ticks_df['trade_time'],unit='ms')).set_index(['tdate'], ['symbol'])
- #one_minute_df = stock_ticks_df.resample('1min')['price'].ohlc()
- #one_minute_df = one_minute_df.append(stock_ticks_df)
- #one_minute_df.index = pd.to_datetime(one_minute_df.index, unit='ms')
- #ggframe=one_minute_df.set_index(['tdate'], ['symbol'], ['trade_size'])
- #candles=ggframe.groupby('symbol').resample('1min').agg({'LTP':'ohlc'})
- #print(candles)
- def stock_trades_process_message(ws, msg):
- try:
- message = json.loads(msg)
- if message[0]['ev'] != 'status':
- ###threading.Thread(target=save_stock_ticks_to_redis, args=[message]).start()
- #threading.Thread(target=save_candlesticks, args=[message]).start()
- threading.Thread(target=on_tick, args=[message]).start()
- #print(datetime.now(tz=timezone.utc), "streaming: ", message[0]['sym'], '\t', message[0]['x'], '\t',
- # message[0]['s'], '\t', message[0]['p'])
- except Exception:
- traceback.print_exc()
- return None
- def stock_trades_error_handler(ws, error):
- #raise ValueError('an error happened:', error)
- print("error ", error)
- pass
- def stock_trades_close_handler(ws, close_code, close_msg):
- print("closed connection", close_code, close_msg)
- main()
- pass
- #return None
- def get_stocks_snapshot(symbols=None):
- try:
- #start_time2 = time.time()
- # Date Info
- #from_date = '2021-01-01'
- #from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
- #to_date = datetime.today().date() + timedelta(days=1)
- ## Transform Dates
- #temp_date_start = to_date - timedelta(days=60)
- #temp_date_end = to_date
- ##print(f'getting data for {symbol}')
- #while temp_date_start > from_date:
- #start_time2 = time.time()
- if symbols is None:
- temp_df = get_current_stocks_snapshot()
- else:
- temp_df = get_current_stocks_snapshot(symbols)
- #print('thread 3', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
- #print(time.time() - start_time2, '\n')
- #print('thread 3', '\n', temp_df)
- #temp_date_end = temp_date_end - timedelta(days=60)
- #temp_date_start = temp_date_start - timedelta(days=2)
- if isinstance(type(temp_df), str):
- return
- #else:
- # Add df to database
- #print(temp_df)
- if temp_df is not None:# or len(temp_df) > 0:
- #print('writing to quotes ->' + str(len(temp_df)))
- #temp_df.to_sql('stocksdata_snapshots', engine, if_exists='append', index=False, method='multi')
- time.sleep(0.1)
- temp_df=None
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- #print(time.time() - start_time2)
- def get_daily_stock_open_close(symbol):
- try:
- #start_time2 = time.time()
- # Date Info
- from_date = '2021-10-01'
- from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
- to_date = datetime.today().date() + timedelta(days=-1)
- # Transform Dates
- temp_date_start = to_date - timedelta(days=3)
- temp_date_end = to_date
- #print(f'getting data for {symbol}')
- start_date = from_date
- end_date = datetime.today().strftime('%Y-%m-%d')
- #for single_date in daterange(start_date, end_date):
- # print(single_date.strftime("%Y-%m-%d"))
- #first_date = from_date
- #duration = timedelta(days=10)
- #for d in range(duration.days + 1):
- # day = first_date + timedelta(days=d)
- # start_time2 = time.time()
- # temp_df = get_historic_stock_daily_open_close(symbol, requestdate=day)
- #print(symbol)
- #print(day)
- #print(temp_df)
- start_date = date(2021, 11, 1)
- end_date = date(2021, 11, 4)
- delta = timedelta(days=1)
- #get_bars(symbol)
- while start_date <= end_date:
- print(symbol, start_date)
- temp_df = get_historic_stock_daily_open_close(symbol, requestdate=temp_date_start)
- #future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
- #future1 = executor.submit(get_bars, symbol)
- #future2 = executor.submit(get_trades, symbol)
- #future3 = executor.submit(get_quotes, symbol)
- #future4 = executor.submit(get_daily_stock_open_close, symbol)
- #temp_df = get_historic_trades(symbol=symbol, requestdate=temp_date_start, limit=50000)
- start_date += delta
- #return
- #while temp_date_start > from_date:
- # start_time2 = time.time()
- ##temp_df = get_historic_stock_daily_open_close(symbol, requestdate=requestdata)
- #print(temp_df)
- #print('thread 3', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
- #print(time.time() - start_time2, '\n')
- #print('thread 3', '\n', temp_df)
- #temp_date_end = temp_date_end - timedelta(days=1)
- #temp_date_start = temp_date_start - timedelta(days=1)
- if isinstance(type(temp_df), str):
- return
- #else:
- # Add df to database
- #print(temp_df)
- #if temp_df is not None or len(temp_df) > 0:
- if temp_df is not None:
- #print('writing to quotes ->' + str(len(temp_df)))
- temp_df.to_sql('stocksdata_hist_quotes', engine, if_exists='append', index=False, method='multi')
- time.sleep(0.1)
- temp_df=None
- except Exception as exe:
- print(exe)
- traceback.print_exc()
- time.sleep(10)
- df = None
- #print(time.time() - start_time2)
- def get_data(symbol):
- start_time2 = time.time()
- # Date Info
- from_date = '2019-01-01'
- from_date = datetime.strptime(from_date, '%Y-%m-%d').date()
- to_date = datetime.today().date() + timedelta(days=1)
- # Transform Dates
- temp_date_start = to_date - timedelta(days=60)
- temp_date_end = to_date
- print(f'getting data for {symbol}')
- while temp_date_start > from_date:
- temp_df = call_api(symbol, temp_date_start, temp_date_end)
- temp_date_end = temp_date_end - timedelta(days=60)
- temp_date_start = temp_date_start - timedelta(days=60)
- if isinstance(type(temp_df), str):
- break
- #else:
- # Add df to database
- #print(temp_df)
- #temp_df.to_sql('stockdata_hist', engine, if_exists='append', index=False, method='multi')
- print(time.time() - start_time2)
- def daterange(start_date, end_date):
- for n in range(int ((end_date - start_date).days)):
- yield start_date + timedelta(n)
- def get_option_trades(option_symbol: str, timestamp=None, timestamp_lt=None, timestamp_lte=None,
- timestamp_gt=None, timestamp_gte=None, limit: int = 50000, order='asc',
- raw_response: bool = False):
- try:
- z = time.time()
- o = options.OptionsPolygon
- #from_date = '2021-10-28'
- #print(option_symbol, timestamp)
- df = get_historic_option_trades(option_symbol, requestdate=timestamp)
- #message = get_historic_option_trades(option_symbol, requestdate=timestamp)
- #temp_df = o.get_option_trades('O:TSLA211029C01150000', requestdate=from_date, limit=50000)
- #temp_df = o.get_option_trades(option_symbol, requestdate=from_date, limit=50000)
- #df = pd.DataFrame.from_dict(temp_df['results'])
- #df = pd.DataFrame.from_dict(message['results'])
- #return
- if df is not None:
- #cols = ['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
- # 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']
- #new_message = []
- #df = {k: df[k] for k in cols}
- #new_message.append(df)
- #redis_message('historic_option_trades', new_message)
- #df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
- #df['save_date'] = datetime.utcnow()
- #df = df[['symbol', 'price', 'size', 'sequence_number', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']]
- print('\n', option_symbol, '\t', timestamp, '\t', len(df))
- df.to_sql('optionsdata_hist_trades', engine, if_exists='append', index=False, method='multi')
- #print(time.time()-z)
- #first_date = from_date
- #duration = timedelta(days=10)
- #for d in range(duration.days + 1):
- # day = first_date + timedelta(days=d)
- # start_time2 = time.time()
- # temp_df = get_trades(symbol, requestdate=day)
- #pprint.pprint(message)
- except Exception:
- traceback.print_exc()
- return None
- def _get_response(path: str, params: dict = None,
- raw_response: bool = True) -> Union[Response, dict]:
- """
- Get response on a path. Meant to be used internally but can be used if you know what you're doing
- :param path: RESTful path for the endpoint. Available on the docs for the endpoint right above its name.
- :param params: Query Parameters to be supplied with the request. These are mapped 1:1 with the endpoint.
- :param raw_response: Whether or not to return the ``Response`` Object. Useful for when you need to check the
- status code or inspect the headers. Defaults to True which returns the ``Response`` object.
- :return: A Response object by default. Make ``raw_response=False`` to get JSON decoded Dictionary
- """
- BASE = 'https://api.polygon.io'
- time_out_conf = httpx.Timeout(connect=10, read=10, pool=10,
- write=10)
- session = requests.session()
- session.headers.update({'Authorization': f'Bearer {options_key}'})
- _res = session.request('GET', BASE + path, params=params, timeout=10)
- #_res = session.request('GET', BASE + path, params=params, timeout=time_out_conf)
- if raw_response:
- return _res
- return _res.json()
- #temporary
- def get_options_aggregate_bars( option_symbol: str, from_date, to_date, adjusted: bool = True,
- sort='asc', limit: int = 50000, multiplier: int = 1, timespan='day',
- raw_response: bool = False) -> Union[Response, dict]:
- """
- Get aggregate bars for a stock over a given date range in custom time window sizes.
- For example, if ``timespan = ‘minute’`` and ``multiplier = ‘5’`` then 5-minute bars will be returned.
- `Official Docs
- <https://polygon.io/docs/get_v2_aggs_ticker__stocksTicker__range__multiplier___timespan___from___to__anchor>`__
- :param symbol: The ticker symbol of the stock/equity.
- :param from_date: The start of the aggregate time window. Could be ``datetime`` or ``date`` or string
- ``YYYY-MM-DD``
- :param to_date: The end of the aggregate time window. Could be ``datetime`` or ``date`` or string ``YYYY-MM-DD``
- :param adjusted: Whether or not the results are adjusted for splits. By default, results are adjusted. Set this
- to false to get results that are NOT adjusted for splits.
- :param sort: Sort the results by timestamp. See :class:`polygon.enums.SortOrder` for choices. ``asc`` default.
- :param limit: Limits the number of base aggregates queried to create the aggregate results. Max 50000 and
- Default 5000.
- :param multiplier: The size of the timespan multiplier. Must be a positive whole number.
- :param timespan: The size of the time window. See :class:`polygon.enums.Timespan` for choices. defaults to
- ``day``
- :param raw_response: Whether or not to return the ``Response`` Object. Useful for when you need to say check the
- status code or inspect the headers. Defaults to False which returns the json decoded
- dictionary.
- :return: A JSON decoded Dictionary by default. Make ``raw_response=True`` to get underlying response object
- """
- if isinstance(from_date, date) or isinstance(from_date, datetime):
- from_date = from_date.strftime('%Y-%m-%d')
- if isinstance(to_date, date) or isinstance(to_date, datetime):
- to_date = to_date.strftime('%Y-%m-%d')
- #timespan, sort = _change_enum(timespan, str), _change_enum(sort, str)
- option_symbol = str(option_symbol).upper()
- #_path = '/v2/aggs/ticker/O:AA211112P00045000/range/1/minute/2021-11-08/2021-11-12?adjusted=true&sort=asc&limit=120&apiKey=iJbpOayAiB6_j3DIs6WbZ79ZG4SlV5eb'
- _path = f'/v2/aggs/ticker/O:{option_symbol}/range/{multiplier}/{timespan}/{from_date}/{to_date}'
- #_path = f'/v2/aggs/ticker/{option_symbol.upper()}/range/{multiplier}/{timespan}/{from_date}/{to_date}'
- _data = {'adjusted': 'true' if adjusted else 'false',
- 'sort': sort,
- 'limit': limit}
- _res = _get_response(_path)#, params=_data)
- if raw_response:
- return _res
- #print(_res.json())
- return _res.json()
- def get_bars_options(option_symbol: str, timestamp=None, timestamp_lt=None, timestamp_lte=None,
- timestamp_gt=None, timestamp_gte=None, limit: int = 50000, order='asc',
- raw_response: bool = False):
- try:
- z = time.time()
- o = options.OptionsPolygon
- ref = reference.ReferencePolygon
- if '_' in option_symbol:
- option_symbol = ref.convert_tda_option_to_polygon(option_symbol)
- #from_date = '2021-10-28'
- #print(option_symbol, timestamp)
- #start_date = date(2021, 11, 8)
- #end_date = date(2021, 11, 12)
- start_date = '2021-10-01'
- end_date = '2021-11-19'
- temp_df = get_historic_bars_options(option_symbol, start_date, end_date, adjusted=True, sort='desc', limit=50000, multiplier=1, timespan='minute')
- #start_date += delta
- #while temp_date_start > from_date:
- # start_time2 = time.time()
- # temp_df = get_historic_bars(symbol, temp_date_start, temp_date_end)
- # #print('thread 1', symbol, '\t', temp_date_start, '\t', temp_date_end, '\t', '\n')
- # #print(time.time() - start_time2, '\n')
- # #print('thread 1', '\n', temp_df)
- # temp_date_end = temp_date_end - timedelta(days=60)
- # temp_date_start = temp_date_start - timedelta(days=60)
- #if isinstance(type(temp_df), str):
- # break
- #else:
- # Add df to database
- #print(temp_df)
- start_time2 = time.time()
- to_sql = True
- #if temp_df is not None or len(temp_df) > 0:
- if temp_df is not None:
- if to_sql == True:
- print('writing to bars -> ' + str(option_symbol) + ' ' + str(len(temp_df)))
- temp_df.to_sql('optionsdata_hist_bars', engine, if_exists='append', index=False, method='multi')
- #time.sleep(0.1)
- else:
- #pprint.pprint(temp_df)
- #bars_df.append(temp_df, ignore_index=True)
- frames = [bars_df, temp_df]
- bars_df = pd.concat(frames)
- #print(bars_df)
- #print(len(bars_df))
- #bars_df
- #print(temp_df)
- temp_df=None
- except Exception:
- traceback.print_exc()
- return None
- ## Does not work
- def get_option_trades_redis(option_symbol: str, timestamp=None, timestamp_lt=None, timestamp_lte=None,
- timestamp_gt=None, timestamp_gte=None, limit: int = 50000, order='asc',
- raw_response: bool = False):
- try:
- z = time.time()
- o = options.OptionsPolygon
- #from_date = '2021-10-28'
- print(option_symbol, timestamp)
- #df = get_historic_option_trades(option_symbol, requestdate=timestamp)
- o = options.OptionsPolygon
- resp = o.get_option_trades(option_symbol, requestdate=timestamp, limit=50000)
- #message = get_historic_option_trades(option_symbol, requestdate=timestamp)
- message = resp
- new_message = []
- if message is not None:
- for d in message:
- #del d['ev'] # delete status
- #if 'op' not in d:
- # d['op'] = None
- d = {keys[name]: val for name, val in d.items()}
- d['tdate'] = unix_convert(d['time_end'])
- d['save_date'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
- d['underlying_symbol'] = underlying_symbol
- d['option_strike'] = int(strike) / 1000
- d['option_type'] = option_type
- d['symbol'] = option_symbol
- d['option_expiration'] = option_expiration
- cols = ['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
- 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']
- d = {k: d[k] for k in cols}
- new_message.append(d)
- redis_message('historic_option_trades', new_message)
- #if 'results' in resp:
- # df = pd.DataFrame.from_dict(resp['results'])
- # if df is not None and df.empty != True:
- # df.columns = ['conditions', 'exchange', 'participant_timestamp', 'price', 'sip_timestamp', 'size']
- # #df.columns = ['conditions', 'exchange', 'price', 'sequence_number', 'sip_timestamp', 'size']
- # polygon_option_symbol = symbol
- # option_numbers = re.findall(r'\d+', polygon_option_symbol)
- # underlying_symbol = polygon_option_symbol[:polygon_option_symbol.index(option_numbers[0])]
- # option_type = str(polygon_option_symbol[polygon_option_symbol.index(option_numbers[1]) - 1:])[:1]
- # option_expiration = str(option_numbers[0])
- # #rint(df['price'])
- # option_strike = str(option_numbers[1])
- # #del df['sequence_number']
- # df.insert(0, 'symbol', symbol)
- # df.insert(1, 'underlying_symbol', underlying_symbol)
- # df.insert(2, 'option_type', option_type)
- # df.insert(3, 'option_expiration', option_expiration)
- # df.insert(4, 'option_strike', int(option_strike)/1000)
- # df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
- # df['save_date'] = datetime.utcnow()
- # #df = df[['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'sequence_number', 'size',
- # df = df[['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
- # 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']]
- # return df.to_json(orient='records')[1:-1].replace('},{', '} {')
- # else:
- # df=None
- #else:
- # df = None
- #temp_df = o.get_option_trades('O:TSLA211029C01150000', requestdate=from_date, limit=50000)
- #temp_df = o.get_option_trades(option_symbol, requestdate=from_date, limit=50000)
- #df = pd.DataFrame.from_dict(temp_df['results'])
- #df = pd.DataFrame.from_dict(message['results'])
- #return
- #for d in message:
- #if df is not None:
- # cols = ['symbol', 'underlying_symbol', 'option_type', 'option_expiration', 'option_strike', 'price', 'size',
- # 'participant_timestamp', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']
- # new_message = []
- # df = {k: df[k] for k in cols}
- # new_message.append(df)
- # redis_message('historic_option_trades', new_message)
- #df['tdate'] = df['sip_timestamp'].map(lambda x: unix_convert(x))
- #df['save_date'] = datetime.utcnow()
- #df = df[['symbol', 'price', 'size', 'sequence_number', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']]
- #print(len(df))
- #df.to_sql('optionsdata_hist_trades', engine, if_exists='append', index=False, method='multi')
- #print(time.time()-z)
- #first_date = from_date
- #duration = timedelta(days=10)
- #for d in range(duration.days + 1):
- # day = first_date + timedelta(days=d)
- # start_time2 = time.time()
- # temp_df = get_trades(symbol, requestdate=day)
- #pprint.pprint(message)
- except Exception:
- traceback.print_exc()
- return None
- def save_data3(message):
- try:
- z = time.time()
- keys = {'price', 'size', 'sequence_number', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date'}
- new_message = []
- new_dict = message.to_dict('results')
- sql_function_options(new_dict)
- return
- #for d in message:
- for d in new_dict:
- #del d['ev'] # delete status
- #if 'op' not in d:
- # d['op'] = None
- d = {keys[name]: val for name, val in d.items()}
- #d['tdate'] = unix_convert(d['time_end'])
- d['save_date'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
- cols = ['price', 'size', 'sip_timestamp', 'conditions', 'exchange', 'participant_timestamp', 'save_date']
- d = {k: d[k] for k in cols}
- new_message.append(d)
- redis_message(new_message)
- print(time.time()-z)
- except Exception:
- traceback.print_exc()
- return None
- def sql_function_options(messages):
- cur = conn.cursor()
- sio = io.StringIO()
- writer = csv.writer(sio)
- values = [[value for value in message.values()] for message in messages]
- writer.writerows(values)
- cols = ['price', 'size', 'sequence_number', 'sip_timestamp', 'conditions', 'exchange', 'tdate', 'save_date']
- #cols = ['symbol', 'tick_volume', 'total_volume', 'opening_price', 'tick_vwap', 'tick_open', 'tick_close',
- # 'tick_high', 'tick_low', 'vwap', 'avg_trade_size', 'time_beg', 'time_end', 'tdate', 'save_date']
- sio.seek(0)
- cur.copy_from(file=sio, table="optionsdata_trades2", sep=",", columns=cols, null='')
- cur.close()
- return None
- def get_historical_data(symbols):
- z = time.time()
- ref = reference.ReferencePolygon
- #for symbol in symbols:
- # get_bars_options(ref.convert_tda_option_to_polygon(symbol))
- with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count() * 20) as executor:
- #with concurrent.futures.ThreadPoolExecutor(10) as executor:
- #executor.map(get_data1, symbols)
- # #for future in concurrent.futures.as_completed(futures):
- #future1 = executor.map(get_bars, symbols)
- #future1 = executor.map(get_bars_options, symbols)
- for symbol in symbols:
- future1 = executor.submit(get_bars_options, symbol)
- #future2 = executor.map(get_trades, symbols)
- #future3 = executor.map(get_quotes, symbols)
- #for symbol in symbols:
- # future1 = executor.submit(get_bars, symbol)
- #symbol = 'TSLA_102921C1100'
- #for symbol in symbols:
- # #get_option_trades(ref.convert_tda_option_to_polygon(symbol))
- # start_date = date(2021, 11, 8)
- # end_date = date(2021, 11, 11)
- # delta = timedelta(days=1)
- # future1 = executor.submit(get_bars, symbol)
- #get_bars(symbol, start_date, end_date, adjusted=True, sort='desc', limit=50000, multiplier=1, timespan='minute')
- print(time.time()-z)
- #future4 = executor.submit(get_daily_stock_open_close, symbol)
- #while start_date <= end_date:
- # #future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
- # #future1 = executor.submit(get_bars, symbol)
- # #future2 = executor.submit(get_trades, symbol)
- # #future3 = executor.submit(get_quotes, symbol)
- # future4 = executor.submit(get_daily_stock_open_close, symbol)
- # start_date += delta
- def resample_price(rule, resample_timeframe, is_origin):
- # Fetch the results for the specific ticker form the historic_data table
- #hist_data = pd.read_sql_query("select * from {} where ticker = '{}'".format(self.historic_data_table + "_" + self.base_timeframe.replace(" ", "_"), self.tickers[0]),
- # con=self.db).sort_values("date_time", ascending=True)
- #hist_data = hist_data.set_index(['date_time'])
- #hist_data.index = pd.to_datetime(hist_data.index, unit='ms')
- # Call the function responsible for fetching tick data and converting it to the base timeframe.
- # Then concat the historic df and streaming df
- tick_data = convert_tick_ohlc(resample_timeframe)
- #data = pd.concat([hist_data, tick_data])
- #df.reset_index(level=0, inplace=True)
- #return tick_data
- #price_ohlc = pd.DataFrame()
- #if not df.empty:
- # # Resample lower time frame to to higher time fra me OHLC candles
- # # Drop the NA and reset index
- # origin = ''
- # if is_origin:
- # origin = df['tdate'][0]
- # 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'})
- # price_ohlc = price_ohlc.dropna()
- # price_ohlc.reset_index(level=0, inplace=True)
- return tick_data#price_ohlc
- def convert_tick_ohlc(resample_timeframe):
- # Fetch the results for the specific ticker form the streaming_data table
- # Create dataframe and set date_time as index and convert it to a python datetime object
- # Resample them to "base timeframe" OHLC candles and drop the NA
- #data = pd.read_sql_query(
- # "select * from {} where ticker = '{}'".format(self.streaming_data_table, self.tickers[0]),
- # con=self.db).sort_values("date_time", ascending=True)
- #data = df
- global stock_ticks_df
- data = stock_ticks_df
- data_ask = pd.DataFrame()
- if not data.empty:
- #data = data.set_index(['symbol'])
- print('1',data.index.name)
- data.set_index(['tdate'], inplace=True)
- print('2',data.index.name)
- #data = data.set_index(['tdate'])
- #data['tdate'] = pd.to_datetime(data['tdate'])
- print(data['tdate'])
- data['tdate'] = pd.to_datetime(data['tdate'], unit='ms')
- #data['tdate'] = pd.to_datetime(data.index, unit='s')
- #data = data.set_index(['symbol'])
- #data.index = pd.to_datetime(data['tdate'], unit='s')
- #data.index = data['tdate']
- #data.index = pd.to_datetime(data.index, unit='s')
- #data.groupby(['symbol', 'tdate'])
- data_ask = data.groupby(['symbol']).resample(resample_timeframe).agg({'price': 'ohlc', 'trade_size': 'sum'}).reset_index()
- #data_ask = data.resample(resample_timeframe).agg({'price': 'ohlc', 'trade_size': 'sum'}).reset_index()
- data_ask = data_ask.dropna()
- # Flattening the multi-index dataframe to a single level dataframe
- data_ask.columns = data_ask.columns.to_series().str.join('')
- # Renaming the columns for the dataframe
- data_ask = data_ask.rename(columns={"priceopen": "open",
- "pricehigh": "high",
- "pricelow": "low",
- "priceclose": "close",
- "trade_sizetrade_size": "volume"})
- # Reset the index and append ticker/timeframe columns to the dataframe.
- # Convert the dataframe to dictionary.
- # data_ask.reset_index(level=0, inplace=True)
- #print(data_ask)
- #data_ask["symbol"] = tickers#[0]
- return data_ask
- #wp = jp.WebPage(delete_flag=False)
- #clock_div = jp.Span(text='Loading...', classes='text-5xl m-1 p-1 bg-gray-300 font-mono', a=wp)
- #async def clock_counter():
- # while True:
- # clock_div.text = time.strftime("%a, %d %b %Y, %H:%M:%S", time.localtime())
- # jp.run_task(wp.update())
- # await asyncio.sleep(1)
- #async def clock_init():
- # jp.run_task(clock_counter())
- #async def clock_test():
- # return wp
- #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'
- #async def count_down(self, msg):
- # self.show = False
- # if hasattr(msg.page, 'd'):
- # msg.page.remove(msg.page.d)
- # bomb_icon = jp.Icon(icon='bomb', classes='inline-block text-5xl ml-1 mt-1', a=msg.page)
- # 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)
- # msg.page.d = d
- # for i in range(self.start_num, 0 , -1):
- # d.text = str(i)
- # await msg.page.update()
- # await asyncio.sleep(1)
- # d.text = 'Boom!'
- # d.animation = 'zoomIn'
- # d.set_classes('text-red-500 bg-white')
- # bomb_icon.set_class('text-red-700')
- # self.show = True
- #def count_test(request):
- # start_num = int(request.query_params.get('num', 10))
- # animation = request.query_params.get('animation', 'flip')
- # wp = jp.WebPage()
- # count_button = jp.Button(text='Start Countdown', classes=button_classes, a=wp, click=count_down)
- # count_button.start_num = start_num
- # count_button.count_animation = animation
- # return wp
- #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'
- #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'
- #message_classes = 'ml-4 p-2 text-lg bg-red-500 text-white overflow-auto font-mono rounded-lg'
- #shared_div = jp.Div(classes='m-2 h-1/2 border overflow-auto', delete_flag=False)
- #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)
- #button_icon = jp.Icon(icon='paper-plane', classes='text-2xl', delete_flag=False)
- #button_text = jp.Div(text='Send', classes='text-sm', delete_flag=False)
- #message_icon = jp.Icon(icon='comments', classes='text-2xl text-green-600', delete_flag=False)
- #def message_initialize():
- # # Called once on startup
- # d = jp.Div(a=shared_div, classes='flex m-2 border')
- # time_stamp = jp.P(text=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), classes='text-xs ml-2 flex-shrink-0')
- # p = jp.Pre(text='Welcome to the simple message board!', classes=message_classes)
- # d.add(message_icon, time_stamp, p)
- #async def send_message(self, msg):
- # if self.message.value:
- # d = jp.Div(classes='flex m-2 border')
- # time_stamp = jp.P(text=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), classes='text-xs ml-2 flex-shrink-0')
- # p = jp.Pre(text=self.message.value, classes=message_classes)
- # d.add(message_icon, time_stamp, p)
- # shared_div.add_component(d, 0)
- # self.message.value = '' # Clear message box after message is sent
- # await shared_div.update()
- #def message_demo():
- # wp = jp.WebPage()
- # outer_div = jp.Div(classes='flex flex-col h-screen', a=wp)
- # outer_div.add(header)
- # d = jp.Div(classes='flex', a=outer_div)
- # message = jp.Textarea(placeholder='Enter message here', a=d, classes=input_classes, debounce=500)
- # send_button = jp.Button(a=d, click=send_message, classes=button_classes)
- # send_button.add(button_icon, button_text)
- # outer_div.add(shared_div)
- # shared_div.add_page(wp)
- # send_button.message = message
- # return wp
- #wp = jp.WebPage(delete_flag=False)
- #wp.reload_interval = 2.5
- #count_div = jp.Div(a=wp, classes='text-center m-4 p-4 text-white bg-blue-500', style='font-size: 200px')
- #async def increment_counter(start):
- # count_div.counter = start
- # while True:
- # count_div.counter += 1
- # count_div.text = str(count_div.counter)
- # await asyncio.sleep(1)
- #def start_counting():
- # jp.run_task(increment_counter(500))
- #def reload_demo():
- # return wp
- #epoch = datetime(1970, 1, 1)
- #def convert_date(date_string):
- # date = datetime.strptime(date_string, '%Y-%m-%d')
- # return (date - epoch).total_seconds()*1000
- #def stock_test(request):
- # wp = jp.WebPage()
- # ticker = request.query_params.get('ticker', 'MSFT')
- # if ticker not in ['AAPL', 'IBM', 'INTC', 'MSFT']:
- # ticker = 'MSFT'
- # data = pd.read_csv(f'https://elimintz.github.io/stocks/{ticker.upper()}.csv')
- # chart = jp.HighStock(a=wp, classes='m-1 p-2 border w-10/12')
- # o = chart.options
- # o.title.text = 'Historical Stock Price'
- # o.legend = {'enabled': True, 'align': 'right', 'layout': 'proximate'}
- # o.rangeSelector.selected = 4 # Set default range to 1 year
- # x = list(data['Date'].map(convert_date))
- # y = data['Adj Close'].to_list()
- # s = jp.Dict({'name': ticker.upper(), 'data': jp.make_pairs_list(x, y)})
- # o.series = [s]
- # s.tooltip.valueDecimals = 2 # Price displayed by tooltip will have 2 decimal values
- # return wp
- #epoch = datetime(1970, 1, 1)
- #grouping_units = [['week', [1]], ['month', [1, 2, 3, 4, 6]]]
- #chart_dict = {
- # 'rangeSelector': {'selected': 1},
- # 'yAxis': [
- # {'labels': {'align': 'right', 'x': -3}, 'title': {'text': 'OHLC'}, 'height': '60%', 'lineWidth': 2, 'resize': {'enabled': True}},
- # {'labels': {'align': 'right', 'x': -3}, 'title': {'text': 'Volume'}, 'top': '65%', 'height': '35%', 'offset': 0, 'lineWidth': 2}
- # ],
- # 'tooltip': {'split': True},
- # 'series': [
- # {'type': 'candlestick', 'tooltip': {'valueDecimals': 2}, 'dataGrouping': {'units': grouping_units}},
- # {'type': 'column', 'name': 'Volume', 'yAxis': 1, 'dataGrouping': {'units': grouping_units}}
- # ]
- #}
- #def convert_date(date_string):
- # date = datetime.strptime(date_string, '%Y-%m-%d')
- # return (date - epoch).total_seconds()*1000
- #async def stock_test(request):
- # wp = jp.WebPage(highcharts_theme='grid')
- # ticker = request.query_params.get('ticker', 'MSFT').upper()
- # if ticker not in ['AAPL', 'IBM', 'INTC', 'MSFT']:
- # ticker = 'MSFT'
- # data = await jp.JustPy.loop.run_in_executor(None, pd.read_csv, f'https://elimintz.github.io/stocks/{ticker}.csv')
- # chart = jp.HighStock(a=wp, classes='m-1 p-2 border w-10/12', options=chart_dict, style='height: 600px')
- # o = chart.options
- # o.title.text = f'{ticker} Historical Prices'
- # x = list(data['Date'].map(convert_date))
- # o.series[0].data = list(zip(x, data['Open'], data['High'], data['Low'], data['Close']))
- # o.series[0].name = ticker
- # o.series[1].data = list(zip(x, data['Volume']))
- # return wp
- #from random import randrange
- #chart_dict = {
- # 'title': {'text': 'Updating Chart'},
- # 'series': [
- # {'name': 'Random Column', 'type': 'column', 'animation': False, 'data': [randrange(100) for i in range(50)]},
- # {'name': 'Random Scatter', 'type': 'scatter', 'animation': False, 'data': [randrange(100) for i in range(50)]}
- # ],
- # }
- #wp = jp.WebPage(delete_flag=False)
- #chart = jp.HighCharts(a=wp, options=chart_dict, classes='m-1 p-2 border w-10/12')
- #async def chart_updater():
- # while True:
- # await asyncio.sleep(1)
- # for i in range(0,2):
- # chart.options.series[i].data.pop(0)
- # chart.options.series[i].data.append(randrange(100))
- # jp.run_task(wp.update())
- #async def chart_init():
- # jp.run_task(chart_updater())
- #async def chart_test():
- # return wp
- #iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
- #iris_stats = iris.describe().round(3)
- #iris_stats.insert(loc=0, column='stats', value=iris_stats.index)
- #iris_species = list(iris['species'].unique())
- ## Create a dictionary of frames per iris species
- #iris_species_frames = {}
- #for s in iris_species:
- # iris_species_frames[s] = iris.loc[iris['species'] == s]
- #async def click_point(self, msg):
- # print(msg)
- # 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)
- #async def tooltip_formatter(self, msg):
- # # print(msg)
- # tooltip_html = f"""
- # <div style="color: {msg.color}"><span>●</span> {msg.series_name}</div>
- # <div style="color: {msg.color}">{self.col2}: {msg.x}</div>
- # <div style="color: {msg.color}">{self.col1}: {msg.y}</div>
- # """
- # await self.draw_crosshair([{'id': chart_id, 'series': msg.series_index, 'point': msg.point_index} for chart_id in self.chart_list], msg.websocket)
- # return await self.tooltip_update(tooltip_html, msg.websocket)
- #def iris_data():
- # wp = jp.WebPage(highcharts_theme='gray', title='Iris Dataset')
- # 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)
- # d1 = jp.Div(classes='m-2 p-2 border-2', a=wp)
- # chart_list = []
- # for i, col1 in enumerate(iris.columns[:4]):
- # d2 = jp.Div(classes='flex', a=d1)
- # for j, col2 in enumerate(iris.columns[:4]):
- # if i != j: # Not on the diagonal
- # chart = jp.HighCharts(a=d2, style='width: 300px; height: 300px', classes='flex-grow m-1')
- # chart_list.append(chart.id)
- # chart.chart_list = chart_list
- # chart.on('tooltip', tooltip_formatter)
- # chart.tooltip_y = 85
- # chart.on('point_click', click_point)
- # chart.col1 = col1
- # chart.col2 = col2
- # o = chart.options
- # o.chart.type = 'scatter'
- # o.chart.zoomType = 'xy'
- # o.title.text = ''
- # o.legend.enabled = False
- # o.credits.enabled = False if i<3 or j<3 else True # https://api.highcharts.com/highcharts/credits.enabled
- # o.xAxis.title.text = col2 if i==3 else ''
- # o.yAxis.title.text = col1 if j==0 else ''
- # o.xAxis.crosshair = o.yAxis.crosshair = True
- # for k, v in iris_species_frames.items():
- # s = jp.Dict()
- # s.name = k
- # s.allowPointSelect = True # https://api.highcharts.com/highcharts/series.scatter.allowPointSelect
- # s.marker.states.select.radius = 8
- # s.data = list(zip(v.iloc[:, j], v.iloc[:, i]))
- # o.series.append(s)
- # else:
- # chart = jp.Histogram(list(iris.iloc[:, j]),a=d2, style='width: 300px; height: 300px', classes='flex-grow m-1')
- # o = chart.options
- # o.title.text = ''
- # o.legend.enabled = False
- # o.xAxis[0].title.text = col2 if i==3 else ''
- # o.xAxis[1].title.text = ''
- # o.yAxis[0].title.text = col1 if j == 0 else ''
- # o.yAxis[1].title.text = ''
- # o.credits.enabled = False if i < 3 or j < 3 else True
- # # Add two grids, first with the data and second with statistics describing the data
- # iris.jp.ag_grid(a=wp, classes='m-2 p-2', style='height: 500px; width: 800px', auto_size=True, theme='ag-theme-balham-dark')
- # 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')
- # return wp
- #class MyPie(jp.HighCharts):
- # _options = """
- #{
- # chart: {
- # type: 'pie'
- # },
- # title: {
- # text: 'Pie Chart'
- # },
- # tooltip: {
- # pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
- # },
- # plotOptions: {
- # pie: {
- # allowPointSelect: true,
- # cursor: 'pointer',
- # dataLabels: {
- # enabled: true,
- # format: '<b>{point.name}</b>: {point.percentage:.1f}%',
- # }
- # }
- # },
- # series: []
- #}
- # """
- # def __init__(self, data, **kwargs):
- # self.labels = []
- # super().__init__(**kwargs)
- # self.load_json(self._options)
- # pie_series = jp.Dict()
- # pie_series.data = []
- # for i, value in enumerate(data):
- # c = jp.Dict()
- # try:
- # c.name = self.labels[i]
- # except:
- # c.name = str(value)
- # c.y = value
- # pie_series.data.append(c)
- # self.options.series.append(pie_series)
- #def pie_test(request):
- # wp = jp.WebPage()
- # chart = MyPie([2,3,4,5], labels=['Apples', 'Pears', 'Bananas', 'Melons'], a=wp, classes='m-2 p-2 border w-1/2')
- # chart.options.title.text = 'Fruit Distribution'
- # chart.options.series[0].name = 'Fruits'
- # return wp
- #import random
- #import numpy
- #class Histogram(jp.HighCharts):
- # _options = """
- #{
- # title: {
- # text: 'Highcharts Histogram'
- # },
- # xAxis: [{
- # title: { text: 'Data' },
- # alignTicks: false
- # }, {
- # title: { text: 'Histogram' },
- # alignTicks: false,
- # opposite: true
- # }],
- # yAxis: [{
- # title: { text: 'Data' }
- # }, {
- # title: { text: 'Histogram' },
- # opposite: true
- # }],
- # series: [{
- # name: 'Histogram',
- # type: 'histogram',
- # xAxis: 1,
- # yAxis: 1,
- # baseSeries: 's1',
- # zIndex: -1
- # }, {
- # name: 'Data',
- # type: 'scatter',
- # data: [],
- # id: 's1',
- # marker: {
- # radius: 1.5
- # }
- # }]
- #}
- # """
- # def __init__(self, data, **kwargs):
- # super().__init__(**kwargs)
- # self.load_json(self._options)
- # self.options.series[1].data = list(data)
- #def histogram_test(request):
- # wp = jp.WebPage()
- # # Uniform distribution
- # data = [random.randrange(10) for i in range(100)]
- # chart = jp.Histogram(data, a=wp, classes='m-2 border w-1/2')
- # chart.options.title.text = 'Uniform Distribution Histogram'
- # # Normal distribution
- # data = [numpy.random.normal() for i in range(1000)]
- # chart = jp.Histogram(data, a=wp, classes='m-2 border w-1/2')
- # chart.options.title.text = 'Normal Distribution Histogram'
- # return wp
- #import numpy as np
- #class ScatterWithRegression(jp.Scatter):
- # def __init__(self, x, y, **kwargs):
- # super().__init__(x, y, **kwargs)
- # x = np.asarray(x)
- # y = np.asarray(y)
- # m = (len(x) * np.sum(x * y) - np.sum(x) * np.sum(y)) / (len(x) * np.sum(x * x) - np.sum(x) ** 2)
- # b = (np.sum(y) - m * np.sum(x)) / len(x)
- # s = jp.Dict() # The new series
- # s.type = 'line'
- # s.marker.enabled = False
- # s.enableMouseTracking = False
- # min = float(x.min())
- # max = float(x.max())
- # s.data = [[min, m * min + b], [max, m * max + b]]
- # s.name = f'Regression, m: {round(m, 3)}, b: {round(b, 3)}'
- # self.options.series.append(s)
- #def scatter_test(request):
- # wp = jp.WebPage(highcharts_theme='grid-light')
- # 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]
- # 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]
- # jp.Scatter(x, y, a=wp, classes='m-2 w-1/2 border', style='height: 300px')
- # sr = ScatterWithRegression(x, y, a=wp, classes='m-2 w-1/2 border', style='height: 300px')
- # sr.options.title.text = 'Scatter Chart with Regression'
- # return wp
- #grid_options = """
- #{
- # defaultColDef: {
- # filter: true,
- # sortable: true,
- # resizable: true,
- # cellStyle: {textAlign: 'center'},
- # headerClass: 'font-bold'
- # },
- # columnDefs: [
- # {headerName: "Make", field: "make"},
- # {headerName: "Model", field: "model"},
- # {headerName: "Price", field: "price"}
- # ],
- # rowData: [
- # {make: "Toyota", model: "Celica", price: 35000},
- # {make: "Ford", model: "Mondeo", price: 32000},
- # {make: "Porsche", model: "Boxter", price: 72000}
- # ]
- #}
- #"""
- ##def grid_test():
- ## wp = jp.WebPage()
- ## grid = jp.AgGrid(a=wp, options=grid_options)
- ## return wp
- #def grid_test():
- # wp = jp.WebPage()
- # grid = jp.AgGrid(a=wp, options=grid_options, style='height: 200px; width: 300px; margin: 0.25em')
- # for col_def in grid.options.columnDefs:
- # col_def.editable = True
- # grid.options.columnDefs[1].cellClass = ['text-2xl','text-red-500','hover:bg-blue-500']
- # return wp
- #grid_options = {
- # 'rowHeight': 200,
- # 'columnDefs': [
- # {'headerName': "Make", 'field': "make"},
- # {'headerName': "Model", 'field': "model"},
- # {'headerName': "Price", 'field': "price"},
- # ],
- # 'rowData': [
- # {'make': "Toyota", 'model': "Celica", 'price': 4},
- # {'make': "Ford", 'model': "Mondeo", 'price': '<div class="m-2 text-red-500 text-5xl">3</div>'},
- # {'make': "Porsche", 'model': "Boxter", 'price': '<img src="https://www.python.org/static/community_logos/python-powered-h-140x182.png">'}
- # ],
- #}
- #def grid_test():
- # wp = jp.WebPage()
- # grid = jp.AgGrid(a=wp, options=grid_options)
- # grid.html_columns = [2]
- # return wp
- #wm_df = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
- #def grid_test():
- # wp = jp.WebPage()
- # grid = jp.AgGrid(a=wp)
- # grid.load_pandas_frame(wm_df)
- # return wp
- #wm_df = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
- #def grid_test():
- # wp = jp.WebPage()
- # wm_df.jp.ag_grid(a=wp)
- # return wp
- #wm_df = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
- #def grid_test():
- # wp = jp.WebPage()
- # grid = wm_df.jp.ag_grid(a=wp)
- # grid.options.pagination = True
- # grid.options.paginationAutoPageSize = True
- # grid.options.columnDefs[0].cellClass = ['text-white', 'bg-blue-500', 'hover:bg-blue-200']
- # for col_def in grid.options.columnDefs[1:]:
- # col_def.cellClassRules = {
- # 'font-bold': 'x < 20',
- # 'bg-red-300': 'x < 20',
- # 'bg-yellow-300': 'x >= 20 && x < 50',
- # 'bg-green-300': 'x >= 50'
- # }
- # return wp
- grid_options = """
- {
- rowSelection: 'multiple',
- defaultColDef: {
- filter: true,
- sortable: true,
- resizable: true,
- cellStyle: {textAlign: 'center'},
- headerClass: 'font-bold'
- },
- columnDefs: [
- {headerName: "Make", field: "make"},
- {headerName: "Model", field: "model"},
- {headerName: "Price", field: "price"}
- ],
- rowData: [
- {make: "Toyota", model: "Celica", price: 35000},
- {make: "Ford", model: "Mondeo", price: 32000},
- {make: "Porsche", model: "Boxter", price: 72000}
- ]
- }
- """
- def row_selected(self, msg):
- wp = msg.page
- if msg.selected:
- wp.selected_rows[msg.rowIndex] = msg.data
- else:
- wp.selected_rows.pop(msg.rowIndex)
- s = f'Selected rows {sorted(list(wp.selected_rows.keys()))}'
- for i in sorted(wp.selected_rows):
- s = f'{s}\n Row {i} Data: {wp.selected_rows[i]}'
- if wp.selected_rows:
- wp.rows_div.text = s
- else:
- wp.rows_div.text = 'No row selected'
- async def select_all_rows(self, msg):
- await self.grid.run_api('selectAll()', msg.page)
- async def deselect_rows(self, msg):
- await self.grid.run_api('deselectAll()', msg.page)
- def grid_test():
- wp = jp.WebPage()
- wp.selected_rows = {} # Dictionary holding selected rows
- grid = jp.AgGrid(a=wp, options=grid_options, style='height: 200px; width: 300px; margin: 0.25em')
- grid.options.columnDefs[0].checkboxSelection = True
- grid.on('rowSelected', row_selected)
- wp.rows_div = jp.Pre(text='Data will go here when you select rows', classes='border text-lg', a=wp)
- btn_deselect = jp.Button(text='Deselect rows', classes=jp.Styles.button_simple+' m-2', a=wp, click=deselect_rows)
- btn_deselect.grid = grid
- btn_select_all = jp.Button(text='Select all rows', classes=jp.Styles.button_simple+' m-2', a=wp, click=select_all_rows)
- btn_select_all.grid = grid
- return wp
- # Load data showing percent of women in different majors per year
- #wm = pd.read_csv('./snapshot1.csv')
- #wm = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
- def grid_test():
- wp = jp.WebPage()
- wm.jp.ag_grid(a=wp) # a=wp adds the grid to WebPage wp
- #while True:
- # jp.run_task(wp.update())
- # #time.sleep(5)
- return wp
- class AggregationPeriod(str, Enum):
- min_1 = "1min"
- min_2 = "2min"
- min_3 = "3min"
- min_5 = "5min"
- min_10 = "10min"
- min_15 = "15min"
- min_20 = "20min"
- min_30 = "30min"
- min_39 = "39min"
- min_78 = "78min"
- min_130 = "130min"
- min_195 = "195min"
- hour_1 = "1H"
- hour_2 = "2H"
- hour_4 = "4H"
- 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):
- date_rng = pd.date_range(start=market_start_datetime, end=market_end_datetime, freq=resolution)
- for i in range(len(date_rng)):
- if i >= 1:
- if (request_datetime in DateTimeRange(date_rng[i - 1], (date_rng[i] - timedelta(seconds = 1)))):
- return str(date_rng[i - 1]), str((date_rng[i] - timedelta(seconds = 1)))
- #def between_periods(request_datetime, resolution):
- # print(request_datetime)
- # global date_rng
- # bar_start_end(startdatetime='2021-11-12 8:30:00', enddatetime='2021-11-12 15:00:00', resolution=resolution)
- # print(' --- ')
- # for i in range(len(date_rng)):
- # if i >= 1:
- # #print(request_datetime in DateTimeRange(date_rng[i - 1], (date_rng[i] - timedelta(seconds = 1))))
- # if (request_datetime in DateTimeRange(date_rng[i - 1], (date_rng[i] - timedelta(seconds = 1)))):
- # #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)):
- # return str(date_rng[i - 1]), str((date_rng[i] - timedelta(seconds = 1)))
- # #print(date_rng[i - 1], ' - ', date_rng[i] - timedelta(seconds = 1))
- #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):
- # print(request_datetime)
- # global date_rng
- # bar_start_end(startdatetime='2021-11-12 8:30:00', enddatetime='2021-11-12 15:00:00', resolution=resolution)
- # print(' --- ')
- # for i in range(len(date_rng)):
- # if i >= 1:
- # #print(request_datetime in DateTimeRange(date_rng[i - 1], (date_rng[i] - timedelta(seconds = 1))))
- # if (request_datetime in DateTimeRange(date_rng[i - 1], (date_rng[i] - timedelta(seconds = 1)))):
- # #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)):
- # return str(date_rng[i - 1]), str((date_rng[i] - timedelta(seconds = 1)))
- # #print(date_rng[i - 1], ' - ', date_rng[i] - timedelta(seconds = 1))
- def main():
- #stocks_client = polygon.StocksClient(stocks_key)
- #current_price = stocks_client.get_current_price('AMD')
- #print(current_price)
- #return
- #print('min_1')
- #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))
- #print('')
- #print('min_5')
- #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))
- #print('')
- #print('min_39')
- #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))
- #print('')
- #print('min_78')
- #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))
- #print('')
- #print('min_130')
- #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))
- #print('')
- #print('min_195')
- #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))
- #print('')
- #print('hour_1')
- #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))
- #print('')
- #print('hour_2')
- #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))
- #print('')
- #print('hour_4')
- #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))
- #print('')
- #return
- #jp.justpy(grid_test)
- #return
- #jp.justpy(clock_test, startup=clock_init)
- #jp.justpy(count_test)
- #jp.justpy(message_demo, startup=message_initialize)
- #jp.justpy(reload_demo, startup=start_counting, websockets=False)
- #jp.justpy(stock_test)
- #jp.justpy(chart_test, startup=chart_init)
- #jp.justpy(iris_data)
- #jp.justpy(pie_test)
- #jp.justpy(histogram_test)
- #jp.justpy(scatter_test)
- #jp.justpy(grid_test)
- #return
- # Format database and empty previous values
- #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()]],
- # columns=['symbol', 'tick_volume',
- # 'total_volume', 'opening_price', 'tick_vwap', 'tick_open', 'tick_close', 'tick_high',
- # 'tick_low', 'vwap', 'avg_trade_size', 'time_beg', 'time_end', 'tdate', 'save_date'])
- #s = stocks.StocksPolygon
- #pprint.pprint(s.get_daily_stock_open_close('TSLA'))
- #return
- #ref = reference.ReferencePolygon
- #get_option_trades(ref.convert_tda_option_to_polygon('TSLA_021822P1950'), timestamp='2021-10-28')
- #return
- # Backup table
- #print("backing up table")
- # df.to_sql('stockdata_backup', engine, if_exists='replace', index=False)
- # query1 = text("DELETE FROM stockdata_backup WHERE symbol = 'delete_this_row';")
- #query1 = text("DROP TABLE IF EXISTS stockdata_backup;")
- #query2 = text("create table stockdata_backup as (select * from stockdata_hist);")
- #with engine.connect() as conn:
- # conn.execute(query1)
- # conn.execute(query2)
- #Create main table
- #df.to_sql('stockdata_hist', engine, if_exists='replace', index=False)
- #query2 = text("DELETE FROM stockdata_hist WHERE symbol = 'delete_this_row';")
- ##with engine.connect() as conn:
- ## conn.execute(query2)
- # Get new data
- #with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count()) as executor:
- ## #executor.map(get_data1, symbols)
- ### #for future in concurrent.futures.as_completed(futures):
- # #future1 = executor.map(get_bars, symbols)
- # #future2 = executor.map(get_trades, symbols)
- # #future3 = executor.map(get_quotes, symbols)
- # for symbol in symbols:
- # future1 = executor.submit(get_bars, symbol)
- #future2 = executor.submit(get_trades, symbol)
- #future3 = executor.submit(get_quotes, symbol)
- #future4 = executor.submit(get_daily_stock_open_close, symbol)
- #future5 = executor.submit(get_trades, symbol)
- #start_date = date(2021, 10, 25)
- #end_date = date(2021, 10, 29)
- #delta = timedelta(days=1)
- #while start_date <= end_date:
- # print(start_date)
- # start_date += delta
- #return
- #ref = reference.ReferencePolygon
- #symbols_df = pd.read_sql_query('select distinct symbol from option_chain where tdate >= \'2021-11-15\' order by symbol ', con=conn)
- ####symbols_df = pd.read_csv('data/polygon/options_symbols.csv')
- ####symbols = symbols_df['symbol'].to_list()
- #####symbols = 'TSLA_102921C1100'
- #####symbols_list1 = "TSLA,AAPL"
- #####symbols_list1 = symbols
- #####get_stocks_snapshot(symbols_list1.split(','))
- #####get_stocks_snapshot(symbols)
- #####redis_dict_update()
- #####return
- #####get_stocks_snapshot()
- #####return
- #####jp.justpy(comp_test)
- #####jp.justpy(grid_test)
- #####while True:
- #get_stocks_snapshot()
- #####get_historical_data(symbols)
- #####return
- ##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)
- ###symbols_df = pd.read_csv('data/polygon/options_symbols.csv')
- ##i = 1
- ##for trade in trades_df.iterrows():
- ## print(i)
- ## i+=1
- ## on_tick(trade)
- #return
- z = time.time()
- my_client = polygon.StreamClient(stocks_key, polygon.enums.StreamCluster('stocks'), on_message=stock_trades_process_message,
- on_close=stock_trades_close_handler, on_error=stock_trades_error_handler)
- try:
- my_client.start_stream_thread()
- my_client.subscribe_stock_trades()
- #my_client.subscribe_stock_trades(list('TSLA'))
- print(time.time()-z)
- return
- except Exception:
- traceback.print_exc()
- my_client.unsubscribe_stock_trades()
- return
- #with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count() * 20) as executor:
- with concurrent.futures.ThreadPoolExecutor(max_workers=450) as executor:
- #executor.map(get_data1, symbols)
- # #for future in concurrent.futures.as_completed(futures):
- #future1 = executor.map(get_bars, symbols)
- #future2 = executor.map(get_trades, symbols)
- #future3 = executor.map(get_quotes, symbols)
- #for symbol in symbols:
- # future1 = executor.submit(get_bars, symbol)
- #symbol = 'TSLA_102921C1100'
- for symbol in symbols:
- #get_option_trades(ref.convert_tda_option_to_polygon(symbol))
- #start_date = date(2021, 11, 8)
- #end_date = date(2021, 11, 11)
- #delta = timedelta(days=1)
- future1 = executor.submit(get_latest_bar, symbol, 'minute')
- print(latest_min_bar_df)
- print(time.time()-z)
- #print(time.time()-z)
- ##with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count() * 20) as executor:
- #with concurrent.futures.ThreadPoolExecutor(49) as executor:
- # #executor.map(get_data1, symbols)
- ## #for future in concurrent.futures.as_completed(futures):
- # #future1 = executor.map(get_bars, symbols)
- # #future2 = executor.map(get_trades, symbols)
- # #future3 = executor.map(get_quotes, symbols)
- # #for symbol in symbols:
- # # future1 = executor.submit(get_bars, symbol)
- # for symbol in symbols:
- # #get_option_trades(ref.convert_tda_option_to_polygon(symbol))
- # start_date = date(2021, 10, 25)
- # end_date = date(2021, 10, 29)
- # delta = timedelta(days=1)
- # while start_date <= end_date:
- # print(symbol, start_date)
- # future1 = executor.submit(get_option_trades, ref.convert_tda_option_to_polygon(symbol), timestamp=start_date)
- # #future1 = executor.submit(get_bars, symbol)
- # #future2 = executor.submit(get_trades, symbol)
- # #future3 = executor.submit(get_quotes, symbol)
- # #future4 = executor.submit(get_daily_stock_open_close, symbol)
- # start_date += delta
- #get_option_trades('TSLA211029C001150000')
- #get_conditions()
- #pprint.pprint(future4)
- #big_df = pd.Dataframe()
- #temp_df = future1#function_that_gets_temp_df()
- #big_df = pd.concat([temp_df, big_df])
- #big_df.to_sql('stockdata_hist_bars', engine, if_exists='append', index=False, method='multi')
- #s = stocks.StocksPolygon
- #threading.Thread(target=get_data1, args=[symbols]).start()
- #threading.Thread(target=get_data2, args=[symbols]).start()
- #threading.Thread(target=get_data3, args=[symbols]).start()
- #await get_historic_bars(symbols, start, end, timeframe)
- #await get_historic_trades(symbols, start, end, timeframe)
- #await get_historic_quotes(symbols, start, end, timeframe)
- #get_data1(symbols)
- #get_data2(symbols)
- #get_data3(symbols)
- #query3 = text("CREATE INDEX idx_sdh_tdate ON stockdata_hist (tdate);")
- #query4 = text("CREATE INDEX idx_sdh_symbol ON stockdata_hist (symbol);")
- ##with engine.connect() as conn:
- ## conn.execute(query3)
- ## conn.execute(query4)
- def is_mkt_open(market):
- now = datetime.now(pytz.utc)
- TDate = date.today() # get today's date
- mkt = mcal.get_calendar(market)
- tradingDay = mkt.schedule(start_date=TDate, end_date=TDate)
- # print(tradingDay)
- try:
- Mopen = tradingDay.iloc[0]
- Mclose = tradingDay.iloc[0]
- Mopen = Mopen[0]
- Mclose = Mclose[1]
- if now > Mopen:
- if now < Mclose:
- market_open = True
- else:
- market_open = False
- else:
- market_open = False
- except Exception as exe:
- market_open = False
- # market_open = True # Force True for testing
- return market_open
- if __name__ == '__main__':
- #is_mkt_open('DJIA')
- start_time = time.time()
- main()
- print(time.time() - start_time)
- time_hr = (time.time() - start_time)/3600
- print(time_hr, " hrs")
- class ndict(dict):
- def __getitem__(self, key):
- if key in self: return self.get(key)
- return self.setdefault(key, ndict())
Advertisement
Add Comment
Please, Sign In to add comment