add volatility
This commit is contained in:
parent
ff0306c65c
commit
868b029b55
@ -43,29 +43,41 @@ async def compute_rsi(price_history, time_period=14):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
async def calculate_price_reactions(filtered_data, price_history):
|
async def calculate_price_reactions(ticker, filtered_data, price_history):
|
||||||
# Ensure price_history is sorted by date
|
# Ensure price_history is sorted by date
|
||||||
price_history.sort(key=lambda x: x['time'])
|
price_history.sort(key=lambda x: x['time'])
|
||||||
|
|
||||||
results = []
|
results = []
|
||||||
|
|
||||||
|
with open(f"json/implied-volatility/{ticker}.json",'r') as file:
|
||||||
|
iv_data = ujson.load(file)
|
||||||
|
|
||||||
for item in filtered_data:
|
for item in filtered_data:
|
||||||
report_date = item['date']
|
report_date = item['date']
|
||||||
|
|
||||||
# Find the index of the report date in the price history
|
# Find the index of the report date in the price history
|
||||||
report_index = next((i for i, entry in enumerate(price_history) if entry['time'] == report_date), None)
|
report_index = next((i for i, entry in enumerate(price_history) if entry['time'] == report_date), None)
|
||||||
|
|
||||||
if report_index is None:
|
if report_index is None:
|
||||||
continue # Skip if report date is not found in the price history
|
continue # Skip if report date is not found in the price history
|
||||||
|
|
||||||
# Initialize a dictionary for price reactions
|
# Initialize a dictionary for price reactions
|
||||||
|
iv_value = next((entry['implied_volatility'] for entry in iv_data if entry['date'] == report_date), None)
|
||||||
|
|
||||||
|
#if iv_value is None:
|
||||||
|
# continue # Skip if no matching iv_data is found for the report_date
|
||||||
|
|
||||||
price_reactions = {
|
price_reactions = {
|
||||||
'date': report_date,
|
'date': report_date,
|
||||||
'quarter': item['quarter'],
|
'quarter': item['quarter'],
|
||||||
'year': item['year'],
|
'year': item['year'],
|
||||||
'time': item['time'],
|
'time': item['time'],
|
||||||
'rsi': int(price_history[report_index]['rsi'])
|
'rsi': int(price_history[report_index]['rsi']),
|
||||||
|
'iv': iv_value,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
for offset in [-4,-3,-2,-1,0,1,2,3,4,6]:
|
for offset in [-4,-3,-2,-1,0,1,2,3,4,6]:
|
||||||
target_index = report_index + offset
|
target_index = report_index + offset
|
||||||
|
|
||||||
@ -140,7 +152,7 @@ async def get_past_data(data, ticker, con):
|
|||||||
price_history = orjson.loads(file.read())
|
price_history = orjson.loads(file.read())
|
||||||
|
|
||||||
price_history = await compute_rsi(price_history)
|
price_history = await compute_rsi(price_history)
|
||||||
results = await calculate_price_reactions(filtered_data, price_history)
|
results = await calculate_price_reactions(ticker, filtered_data, price_history)
|
||||||
#print(results[0])
|
#print(results[0])
|
||||||
await save_json(results, ticker, 'json/earnings/past')
|
await save_json(results, ticker, 'json/earnings/past')
|
||||||
|
|
||||||
@ -173,7 +185,7 @@ try:
|
|||||||
cursor.execute("PRAGMA journal_mode = wal")
|
cursor.execute("PRAGMA journal_mode = wal")
|
||||||
cursor.execute("SELECT DISTINCT symbol FROM stocks WHERE symbol NOT LIKE '%.%'")
|
cursor.execute("SELECT DISTINCT symbol FROM stocks WHERE symbol NOT LIKE '%.%'")
|
||||||
stock_symbols = [row[0] for row in cursor.fetchall()]
|
stock_symbols = [row[0] for row in cursor.fetchall()]
|
||||||
#stock_symbols = ['AMD']
|
stock_symbols = ['AMD']
|
||||||
|
|
||||||
asyncio.run(run(stock_symbols, con))
|
asyncio.run(run(stock_symbols, con))
|
||||||
|
|
||||||
|
|||||||
@ -60,6 +60,27 @@ def safe_round(value, decimals=2):
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def add_data(data, historical_data):
|
||||||
|
res_list = []
|
||||||
|
for item in data:
|
||||||
|
date = item['date']
|
||||||
|
for item2 in historical_data:
|
||||||
|
try:
|
||||||
|
if date == item2['date']:
|
||||||
|
item['changesPercentage'] = item2['changesPercentage']
|
||||||
|
item['putCallRatio'] = item2['putCallRatio']
|
||||||
|
item['total_open_interest'] = item2['total_open_interest']
|
||||||
|
item['changesPercentageOI'] = item2.get('changesPercentageOI',None)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if 'changesPercentage' in item:
|
||||||
|
res_list.append(item)
|
||||||
|
|
||||||
|
return res_list
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def prepare_data(data, symbol, directory_path, sort_by = "date"):
|
def prepare_data(data, symbol, directory_path, sort_by = "date"):
|
||||||
res_list = []
|
res_list = []
|
||||||
for item in data:
|
for item in data:
|
||||||
@ -74,10 +95,16 @@ def prepare_data(data, symbol, directory_path, sort_by = "date"):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
if res_list:
|
if res_list:
|
||||||
res_list = sorted(res_list, key=lambda x: x[sort_by], reverse=True)
|
data = sorted(res_list, key=lambda x: x[sort_by], reverse=True)
|
||||||
|
with open(f"json/options-historical-data/companies/{symbol}.json", "r") as file:
|
||||||
|
historical_data = orjson.loads(file.read())
|
||||||
|
|
||||||
|
res_list = add_data(data,historical_data)
|
||||||
|
|
||||||
save_json(res_list, symbol, directory_path)
|
save_json(res_list, symbol, directory_path)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def get_iv_data():
|
def get_iv_data():
|
||||||
print("Starting to download iv data...")
|
print("Starting to download iv data...")
|
||||||
directory_path = "json/implied-volatility"
|
directory_path = "json/implied-volatility"
|
||||||
@ -86,7 +113,7 @@ def get_iv_data():
|
|||||||
total_symbols = stocks_symbols+etf_symbols
|
total_symbols = stocks_symbols+etf_symbols
|
||||||
|
|
||||||
counter = 0
|
counter = 0
|
||||||
|
total_symbols = ['AMZN']
|
||||||
for symbol in tqdm(total_symbols):
|
for symbol in tqdm(total_symbols):
|
||||||
try:
|
try:
|
||||||
url = f"https://api.unusualwhales.com/api/stock/{symbol}/volatility/realized"
|
url = f"https://api.unusualwhales.com/api/stock/{symbol}/volatility/realized"
|
||||||
@ -110,3 +137,4 @@ def get_iv_data():
|
|||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
get_iv_data()
|
get_iv_data()
|
||||||
|
|
||||||
@ -3556,7 +3556,7 @@ async def get_analyst_insight(data:TickerData, api_key: str = Security(get_api_k
|
|||||||
|
|
||||||
|
|
||||||
@app.post("/implied-volatility")
|
@app.post("/implied-volatility")
|
||||||
async def get_clinical_trial(data:TickerData, api_key: str = Security(get_api_key)):
|
async def get_data(data:TickerData, api_key: str = Security(get_api_key)):
|
||||||
ticker = data.ticker.upper()
|
ticker = data.ticker.upper()
|
||||||
cache_key = f"implied-volatility-{ticker}"
|
cache_key = f"implied-volatility-{ticker}"
|
||||||
cached_result = redis_client.get(cache_key)
|
cached_result = redis_client.get(cache_key)
|
||||||
@ -3568,16 +3568,17 @@ async def get_clinical_trial(data:TickerData, api_key: str = Security(get_api_ke
|
|||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(f"json/implied-volatility/companies/{ticker}.json", 'rb') as file:
|
with open(f"json/implied-volatility/{ticker}.json", 'rb') as file:
|
||||||
res = orjson.loads(file.read())
|
res = orjson.loads(file.read())
|
||||||
except:
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
res = []
|
res = []
|
||||||
|
|
||||||
data = orjson.dumps(res)
|
data = orjson.dumps(res)
|
||||||
compressed_data = gzip.compress(data)
|
compressed_data = gzip.compress(data)
|
||||||
|
|
||||||
redis_client.set(cache_key, compressed_data)
|
redis_client.set(cache_key, compressed_data)
|
||||||
redis_client.expire(cache_key, 3600*3600) # Set cache expiration time to 1 day
|
redis_client.expire(cache_key, 60*60) # Set cache expiration time to 1 day
|
||||||
|
|
||||||
return StreamingResponse(
|
return StreamingResponse(
|
||||||
io.BytesIO(compressed_data),
|
io.BytesIO(compressed_data),
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user