add financial score

This commit is contained in:
MuslemRahimi 2024-09-15 20:17:00 +02:00
parent 6434fb3901
commit 42d8dba973
4 changed files with 101 additions and 2 deletions

View File

@ -0,0 +1,64 @@
from datetime import datetime, timedelta
import ujson
import time
import sqlite3
import asyncio
import aiohttp
import random
from tqdm import tqdm
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv('FMP_API_KEY')
async def save_json(symbol, data):
with open(f"json/financial-score/{symbol}.json", 'w') as file:
ujson.dump(data, file)
async def get_data(session, symbol):
# Construct the API URL
url = f"https://financialmodelingprep.com/api/v4/score?symbol={symbol}&apikey={api_key}"
try:
async with session.get(url) as response:
if response.status == 200:
data = await response.json()
if len(data) > 0:
filtered_data = [
{
k: round(v, 2) if k == 'altmanZScore' else v
for k, v in item.items()
if k in ['altmanZScore', 'piotroskiScore', 'workingCapital', 'totalAssets']
}
for item in data
]
await save_json(symbol, filtered_data[0])
except:
pass
async def run():
con = sqlite3.connect('stocks.db')
cursor = con.cursor()
cursor.execute("PRAGMA journal_mode = wal")
cursor.execute("SELECT DISTINCT symbol FROM stocks WHERE symbol NOT LIKE '%.%'")
symbols = [row[0] for row in cursor.fetchall()]
con.close()
async with aiohttp.ClientSession() as session:
tasks = []
for i, symbol in enumerate(tqdm(symbols), 1):
tasks.append(get_data(session, symbol))
if i % 100 == 0:
await asyncio.gather(*tasks)
tasks = []
print(f'sleeping mode: {i}')
await asyncio.sleep(60) # Pause for 60 seconds
if tasks:
await asyncio.gather(*tasks)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(run())

View File

@ -421,8 +421,19 @@ data = {
'text': 'FCF margin is the percentage of revenue left as free cash flow. FCF is calculated by subtracting capital expenditures (CapEx) from the operating cash flow (OCF). Both CapEx and OCF are shown on the cash flow statement.', 'text': 'FCF margin is the percentage of revenue left as free cash flow. FCF is calculated by subtracting capital expenditures (CapEx) from the operating cash flow (OCF). Both CapEx and OCF are shown on the cash flow statement.',
'equation': 'FCF Margin = (Free Cash Flow / Revenue) * 100%' 'equation': 'FCF Margin = (Free Cash Flow / Revenue) * 100%'
}, },
'altmanZScore': {
'text': 'The Altman Z-Score is a number based on a formula that can be used to predict the likelihood that a company will go into bankruptcy within two years.',
},
'piotroskiScore': {
'text': 'The Piotroski F-Score is a score between 0 and 9 that determine the strength of a company`s financial position. The higher, the better.',
},
'totalAssets': {
'text': 'Total assets is the sum of all current and non-current assets on the balance sheet. Assets are everything that the company owns.',
},
'workingCapital': {
'text': 'Working capital is the amount of money available to a business to conduct its day-to-day operations. It is calculated by subtracting total current liabilities from total current assets.',
'equation': 'Working Capital = Current Assets - Current Liabilities'
},

View File

@ -521,6 +521,15 @@ def run_financial_statements():
] ]
run_command(command) run_command(command)
def run_financial_score():
run_command(["python3", "cron_financial_score.py"])
command = [
"sudo", "rsync", "-avz", "-e", "ssh",
"/root/backend/app/json/financial-score",
f"root@{useast_ip_address}:/root/backend/app/json"
]
run_command(command)
def run_market_cap(): def run_market_cap():
run_command(["python3", "cron_market_cap.py"]) run_command(["python3", "cron_market_cap.py"])
command = [ command = [
@ -599,6 +608,7 @@ schedule.every().day.at("14:00").do(run_threaded, run_cron_sector).tag('sector_j
schedule.every().day.at("15:45").do(run_threaded, run_restart_cache) schedule.every().day.at("15:45").do(run_threaded, run_restart_cache)
schedule.every(2).days.at("01:00").do(run_threaded, run_market_maker).tag('markt_maker_job') schedule.every(2).days.at("01:00").do(run_threaded, run_market_maker).tag('markt_maker_job')
schedule.every(2).days.at("08:30").do(run_threaded, run_financial_score).tag('financial_score_job')
schedule.every().saturday.at("05:00").do(run_threaded, run_ownership_stats).tag('ownership_stats_job') schedule.every().saturday.at("05:00").do(run_threaded, run_ownership_stats).tag('ownership_stats_job')

View File

@ -561,6 +561,20 @@ async def get_stock_screener(con):
except: except:
item['forwardPE'] = None item['forwardPE'] = None
try:
with open(f"json/financial-score/{symbol}.json", 'r') as file:
res = orjson.loads(file.read())
item['altmanZScore'] = res['altmanZScore']
item['piotroskiScore'] = res['piotroskiScore']
item['workingCapital'] = res['workingCapital']
item['totalAssets'] = res['totalAssets']
except:
item['altmanZScore'] = None
item['piotroskiScore'] = None
item['workingCapital'] = None
item['totalAssets'] = None
try: try:
with open(f"json/dividends/companies/{symbol}.json", 'r') as file: with open(f"json/dividends/companies/{symbol}.json", 'r') as file:
res = orjson.loads(file.read()) res = orjson.loads(file.read())