Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
60
13.7k
id
stringlengths
19
48
metadata
dict
__index_level_0__
int64
0
2
import csv from datetime import datetime, timezone as dt_timezone from django.core.management.base import BaseCommand from django.db import transaction from api.models import Item import time class Command(BaseCommand): help = 'Efficiently load items from a large CSV file in batches.' def add_arguments(self, parser): parser.add_argument('csv_file', type=str, help='Path to the CSV file') parser.add_argument('--batch-size', type=int, default=int(1e7), help='Number of rows to insert per batch (default: 1e7)') def handle(self, *args, **options): csv_file = options['csv_file'] batch_size = options['batch_size'] start_time = time.time() def parse_csv(): with open(csv_file, 'r', newline='') as f: reader = csv.reader(f) header = next(reader) expected_columns = ['Timestamp', 'Symbol', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6'] if header != expected_columns: raise ValueError(f"CSV header mismatch. Expected: {expected_columns}") for row_num, row in enumerate(reader, start=2): try: timestamp = datetime.fromisoformat(row[0].replace('Z', '+00:00')) yield Item( time=timestamp, symbol=row[1], c1=float(row[2]), c2=float(row[3]), c3=float(row[4]), c4=float(row[5]), c5=float(row[6]), c6=float(row[7]), ) except Exception as e: self.stderr.write(f"Skipping row {row_num} due to error: {e}") total_inserted = 0 batch = [] for item in parse_csv(): batch.append(item) if len(batch) >= batch_size: elapsed = time.time() - start_time with transaction.atomic(): Item.objects.bulk_create(batch, batch_size=batch_size) total_inserted += len(batch) self.stdout.write(f"Inserted {total_inserted} items... Time taken: {elapsed / 60:.2f} minutes") batch.clear() # Insert any remaining items if batch: with transaction.atomic(): Item.objects.bulk_create(batch, batch_size=batch_size) total_inserted += len(batch) elapsed = time.time() - start_time self.stdout.write(self.style.SUCCESS(f"Finished. Total inserted: {total_inserted} items.")) self.stdout.write(self.style.SUCCESS(f"Time taken: {elapsed / 60:.2f} minutes"))
backend/api/management/commands/load_csv.py/0
{ "file_path": "backend/api/management/commands/load_csv.py", "repo_id": "backend", "token_count": 1424 }
0
{ "proxy": "http://localhost:8000", "name": "frontend", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/dom": "^10.4.0", "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.3.0", "@testing-library/user-event": "^13.5.0", "axios": "^1.9.0", "highcharts": "^12.2.0", "highcharts-accessibility": "^0.1.7", "highcharts-react-official": "^3.2.2", "react": "^19.1.0", "react-dom": "^19.1.0", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
frontend/package.json/0
{ "file_path": "frontend/package.json", "repo_id": "frontend", "token_count": 500 }
1
// jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom';
frontend/src/setupTests.js/0
{ "file_path": "frontend/src/setupTests.js", "repo_id": "frontend", "token_count": 75 }
2
import random from datetime import datetime, timedelta from django.core.management.base import BaseCommand from django.db import transaction from django.utils import timezone from datetime import timezone as dt_timezone from api.models import Item class Command(BaseCommand): help = "Populate Item table with stock data for a fixed symbol at equal time intervals" def handle(self, *args, **options): # Define inputs here directly num_rows = 100000000 start_str = "2005-05-17 09:00:00" symbol = ["RA","RB","RC","RD","RE","RF","RG","RH"] n=len(symbol) naive_start = datetime.strptime(start_str, "%Y-%m-%d %H:%M:%S") start_time = timezone.make_aware(naive_start, timezone=dt_timezone.utc) self.stdout.write( f"Populating {num_rows} rows for symbol '{symbol}' starting from {start_time}" ) interval_seconds = 1 items_to_create = [] batch_size = 1000000 # large batch size, adjust if needed count=0 for i in range(num_rows): current_time = start_time + timedelta(seconds=i * interval_seconds) price = round(random.uniform(10000000, 500000000), 2) volume = random.randint(10000, 1000000) for s in symbol: item = Item( symbol=s, time=current_time, price=price, volume=volume, ) items_to_create.append(item) if len(items_to_create) >= batch_size: with transaction.atomic(): Item.objects.bulk_create(items_to_create) print(f"Inserted batch: {count}") count+=1 items_to_create = [] # Insert remaining items if items_to_create: with transaction.atomic(): Item.objects.bulk_create(items_to_create) print("Inserted final batch") self.stdout.write(self.style.SUCCESS(f"Successfully populated {num_rows} rows")) # Generate the script to populate the database having CSV rows Timestamp(in milliseconds),Symbol,C1,C2,C3,C4,C5,C6(floats)
backend/api/management/commands/load_stocks.py/0
{ "file_path": "backend/api/management/commands/load_stocks.py", "repo_id": "backend", "token_count": 1007 }
0
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>React App</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body> </html>
frontend/public/index.html/0
{ "file_path": "frontend/public/index.html", "repo_id": "frontend", "token_count": 623 }
1
from django.db import models class Item(models.Model): time = models.DateTimeField() symbol = models.CharField(max_length=100) c1 = models.FloatField() c2 = models.FloatField() c3 = models.FloatField() c4 = models.FloatField() c5 = models.FloatField() c6 = models.FloatField() def __str__(self): return f"{self.time},symbol: {self.symbol},id: {self.id}" class Meta: indexes = [ models.Index(fields=['symbol', 'time']), ] class ItemAggregate(models.Model): AGG_CHOICES = [ ('minute', 'Minute'), ('hour', 'Hour'), ('month', 'Month'), ] symbol = models.CharField(max_length=100) time_group = models.DateTimeField() aggregation_level = models.CharField(max_length=10, choices=AGG_CHOICES) avg_price = models.FloatField() total_volume = models.BigIntegerField() class Meta: indexes = [ models.Index(fields=['symbol', 'aggregation_level', 'time_group']), ] unique_together = ('symbol', 'aggregation_level', 'time_group')
backend/api/models.py/0
{ "file_path": "backend/api/models.py", "repo_id": "backend", "token_count": 461 }
0
from rest_framework import serializers from .models import * class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__'
backend/api/serializers.py/0
{ "file_path": "backend/api/serializers.py", "repo_id": "backend", "token_count": 61 }
0
from django.test import TestCase # Create your tests here.
backend/api/tests.py/0
{ "file_path": "backend/api/tests.py", "repo_id": "backend", "token_count": 17 }
0
{ "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" }
frontend/public/manifest.json/0
{ "file_path": "frontend/public/manifest.json", "repo_id": "frontend", "token_count": 251 }
1
from rest_framework import routers from .views import * from django.urls import path, include urlpatterns = [ path('items/', ItemListView.as_view(), name='item-list'), path('items/add/', AddItemView.as_view(), name='add-item'), path('items/<int:id>/edit/', EditItemView.as_view(), name='edit-item'), path('items/<int:id>/', get_item, name='get-item'), path('items/e/', get_items_equidistant, name='get_items_equidistant'), ]
backend/api/urls.py/0
{ "file_path": "backend/api/urls.py", "repo_id": "backend", "token_count": 165 }
0
from rest_framework import viewsets from .models import * from .serializers import * from rest_framework.generics import * from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import api_view, parser_classes from rest_framework.views import APIView from datetime import datetime from rest_framework.viewsets import ViewSet from rest_framework.parsers import MultiPartParser, FormParser from django.utils.dateparse import parse_datetime from django.db.models import Min, Max from rest_framework import status import time from datetime import timedelta from datetime import timedelta, datetime as dt_class import csv import io from django.utils.timezone import make_aware, is_aware from django.db.models.functions import TruncMinute, TruncHour, TruncMonth import math class ItemListView(ListAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer class AddItemView(CreateAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer class EditItemView(UpdateAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer lookup_field = 'id' @api_view(['GET']) def get_item(request, id): try: item = Item.objects.get(id=id) serializer = ItemSerializer(item) return Response(serializer.data, status=status.HTTP_200_OK) except Item.DoesNotExist: return Response( {'error': 'Item not found'}, status=status.HTTP_404_NOT_FOUND ) def round_to_nearest_multiple(timestamp_float, multiple_seconds): if multiple_seconds == 0: return timestamp_float return math.floor(timestamp_float / multiple_seconds + 0.5) * multiple_seconds @api_view(['GET']) def get_items_equidistant(request): start_time_measurement = time.time() symbol = request.query_params.get('symbol') start_date_str = request.query_params.get('start_date') end_date_str = request.query_params.get('end_date') time_gap_str = request.query_params.get('time_gap') N_str = request.query_params.get('N') required_params = { 'symbol': symbol, 'start_date': start_date_str, 'end_date': end_date_str, 'time_gap': time_gap_str, 'N': N_str } missing_params = [name for name, val in required_params.items() if val is None] if missing_params: return Response( {'error': f'Missing parameters: {", ".join(missing_params)}'}, status=status.HTTP_400_BAD_REQUEST ) try: time_gap_seconds = float(time_gap_str) if time_gap_seconds <= 0: raise ValueError("time_gap must be positive") except ValueError: return Response( {'error': '"time_gap" must be a positive number representing seconds (e.g., 60, 0.5 for 500ms, or 0.001 for 1ms).'}, status=status.HTTP_400_BAD_REQUEST ) try: N = int(N_str) if N <= 0: raise ValueError("N must be positive") except ValueError: return Response( {'error': '"N" must be a positive integer.'}, status=status.HTTP_400_BAD_REQUEST ) start_date = parse_datetime(start_date_str) if not start_date: return Response( {'error': 'Invalid start_date format. Use ISO format (e.g., 2024-01-01T12:00:00.000Z).'}, status=status.HTTP_400_BAD_REQUEST ) if not is_aware(start_date): start_date = make_aware(start_date) end_date = parse_datetime(end_date_str) if not end_date: return Response( {'error': 'Invalid end_date format. Use ISO format (e.g., 2024-01-01T12:00:00.000Z).'}, status=status.HTTP_400_BAD_REQUEST ) if not is_aware(end_date): end_date = make_aware(end_date) if start_date >= end_date: return Response( {'error': 'start_date must be strictly before end_date.'}, status=status.HTTP_400_BAD_REQUEST ) first_item = Item.objects.filter(symbol=symbol).order_by('time').first() last_item = Item.objects.filter(symbol=symbol).order_by('-time').first() if not first_item or not last_item: return Response( {'error': f'No data found for symbol "{symbol}".'}, status=status.HTTP_404_NOT_FOUND ) first_time = first_item.time last_time = last_item.time clamped_start_date = max(start_date, first_time) clamped_end_date = min(end_date, last_time) if clamped_start_date > clamped_end_date: return Response({ 'error': 'After clamping to available data range, start_date > end_date.', 'details': { 'requested_start_date': start_date.isoformat(), 'requested_end_date': end_date.isoformat(), 'clamped_start_date': clamped_start_date.isoformat(), 'clamped_end_date': clamped_end_date.isoformat(), 'available_start_date': first_time.isoformat(), 'available_end_date': last_time.isoformat() } }, status=status.HTTP_400_BAD_REQUEST) start_timestamp = clamped_start_date.timestamp() aligned_start_timestamp = round_to_nearest_multiple(start_timestamp, time_gap_seconds) aligned_start_dt = dt_class.fromtimestamp(aligned_start_timestamp, tz=start_date.tzinfo) end_timestamp = clamped_end_date.timestamp() aligned_end_timestamp = round_to_nearest_multiple(end_timestamp, time_gap_seconds) aligned_end_dt = dt_class.fromtimestamp(aligned_end_timestamp, tz=end_date.tzinfo) if aligned_start_dt > aligned_end_dt: return Response({ 'error': 'Adjusted start date is after adjusted end date due to rounding. Cannot generate points from this range.', 'details': { 'original_start_date': start_date.isoformat(), 'original_end_date': end_date.isoformat(), 'aligned_start_date': aligned_start_dt.isoformat(), 'aligned_end_date': aligned_end_dt.isoformat(), 'time_gap_seconds': time_gap_seconds } }, status=status.HTTP_400_BAD_REQUEST) times_to_query = [] if N == 1: times_to_query.append(aligned_start_dt) else: if aligned_start_dt == aligned_end_dt: times_to_query = [aligned_start_dt] else: total_duration_seconds = (aligned_end_dt - aligned_start_dt).total_seconds() if total_duration_seconds < 0: return Response({ 'error': 'Internal calculation error: total duration for points is negative.', }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) num_intervals = (total_duration_seconds / time_gap_seconds) print("num_intervals", num_intervals) N = min(N, math.floor(num_intervals) + 1) interval_seconds = math.floor(num_intervals / (N - 1)) print("difference: ", interval_seconds * time_gap_seconds) for i in range(N): offset_seconds = i * interval_seconds * time_gap_seconds current_time_point = aligned_start_dt + timedelta(seconds=offset_seconds) if current_time_point > aligned_end_dt: break times_to_query.append(current_time_point) try: items = Item.objects.filter(symbol=symbol, time__in=times_to_query) serializer = ItemSerializer(items, many=True) duration_measurement = time.time() - start_time_measurement stats = { "count": len(serializer.data), "performance": { "duration_seconds": round(duration_measurement, 4) }, "query_details": { "symbol": symbol, "requested_start_date": start_date_str, "requested_end_date": end_date_str, "time_gap_alignment_seconds": time_gap_seconds, "N_points_requested": N, "aligned_start_datetime": aligned_start_dt.isoformat(), "aligned_end_datetime": aligned_end_dt.isoformat(), "num_timestamps_generated": len(times_to_query), }, } print(stats) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: print(str(e)) return Response( {'error': 'An unexpected error occurred during data retrieval.', 'details': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR )
backend/api/views.py/0
{ "file_path": "backend/api/views.py", "repo_id": "backend", "token_count": 3763 }
0
.App { text-align: center; } .App-logo { height: 40vmin; pointer-events: none; } @media (prefers-reduced-motion: no-preference) { .App-logo { animation: App-logo-spin infinite 20s linear; } } .App-header { background-color: #282c34; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; } .App-link { color: #61dafb; } @keyframes App-logo-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
frontend/src/App.css/0
{ "file_path": "frontend/src/App.css", "repo_id": "frontend", "token_count": 240 }
1
// src/App.js import React from 'react'; import TradingChart from './components/TradingChart'; function App() { return ( <div className="App"> <h1>Trading Dashboard</h1> <TradingChart /> </div> ); } export default App;
frontend/src/App.js/0
{ "file_path": "frontend/src/App.js", "repo_id": "frontend", "token_count": 96 }
0
""" ASGI config for lsg project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lsg.settings') application = get_asgi_application()
backend/lsg/asgi.py/0
{ "file_path": "backend/lsg/asgi.py", "repo_id": "backend", "token_count": 131 }
0
import { render, screen } from '@testing-library/react'; import App from './App'; test('renders learn react link', () => { render(<App />); const linkElement = screen.getByText(/learn react/i); expect(linkElement).toBeInTheDocument(); });
frontend/src/App.test.js/0
{ "file_path": "frontend/src/App.test.js", "repo_id": "frontend", "token_count": 78 }
1
""" Django settings for lsg project. Generated by 'django-admin startproject' using Django 5.2.1. For more information on this file, see https://docs.djangoproject.com/en/5.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-%003))6u_zp+ysytzj_wgh5=1m!#e+-w45^32+d-vl3y6n45o(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'lsg.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] WSGI_APPLICATION = 'lsg.wsgi.application' # Database # https://docs.djangoproject.com/en/5.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.postgresql', # 'NAME': 'django_db', # e.g. 'postgres' or your custom db # 'USER': 'postgres', # 'PASSWORD': '1234', # 'HOST': 'localhost', # 'PORT': '5432', # } # } # Password validation # https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/5.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.2/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
backend/lsg/settings.py/0
{ "file_path": "backend/lsg/settings.py", "repo_id": "backend", "token_count": 1545 }
0
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), ]
backend/lsg/urls.py/0
{ "file_path": "backend/lsg/urls.py", "repo_id": "backend", "token_count": 62 }
0
import React, { useEffect, useState, useRef, useCallback } from 'react'; import Highcharts from 'highcharts/highstock'; import HighchartsReact from 'highcharts-react-official'; const SYMBOLS = ['AAPL', 'NFLX', 'GOOG', 'AMZN', 'TSLA']; const DEFAULT_VISIBLE_COLUMNS = { c1: true, c2: true, c3: true, c4: true, c5: true, c6: true }; const DEFAULT_TIMEFRAME = '1min'; const DEFAULT_YSCALE = 'linear'; const oneDay = 24 * 3600 * 1000; function parseTimeGapToSeconds(timeStr) { const match = /^([\d.]+)\s*(ms|s|min|h|d)?$/.exec(timeStr.trim()); if (!match) return NaN; const value = parseFloat(match[1]); const unit = match[2] || 's'; switch (unit) { case 'ms': return value / 1000; case 's': return value; case 'min': return value * 60; case 'h': return value * 3600; case 'd': return value * oneDay; default: return value; } } const generateDayBands = (min, max) => { const bands = []; let start = Math.floor(min / oneDay) * oneDay; while (start < max) { const end = start + oneDay; bands.push({ from: start, to: end, color: start % (oneDay * 2) === 0 ? 'rgba(200, 200, 200, 0.1)' : 'rgba(150, 150, 150, 0.05)' }); start = end; } return bands; }; const generateDaySeparators = (min, max) => { const lines = []; let time = Math.floor(min / oneDay) * oneDay; while (time <= max) { lines.push({ value: time, color: '#888', width: 1, dashStyle: 'ShortDash', zIndex: 5 }); time += oneDay; } return lines; }; const timeframeMinMs = { '1ms': 1, '10ms': 10, '100ms': 100, '1s': 1000, '1min': 60000, '5min': 300000, '1h': 3600000, '1d': oneDay }; const COLORS = [ '#007bff', '#28a745', '#ffc107', '#dc3545', '#6f42c1', '#17a2b8' ]; const COLUMN_KEYS = ['c1', 'c2', 'c3', 'c4', 'c5', 'c6']; const TradingChart = () => { const chartRef = useRef(null); const chartContainerRef = useRef(null); const [symbol, setSymbol] = useState('AMZN'); const [seriesData, setSeriesData] = useState([]); const [rawSeries, setRawSeries] = useState([]); const [timeframe, setTimeframe] = useState('1min'); const [yScale, setYScale] = useState('linear'); const [visibleRange, setVisibleRange] = useState({ min: null, max: null }); const [loadedRange, setLoadedRange] = useState({ min: null, max: null }); const [isLoading, setIsLoading] = useState(false); const [visibleColumns, setVisibleColumns] = useState({ c1: true, c2: true, c3: true, c4: true, c5: true, c6: true }); const fetchData = useCallback(async (min, max) => { setIsLoading(true); try { const starttime = performance.now(); const d = max - min; const startISO = new Date(min - d).toISOString(); const endISO = new Date(max + d).toISOString(); const resp = await fetch( `/api/items/e/?symbol=${symbol}&time_gap=${parseTimeGapToSeconds(timeframe)}&start_date=${startISO}&end_date=${endISO}&N=500` ); if (!resp.ok) throw new Error(`HTTP ${resp.status}`); const data = await resp.json(); const c1 = [], c2 = [], c3 = [], c4 = [], c5 = [], c6 = []; data.forEach(item => { const t = new Date(item.time).getTime(); c1.push([t, Number(item.c1)]); c2.push([t, Number(item.c2)]); c3.push([t, Number(item.c3)]); c4.push([t, Number(item.c4)]); c5.push([t, Number(item.c5)]); c6.push([t, Number(item.c6)]); }); const raw = [ { name: 'c1', data: c1, type: 'line', color: COLORS[0] }, { name: 'c2', data: c2, type: 'line', color: COLORS[1] }, { name: 'c3', data: c3, type: 'line', color: COLORS[2] }, { name: 'c4', data: c4, type: 'line', color: COLORS[3] }, { name: 'c5', data: c5, type: 'line', color: COLORS[4] }, { name: 'c6', data: c6, type: 'line', color: COLORS[5] } ]; setRawSeries(raw); setSeriesData( raw.map((s, i) => ({ ...s, visible: visibleColumns[s.name], boostThreshold: 1 })) ); setLoadedRange({ min: min - d, max: max + d }); } catch (err) { console.error('Fetch error:', err); } finally { setIsLoading(false); } }, [timeframe, symbol, visibleColumns]); useEffect(() => { setSeriesData( rawSeries.map(s => ({ ...s, visible: visibleColumns[s.name], boostThreshold: 1 })) ); }, [visibleColumns, symbol, rawSeries]); const handleAfterSetExtremes = e => { const { min, max, trigger } = e; if (isLoading || trigger === 'init') return; setVisibleRange({ min: min, max: max }); const span = max - min; const nowspan = loadedRange.max - loadedRange.min; if (trigger !== 'zoomout' && span <= nowspan * 0.3) { const unit = timeframeMinMs[timeframe]; const alignedMin = Math.floor(min / unit) * unit; const alignedMax = Math.ceil(max / unit) * unit; fetchData(alignedMin, alignedMax); return; } if (trigger == "pan") { const diff = Math.floor((loadedRange.max - loadedRange.min) / 5); if ((max >= loadedRange.max - diff) || (min <= loadedRange.min + diff)) { const unit = timeframeMinMs[timeframe]; const alignedMin = Math.floor(min / unit) * unit; const alignedMax = Math.ceil(max / unit) * unit; fetchData(alignedMin, alignedMax); } return; } if (trigger == 'zoomout') { const diff = Math.floor((loadedRange.max - loadedRange.min) / 5); if ((max >= loadedRange.max - diff) || (min <= loadedRange.min + diff)) { const unit = timeframeMinMs[timeframe]; const alignedMin = Math.floor(min / unit) * unit; const alignedMax = Math.ceil(max / unit) * unit; fetchData(alignedMin, alignedMax); return; } return; } if (trigger == undefined) { return; } if (loadedRange.min != null && loadedRange.max != null) { if (min >= loadedRange.min && max <= loadedRange.max) { return; } const newMin = Math.min(min, loadedRange.min); const newMax = Math.max(max, loadedRange.max); const unit = timeframeMinMs[timeframe]; fetchData(newMin, newMax); } else { fetchData(min, max); } }; function instantZoomOut(chart, factor = 1.2) { if (!chart || !chart.xAxis || !chart.xAxis[0]) return; const min0 = chart.xAxis[0].min; const max0 = chart.xAxis[0].max; if (min0 == null || max0 == null) return; const center = Math.floor((min0 + max0) / 2); const range0 = max0 - min0; const range1 = range0 * factor; const newMin = center - Math.ceil(range1 / 2); const newMax = center + Math.ceil(range1 / 2); chart.xAxis[0].setExtremes( newMin, newMax, true, true, { trigger: 'zoomout' } ); } const handleZoomOut = () => { const chart = chartRef.current?.chart; instantZoomOut(chart); }; useEffect(() => { const container = chartContainerRef.current; if (!container) return; const onWheel = (e) => { if (e.ctrlKey || e.metaKey) return; if (e.deltaY > 0) { handleZoomOut(); e.preventDefault(); } }; container.addEventListener('wheel', onWheel, { passive: false }); return () => container.removeEventListener('wheel', onWheel); }, [handleZoomOut]); const toggleFullScreen = () => { const el = chartContainerRef.current; if (!document.fullscreenElement) { el.requestFullscreen().catch(console.error); } else { document.exitFullscreen(); } }; useEffect(() => { const now = Date.now(); const initialMin = now - 60 * 60 * 1000 * 10000; const initialMax = now; setVisibleRange({ min: initialMin, max: initialMax }); fetchData(initialMin, initialMax); }, []); useEffect(() => { setLoadedRange({ min: null, max: null }); setSeriesData([]); setRawSeries([]); setTimeframe(DEFAULT_TIMEFRAME); setYScale(DEFAULT_YSCALE); setVisibleColumns(DEFAULT_VISIBLE_COLUMNS); const now = Date.now(); const initialMin = now - 60 * 60 * 1000 * 10000; const initialMax = now; setVisibleRange({ min: initialMin, max: initialMax }); fetchData(initialMin, initialMax); }, [symbol]); useEffect(() => { const handleKeyDown = (e) => { const chart = chartRef.current?.chart; if (!chart) return; const visibleSpan = chart.xAxis[0].max - chart.xAxis[0].min; const panAmount = visibleSpan * 0.05; if (e.key === 'ArrowLeft') { const newMin = Math.max( chart.xAxis[0].min - panAmount, -8640000000000000 ); const newMax = Math.max( chart.xAxis[0].max - panAmount, newMin + 1000 ); chart.xAxis[0].setExtremes( newMin, newMax, true, false, { trigger: 'pan' } ); } else if (e.key === 'ArrowRight') { const newMax = Math.min( chart.xAxis[0].max + panAmount, 8640000000000000 ); const newMin = Math.min( chart.xAxis[0].min + panAmount, newMax - 1000 ); chart.xAxis[0].setExtremes( newMin, newMax, true, false, { trigger: 'pan' } ); } }; window.addEventListener('keydown', handleKeyDown); return () => window.removeEventListener('keydown', handleKeyDown); }, []); const chartOptions = { chart: { zoomType: 'x', panning: true, panKey: 'shift', animation: false }, title: { text: `Trading Chart (${timeframe})` }, xAxis: { type: 'datetime', ordinal: false, minRange: timeframeMinMs[timeframe], events: { afterSetExtremes: handleAfterSetExtremes }, plotBands: visibleRange.min != null ? generateDayBands(visibleRange.min, visibleRange.max) : [], plotLines: visibleRange.min != null ? generateDaySeparators(visibleRange.min, visibleRange.max) : [] }, yAxis: { type: yScale, title: { text: 'Price' } }, tooltip: { shared: true, xDateFormat: '%Y-%m-%d %H:%M:%S' }, dataGrouping: { enabled: false }, series: seriesData, boost: { useGPUTranslations: true, seriesThreshold: 1 }, plotOptions: { line: { marker: { enabled: false } } }, navigator: { enabled: true }, scrollbar: { enabled: true }, credits: { enabled: false }, navigation: { stockTools: { gui: { enabled: true, buttons: [ 'fullScreen', 'indicators', 'separator', 'crookedLines', 'measure', 'typeChange', 'zoomChange', 'annotations', 'verticalLabels', 'flags', 'fibonacci', 'toggleAnnotations' ] } } } }; return ( <div ref={chartContainerRef} style={{ height: '100vh', display: 'flex', flexDirection: 'column', backgroundColor: '#fff' }}> <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '12px', backgroundColor: '#f8f9fa' }}> {['1ms','10ms','100ms','1s', '1min', '5min', '1h', '1d'].map(tf => ( <button key={tf} onClick={() => setTimeframe(tf)} style={{ background: timeframe === tf ? '#007bff' : '#e2e6ea', color: timeframe === tf ? '#fff' : '#000', border: '1px solid #ced4da', padding: '6px 12px', borderRadius: '4px', cursor: 'pointer' }}>{tf}</button> ))} <select value={yScale} onChange={e => setYScale(e.target.value)} style={{ padding: '6px', borderRadius: '4px' }}> <option value="linear">Y-Scale: Linear</option> <option value="logarithmic">Y-Scale: Logarithmic</option> </select> <div style={{ marginLeft: 16, display: 'flex', alignItems: 'center', gap: '8px' }}> {COLUMN_KEYS.map((col, idx) => ( <label key={col} style={{ marginRight: 8, display: 'flex', alignItems: 'center', fontWeight: 500 }}> <input type="checkbox" checked={visibleColumns[col]} onChange={() => setVisibleColumns(v => ({ ...v, [col]: !v[col] })) } style={{ marginRight: 4 }} /> <span style={{ color: COLORS[idx] }}>{col}</span> </label> ))} </div> <select value={symbol} onChange={e => setSymbol(e.target.value)}> {SYMBOLS.map(sym => ( <option value={sym} key={sym}>{sym}</option> ))} </select> <div style={{ flexGrow: 1 }} /> <button onClick={handleZoomOut} style={{ padding: '6px 12px', borderRadius: '4px', border: '1px solid #ced4da', cursor: 'pointer', background: '#ffc107', color: '#000' }}>Zoom Out</button> <button onClick={toggleFullScreen} style={{ padding: '6px 12px', borderRadius: '4px', border: '1px solid #ced4da', cursor: 'pointer', background: '#6c757d', color: '#fff' }}>Fullscreen</button> </div> <HighchartsReact highcharts={Highcharts} constructorType="stockChart" options={chartOptions} ref={chartRef} containerProps={{ style: { flexGrow: 1 } }} /> </div> ); }; export default TradingChart;
frontend/src/components/TradingChart.js/0
{ "file_path": "frontend/src/components/TradingChart.js", "repo_id": "frontend", "token_count": 6231 }
1
""" WSGI config for lsg project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lsg.settings') application = get_wsgi_application()
backend/lsg/wsgi.py/0
{ "file_path": "backend/lsg/wsgi.py", "repo_id": "backend", "token_count": 131 }
0
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; }
frontend/src/index.css/0
{ "file_path": "frontend/src/index.css", "repo_id": "frontend", "token_count": 155 }
1
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lsg.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
backend/manage.py/0
{ "file_path": "backend/manage.py", "repo_id": "backend", "token_count": 246 }
0
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <App /> </React.StrictMode> ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
frontend/src/index.js/0
{ "file_path": "frontend/src/index.js", "repo_id": "frontend", "token_count": 167 }
1
from django.contrib import admin # Register your models here.
backend/api/admin.py/0
{ "file_path": "backend/api/admin.py", "repo_id": "backend", "token_count": 17 }
0
# Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can't go back!** If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
frontend/README.md/0
{ "file_path": "frontend/README.md", "repo_id": "frontend", "token_count": 949 }
1
from django.apps import AppConfig class ApiConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api'
backend/api/apps.py/0
{ "file_path": "backend/api/apps.py", "repo_id": "backend", "token_count": 50 }
0
const reportWebVitals = onPerfEntry => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); getLCP(onPerfEntry); getTTFB(onPerfEntry); }); } }; export default reportWebVitals;
frontend/src/reportWebVitals.js/0
{ "file_path": "frontend/src/reportWebVitals.js", "repo_id": "frontend", "token_count": 163 }
1
README.md exists but content is empty.
Downloads last month
8