Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/be daily currency stock update #442

Merged
merged 6 commits into from
Dec 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ services:
sh -c 'python3 manage.py makemigrations &&
python3 manage.py migrate --noinput &&
python3 manage.py collectstatic --noinput &&
python3 manage.py update_currencies &&
python3 manage.py update_stocks &&
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice!

gunicorn backend.wsgi:application --bind 0.0.0.0:8000'
restart: always
environment:
Expand Down
Empty file.
Empty file.
36 changes: 36 additions & 0 deletions backend/marketfeed/management/commands/update_currencies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import json
from django.core.management.base import BaseCommand
from marketfeed.models import Currency
from django.conf import settings
import os

class Command(BaseCommand):
help = 'Update or Insert the supported currencies to db'

def handle(self, *args, **kwargs):
# Define the file path (assuming it's inside a 'currency_data' folder)
file_path = os.path.join(settings.BASE_DIR,'marketfeed', 'management', 'currencies.json')

# Check if the file exists
if not os.path.exists(file_path):
self.stdout.write(self.style.ERROR(f'Currency data file not found: {file_path}'))
return

with open(file_path, 'r') as file:
currencies_data = json.load(file)

for currency_data in currencies_data:
code = currency_data.get('code')
name = currency_data.get('name')

# Get or create the currency
currency, created = Currency.objects.get_or_create(
code=code,
defaults={'name': name}
)

# Output the result
if created:
self.stdout.write(self.style.SUCCESS(f'Inserted {currency.code} into the database.'))
else:
self.stdout.write(self.style.SUCCESS(f'{currency.code} already exists in the database.'))
38 changes: 38 additions & 0 deletions backend/marketfeed/management/commands/update_stocks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import json
from django.core.management.base import BaseCommand
from marketfeed.models import Stock, Currency
from django.conf import settings
import requests
import re

# Search whether the stock name has FON, FONU or BYF in it to pass those: they are not stocks
def notStock(stockName):
return bool(re.search(r'\b(FON|FONU|BYF)\b', stockName, re.IGNORECASE))

class Command(BaseCommand):
help = 'Update or Insert the Turkish stock market stocks to db'


def handle(self, *args, **kwargs):
# Url to fetch stock list
url = 'https://bigpara.hurriyet.com.tr/api/v1/hisse/list'
try:
response = requests.get(url)
response.raise_for_status()
stocks = response.json().get('data', [])
currency = Currency.objects.get(code='TRY')
for stock in stocks:
try:
if notStock(stock['ad']):
continue
Stock.objects.update_or_create(
symbol=stock['kod'],
defaults={
'name': stock['ad'],
'currency': currency,
}
)
except Exception as e:
print(e)
except Exception as e:
print(e)
5 changes: 5 additions & 0 deletions backend/marketfeed/management/currencies.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[
{"code": "TRY", "name": "Turkish Lira"},
{"code": "USD", "name": "US Dollar"}
]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's discuss other currencies, so stocks, in the future


16 changes: 16 additions & 0 deletions backend/marketfeed/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@ def __init__(self, *args, **kwargs):
self.fields['name'].required = False
self.fields['symbol'].required = False

class StockCreateSerializer(serializers.ModelSerializer):
currency = serializers.PrimaryKeyRelatedField(queryset=Currency.objects.all())

class Meta:
model = Stock
fields = ['id', 'name', 'symbol', 'currency']

def __init__(self, *args, **kwargs):
super(StockCreateSerializer, self).__init__(*args, **kwargs)

# Get the request method if available
request = self.context.get('request', None)

if request and request.method == 'POST':
self.fields['currency'].required = True




Expand Down
2 changes: 2 additions & 0 deletions backend/marketfeed/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ def retrieve(self, request, pk=None):
return Response(serializer.data)

def create(self, request):
if request.method == 'POST':
self.serializer_class = StockCreateSerializer
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
Expand Down
3 changes: 2 additions & 1 deletion backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@ drf-spectacular==0.27.2
django-cors-headers==4.5.0
Pillow
feedparser
beautifulsoup4
yfinance
requests
beautifulsoup4