diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..7570ec3ba78e63b233198a8fe1c4ac1cc7765f02 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +target +.git +.gitignore +node_modules +.env diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..77d1b30b7bcd7aed915c238f0855f5054849bb4c --- /dev/null +++ b/.gitignore @@ -0,0 +1,36 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + + +docs/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..c0bcafe984fe33005eacbcfabe8b188e0f75afcd --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..321ad733f0fe90c366bc0e508ecdedaa198d386e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,30 @@ +# =============================== +# Build stage (Java 21) +# =============================== +FROM maven:3.9.6-eclipse-temurin-21 AS build + +WORKDIR /app + +COPY pom.xml . +RUN mvn dependency:go-offline + +COPY src ./src +RUN mvn clean package -DskipTests + +# =============================== +# Runtime stage (Java 21) +# =============================== +FROM eclipse-temurin:21-jre-alpine + +# Hugging Face requires running as a non-root user (user ID 1000) +RUN addgroup -S appgroup && adduser -S -u 1000 appuser -G appgroup +USER 1000 + +WORKDIR /app + +COPY --from=build --chown=appuser:appgroup /app/target/*.jar app.jar + +# Hugging Face Spaces exposes port 7860 +EXPOSE 7860 + +ENTRYPOINT ["java","-Dserver.port=7860","-jar","app.jar"] diff --git a/TestYahoo.java b/TestYahoo.java new file mode 100644 index 0000000000000000000000000000000000000000..fb82010bb3afe62c88b2c2d2592ddbfe88702627 --- /dev/null +++ b/TestYahoo.java @@ -0,0 +1,15 @@ +import yahoofinance.Stock; +import yahoofinance.YahooFinance; +import java.io.IOException; + +public class TestYahoo { + public static void main(String[] args) throws IOException { + System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"); + try { + Stock stock = YahooFinance.get("AAPL"); + System.out.println("Success! Price: " + stock.getQuote().getPrice()); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/mvnw b/mvnw new file mode 100644 index 0000000000000000000000000000000000000000..bd8896bf2217b46faa0291585e01ac1a3441a958 --- /dev/null +++ b/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000000000000000000000000000000000000..92450f93273470af42eeee491874afb2039b700a --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..bf76b9e263ca560b01ae97579e04dd428bff185a --- /dev/null +++ b/pom.xml @@ -0,0 +1,144 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.7 + + + com.rods + BacktestingStrategies + 0.0.1-SNAPSHOT + BacktestingStrategies + BacktestingStrategies + + + + + + + + + + + + + + + 21 + + + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.projectlombok + lombok + true + + + com.mysql + mysql-connector-j + runtime + + + + + com.yahoofinance-api + YahooFinanceAPI + 3.17.0 + + + + + com.fasterxml.jackson.core + jackson-databind + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-validation + + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + io.jsonwebtoken + jjwt-impl + 0.11.5 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + runtime + + + + org.postgresql + postgresql + runtime + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 21 + 21 + + + org.projectlombok + lombok + 1.18.42 + + + + + + + + diff --git a/src/main/java/com/rods/backtestingstrategies/BacktestingStrategiesApplication.java b/src/main/java/com/rods/backtestingstrategies/BacktestingStrategiesApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..e93f0804ff39142b67dc251fbed4fbc9115fa201 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/BacktestingStrategiesApplication.java @@ -0,0 +1,13 @@ +package com.rods.backtestingstrategies; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BacktestingStrategiesApplication { + + public static void main(String[] args) { + SpringApplication.run(BacktestingStrategiesApplication.class, args); + } + +} diff --git a/src/main/java/com/rods/backtestingstrategies/TestYahooCrumb.java b/src/main/java/com/rods/backtestingstrategies/TestYahooCrumb.java new file mode 100644 index 0000000000000000000000000000000000000000..558f19435732789fee37f18c8e906e2c0a82de92 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/TestYahooCrumb.java @@ -0,0 +1,52 @@ +import java.net.CookieManager; +import java.net.CookiePolicy; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import yahoofinance.YahooFinance; +import yahoofinance.Stock; + +public class TestYahooCrumb { + public static void main(String[] args) { + try { + System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"); + + CookieManager cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL); + java.net.CookieHandler.setDefault(cookieManager); + + HttpClient client = HttpClient.newBuilder() + .cookieHandler(cookieManager) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + + // 1. Get Cookie + HttpRequest req1 = HttpRequest.newBuilder() + .uri(URI.create("https://fc.yahoo.com")) + .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)") + .GET() + .build(); + client.send(req1, HttpResponse.BodyHandlers.discarding()); + System.out.println("Got cookies: " + cookieManager.getCookieStore().getCookies()); + + // 2. Get Crumb + HttpRequest req2 = HttpRequest.newBuilder() + .uri(URI.create("https://query1.finance.yahoo.com/v1/test/getcrumb")) + .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)") + .GET() + .build(); + HttpResponse res2 = client.send(req2, HttpResponse.BodyHandlers.ofString()); + String crumb = res2.body(); + System.out.println("Got crumb: " + crumb); + + // Set crumb internally for yahoofinance-api if possible, using reflection if needed + Class.forName("yahoofinance.histquotes2.CrumbManager").getDeclaredMethod("setCrumb", String.class).invoke(null, crumb); + + Stock stock = YahooFinance.get("AAPL"); + System.out.println("Success! Price: " + stock.getQuote().getPrice()); + + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/config/CorsConfig.java b/src/main/java/com/rods/backtestingstrategies/config/CorsConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..da0135b150c567c6f2b71332342ca798fc040b9c --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/config/CorsConfig.java @@ -0,0 +1,28 @@ +package com.rods.backtestingstrategies.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class CorsConfig { + + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins( + "https://backtest-livid.vercel.app", + "http://localhost:3000", + "http://localhost:5173") + .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") + .allowedHeaders("*") + .allowCredentials(true); + } + }; + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/controller/AuthController.java b/src/main/java/com/rods/backtestingstrategies/controller/AuthController.java new file mode 100644 index 0000000000000000000000000000000000000000..2ee07cd864eee804e733768094340aff8d0fb91e --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/controller/AuthController.java @@ -0,0 +1,59 @@ +package com.rods.backtestingstrategies.controller; + +import com.rods.backtestingstrategies.dto.AuthRequest; +import com.rods.backtestingstrategies.dto.AuthResponse; +import com.rods.backtestingstrategies.entity.User; +import com.rods.backtestingstrategies.repository.UserRepository; +import com.rods.backtestingstrategies.security.JwtUtils; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/api/auth") +@RequiredArgsConstructor +public class AuthController { + + private final AuthenticationManager authenticationManager; + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + private final JwtUtils jwtUtils; + private final UserDetailsService userDetailsService; + + @PostMapping("/register") + public ResponseEntity register(@RequestBody AuthRequest request) { + if (userRepository.findByUsername(request.getUsername()).isPresent()) { + return ResponseEntity.badRequest().body("Username already exists"); + } + + User user = User.builder() + .username(request.getUsername()) + .password(passwordEncoder.encode(request.getPassword())) + .role("USER") + .build(); + + userRepository.save(user); + + UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername()); + String jwtToken = jwtUtils.generateToken(userDetails); + + return ResponseEntity.ok(AuthResponse.builder().token(jwtToken).build()); + } + + @PostMapping("/login") + public ResponseEntity login(@RequestBody AuthRequest request) { + authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()) + ); + + UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername()); + String jwtToken = jwtUtils.generateToken(userDetails); + + return ResponseEntity.ok(AuthResponse.builder().token(jwtToken).build()); + } +} \ No newline at end of file diff --git a/src/main/java/com/rods/backtestingstrategies/controller/BacktestController.java b/src/main/java/com/rods/backtestingstrategies/controller/BacktestController.java new file mode 100644 index 0000000000000000000000000000000000000000..112efa4b2c7a98b5a1c825eb06e94eb62e7be51b --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/controller/BacktestController.java @@ -0,0 +1,99 @@ +package com.rods.backtestingstrategies.controller; + +import com.rods.backtestingstrategies.entity.BacktestResult; +import com.rods.backtestingstrategies.entity.PortfolioRequest; +import com.rods.backtestingstrategies.entity.PortfolioResult; +import com.rods.backtestingstrategies.entity.StrategyComparisonResult; +import com.rods.backtestingstrategies.service.BacktestService; +import com.rods.backtestingstrategies.strategy.StrategyType; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/api/backtest") +@CrossOrigin +@RequiredArgsConstructor +public class BacktestController { + + private final BacktestService backtestService; + + /** + * Run a backtest for a given symbol using a strategy. + * Supports optional custom strategy parameters. + * + * Examples: + * POST /api/backtest/AAPL?strategy=SMA&capital=100000 + * POST /api/backtest/AAPL?strategy=SMA&capital=100000&shortPeriod=10&longPeriod=30 + * POST /api/backtest/AAPL?strategy=MACD&fastPeriod=8&slowPeriod=21&signalPeriod=5 + */ + @PostMapping("/{symbol}") + public ResponseEntity runBacktest( + @PathVariable String symbol, + @RequestParam(defaultValue = "SMA") StrategyType strategy, + @RequestParam(defaultValue = "100000") double capital, + @RequestParam(required = false) Integer shortPeriod, + @RequestParam(required = false) Integer longPeriod, + @RequestParam(required = false) Integer fastPeriod, + @RequestParam(required = false) Integer slowPeriod, + @RequestParam(required = false) Integer signalPeriod + ) { + // Check if any custom params were provided + Map params = new HashMap<>(); + if (shortPeriod != null) params.put("shortPeriod", String.valueOf(shortPeriod)); + if (longPeriod != null) params.put("longPeriod", String.valueOf(longPeriod)); + if (fastPeriod != null) params.put("fastPeriod", String.valueOf(fastPeriod)); + if (slowPeriod != null) params.put("slowPeriod", String.valueOf(slowPeriod)); + if (signalPeriod != null) params.put("signalPeriod", String.valueOf(signalPeriod)); + + BacktestResult result; + if (params.isEmpty()) { + result = backtestService.backtest(symbol, strategy, capital); + } else { + result = backtestService.backtestWithParams(symbol, strategy, capital, params); + } + + return ResponseEntity.ok(result); + } + + /** + * Compare ALL available strategies on the same stock data. + * Returns rankings by return % and Sharpe Ratio. + * + * POST /api/backtest/compare/AAPL?capital=100000 + */ + @PostMapping("/compare/{symbol}") + public ResponseEntity compareStrategies( + @PathVariable String symbol, + @RequestParam(defaultValue = "100000") double capital + ) { + StrategyComparisonResult result = backtestService.compareStrategies(symbol, capital); + return ResponseEntity.ok(result); + } + + /** + * Run a portfolio-level backtest across multiple stocks. + * + * POST /api/backtest/portfolio + * Body: + * { + * "entries": [ + * {"symbol": "AAPL", "weight": 0.4}, + * {"symbol": "MSFT", "weight": 0.3}, + * {"symbol": "GOOGL", "weight": 0.3} + * ], + * "totalCapital": 100000, + * "strategy": "SMA" + * } + */ + @PostMapping("/portfolio") + public ResponseEntity runPortfolioBacktest( + @RequestBody PortfolioRequest request + ) { + PortfolioResult result = backtestService.backtestPortfolio(request); + return ResponseEntity.ok(result); + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/controller/MarketController.java b/src/main/java/com/rods/backtestingstrategies/controller/MarketController.java new file mode 100644 index 0000000000000000000000000000000000000000..e9d51ce22ffaf2b614ca87d94ebbfa5b1a067d32 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/controller/MarketController.java @@ -0,0 +1,104 @@ +package com.rods.backtestingstrategies.controller; + +import com.rods.backtestingstrategies.entity.Candle; +import com.rods.backtestingstrategies.entity.QuoteSummary; +import com.rods.backtestingstrategies.service.MarketDataService; +import com.rods.backtestingstrategies.service.TickerSeederService; +import com.rods.backtestingstrategies.service.YahooFinanceService; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import yahoofinance.Stock; +import yahoofinance.quotes.stock.StockQuote; +import yahoofinance.quotes.stock.StockStats; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/market") +@CrossOrigin +public class MarketController { + + private final YahooFinanceService yahooFinanceService; + private final MarketDataService marketDataService; + private final TickerSeederService tickerSeederService; + + public MarketController(YahooFinanceService yahooFinanceService, + MarketDataService marketDataService, + TickerSeederService tickerSeederService) { + this.yahooFinanceService = yahooFinanceService; + this.marketDataService = marketDataService; + this.tickerSeederService = tickerSeederService; + } + + /** + * Fetch & cache candle data for a stock symbol. + * Uses DB-first approach with Yahoo Finance sync. + */ + @GetMapping("/stock/{symbol}") + public ResponseEntity> getDailyStockData(@PathVariable String symbol) { + System.out.println("Request Received for: " + symbol); + return ResponseEntity.ok(marketDataService.getCandles(symbol)); + } + + /** + * Get real-time quote summary from Yahoo Finance. + * Includes price, change, volume, 52W range, fundamentals. + */ + @GetMapping("/quote/{symbol}") + public ResponseEntity getQuote(@PathVariable String symbol) { + try { + Stock stock = yahooFinanceService.getStock(symbol); + if (stock == null || stock.getQuote() == null) { + return ResponseEntity.notFound().build(); + } + + StockQuote quote = stock.getQuote(); + StockStats stats = stock.getStats(); + + QuoteSummary summary = QuoteSummary.builder() + .symbol(stock.getSymbol()) + .name(stock.getName()) + .exchange(stock.getStockExchange()) + .currency(stock.getCurrency()) + .price(quote.getPrice()) + .change(quote.getChange()) + .changePercent(quote.getChangeInPercent()) + .previousClose(quote.getPreviousClose()) + .open(quote.getOpen()) + .dayHigh(quote.getDayHigh()) + .dayLow(quote.getDayLow()) + .volume(quote.getVolume()) + .avgVolume(quote.getAvgVolume()) + .yearHigh(quote.getYearHigh()) + .yearLow(quote.getYearLow()) + .marketCap(stats != null ? stats.getMarketCap() : null) + .pe(stats != null ? stats.getPe() : null) + .eps(stats != null ? stats.getEps() : null) + .priceToBook(stats != null ? stats.getPriceBook() : null) + .bookValue(stats != null ? stats.getBookValuePerShare() : null) + .dividendYield(stock.getDividend() != null ? + stock.getDividend().getAnnualYieldPercent() : null) + .build(); + + return ResponseEntity.ok(summary); + } catch (IOException e) { + return ResponseEntity.internalServerError() + .body(Map.of("error", "Failed to fetch quote: " + e.getMessage())); + } + } + + /** + * Manually trigger a re-seed of the ticker database. + */ + @PostMapping("/reseed-tickers") + public ResponseEntity> reseedTickers() { + int count = tickerSeederService.reseedTickers(); + return ResponseEntity.ok(Map.of( + "message", "Ticker database re-seeded successfully", + "totalSymbols", count + )); + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/controller/SymbolController.java b/src/main/java/com/rods/backtestingstrategies/controller/SymbolController.java new file mode 100644 index 0000000000000000000000000000000000000000..a7ef191228cda1c6ca7eec19ed33fcd36b94510e --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/controller/SymbolController.java @@ -0,0 +1,90 @@ +package com.rods.backtestingstrategies.controller; + +import com.rods.backtestingstrategies.entity.StockSymbol; +import com.rods.backtestingstrategies.repository.StockSymbolRepository; +import com.rods.backtestingstrategies.service.MarketDataService; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/symbols") +@CrossOrigin +public class SymbolController { + + private final MarketDataService marketDataService; + private final StockSymbolRepository symbolRepository; + + public SymbolController(MarketDataService marketDataService, + StockSymbolRepository symbolRepository) { + this.marketDataService = marketDataService; + this.symbolRepository = symbolRepository; + } + + /** + * Search symbols by keyword (matches symbol prefix or company name). + * Optionally filter by exchange. + */ + @GetMapping("/search") + public List searchSymbols( + @RequestParam String query, + @RequestParam(required = false) String exchange + ) { + System.out.println("Symbol search request: query=" + query + ", exchange=" + exchange); + + if (query == null || query.length() < 1) { + return List.of(); + } + + if (exchange != null && !exchange.isBlank()) { + return marketDataService.searchSymbolsByExchange(query.trim(), exchange.trim()); + } + + return marketDataService.searchSymbols(query.trim()); + } + + /** + * Get all symbols for a specific exchange. + */ + @GetMapping("/exchange/{exchange}") + public List getByExchange(@PathVariable String exchange) { + return marketDataService.getSymbolsByExchange(exchange); + } + + /** + * Get symbols filtered by sector. + */ + @GetMapping("/sector/{sector}") + public List getBySector(@PathVariable String sector) { + return symbolRepository.findBySector(sector); + } + + /** + * Get all available exchanges. + */ + @GetMapping("/exchanges") + public List getExchanges() { + return symbolRepository.findAllExchanges(); + } + + /** + * Get all available sectors. + */ + @GetMapping("/sectors") + public List getSectors() { + return symbolRepository.findAllSectors(); + } + + /** + * Get summary stats about the ticker database. + */ + @GetMapping("/stats") + public Map getStats() { + return Map.of( + "totalSymbols", symbolRepository.count(), + "exchanges", symbolRepository.findAllExchanges(), + "sectors", symbolRepository.findAllSectors() + ); + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/dto/AuthRequest.java b/src/main/java/com/rods/backtestingstrategies/dto/AuthRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..e8dacbca8f8f632b1cea7058953b6ab78aff97bb --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/dto/AuthRequest.java @@ -0,0 +1,15 @@ +package com.rods.backtestingstrategies.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AuthRequest { + private String username; + private String password; +} diff --git a/src/main/java/com/rods/backtestingstrategies/dto/AuthResponse.java b/src/main/java/com/rods/backtestingstrategies/dto/AuthResponse.java new file mode 100644 index 0000000000000000000000000000000000000000..88d50652de5d193891261379d87dd8216e4c7ee9 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/dto/AuthResponse.java @@ -0,0 +1,14 @@ +package com.rods.backtestingstrategies.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AuthResponse { + private String token; +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/AuthenticationRequest.java b/src/main/java/com/rods/backtestingstrategies/entity/AuthenticationRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..2f0c60e82b90a7ef4f73c5e95a4a096ebf24beee --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/AuthenticationRequest.java @@ -0,0 +1,20 @@ +package com.rods.backtestingstrategies.entity; + +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class AuthenticationRequest { + + @NotBlank(message = "Username is required") + private String username; + + @NotBlank(message = "Password is required") + private String password; +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/AuthenticationResponse.java b/src/main/java/com/rods/backtestingstrategies/entity/AuthenticationResponse.java new file mode 100644 index 0000000000000000000000000000000000000000..788b67458a3ceaa0ef7aeff917f4c4cec7cd7a34 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/AuthenticationResponse.java @@ -0,0 +1,14 @@ +package com.rods.backtestingstrategies.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class AuthenticationResponse { + private String token; +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/BacktestResult.java b/src/main/java/com/rods/backtestingstrategies/entity/BacktestResult.java new file mode 100644 index 0000000000000000000000000000000000000000..d43f40009c53fce0a35a2ebaef335c859f4445d5 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/BacktestResult.java @@ -0,0 +1,52 @@ +package com.rods.backtestingstrategies.entity; + +import lombok.Builder; +import lombok.Getter; +import lombok.ToString; + +import java.util.List; + +@Getter +@Builder +@ToString +public class BacktestResult { + + // Capital metrics + private final double startCapital; + private final double finalCapital; + private final double profitLoss; + private final double returnPct; + + // Advanced performance metrics + private final PerformanceMetrics metrics; + + // Strategy name used + private final String strategyName; + + // Time-series equity curve + private final List equityCurve; + + // Executed trades + private final List transactions; + + // Bullish / Bearish crossover events + private final List crossovers; + + /* ========================== + Factory Helpers + ========================== */ + + public static BacktestResult empty(double capital) { + return BacktestResult.builder() + .startCapital(capital) + .finalCapital(capital) + .profitLoss(0.0) + .returnPct(0.0) + .strategyName("N/A") + .metrics(PerformanceMetrics.builder().build()) + .equityCurve(List.of()) + .transactions(List.of()) + .crossovers(List.of()) + .build(); + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/Candle.java b/src/main/java/com/rods/backtestingstrategies/entity/Candle.java new file mode 100644 index 0000000000000000000000000000000000000000..e96acdc2ea4d241518ef5cfa6abdab6fdc7a4e47 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/Candle.java @@ -0,0 +1,37 @@ +package com.rods.backtestingstrategies.entity; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Table( + name = "candles", + uniqueConstraints = { + @UniqueConstraint(columnNames = {"symbol", "date"}) + } +) +public class Candle { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + // We are using this Candle Entity to store the data related to a Stock in the database "OHLVC" + private String symbol; + + // Enforcing that the Symbol and the Dates are always unique + private LocalDate date; + private double openPrice; + private double highPrice; + private double lowPrice; + private double closePrice; + private long volume; + + +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/CrossOver.java b/src/main/java/com/rods/backtestingstrategies/entity/CrossOver.java new file mode 100644 index 0000000000000000000000000000000000000000..c5b7221a4398e8c0aab99800d972588a0513f87c --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/CrossOver.java @@ -0,0 +1,60 @@ +package com.rods.backtestingstrategies.entity; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDate; + +@Entity +@Table( + name = "crossovers", + indexes = { + @Index(name = "idx_crossover_date", columnList = "date"), + @Index(name = "idx_crossover_type", columnList = "type") + } +) +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) // JPA requirement +@AllArgsConstructor(access = AccessLevel.PRIVATE) // force factory usage +@ToString +@EqualsAndHashCode(of = {"date", "type", "price"}) +public class CrossOver { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // Date when crossover occurred + @Column(nullable = false) + private LocalDate date; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 10) + private CrossOverType type; // BULLISH or BEARISH + + // Price at crossover + @Column(nullable = false) + private double price; + + /* ========================== + Factory Methods + ========================== */ + + public static CrossOver bullish(Candle candle) { + return new CrossOver( + null, + candle.getDate(), + CrossOverType.BULLISH, + candle.getClosePrice() + ); + } + + public static CrossOver bearish(Candle candle) { + return new CrossOver( + null, + candle.getDate(), + CrossOverType.BEARISH, + candle.getClosePrice() + ); + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/CrossOverType.java b/src/main/java/com/rods/backtestingstrategies/entity/CrossOverType.java new file mode 100644 index 0000000000000000000000000000000000000000..88b4e02d6e817580e51f66026a3d5161007318f7 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/CrossOverType.java @@ -0,0 +1,6 @@ +package com.rods.backtestingstrategies.entity; + +public enum CrossOverType { + BULLISH, + BEARISH +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/EquityPoint.java b/src/main/java/com/rods/backtestingstrategies/entity/EquityPoint.java new file mode 100644 index 0000000000000000000000000000000000000000..fe4119487c4e20cd01814b0a88ba390c258f305e --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/EquityPoint.java @@ -0,0 +1,67 @@ +package com.rods.backtestingstrategies.entity; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDate; + +@Entity +@Table( + name = "equity_points", + indexes = { + @Index(name = "idx_equity_point_date", columnList = "date") + } +) +@Getter +@NoArgsConstructor // JPA requirement +@AllArgsConstructor // force factory usage +@ToString +@EqualsAndHashCode(of = {"date", "equity", "shares", "cash"}) +public class EquityPoint { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // Date of this equity snapshot + @Column(nullable = false) + private LocalDate date; + + // Market price at this candle + @Column(nullable = false) + private double price; + + // Total portfolio equity (cash + holdings) + @Column(nullable = false) + private double equity; + + // Number of shares held + @Column(nullable = false) + private long shares; + + // Cash balance + @Column(nullable = false) + private double cash; + + + + /* ========================== + Factory Method + ========================== */ + + public static EquityPoint of( + Candle candle, + double equity, + long shares, + double cash + ) { + return new EquityPoint( + null, + candle.getDate(), + candle.getClosePrice(), + equity, + shares, + cash + ); + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/PerformanceMetrics.java b/src/main/java/com/rods/backtestingstrategies/entity/PerformanceMetrics.java new file mode 100644 index 0000000000000000000000000000000000000000..cf0428395d6cecbf20b73d59cc1f52aaeeccbdf7 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/PerformanceMetrics.java @@ -0,0 +1,53 @@ +package com.rods.backtestingstrategies.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Advanced performance metrics for a backtest result. + * Calculated from equity curve and transaction history. + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class PerformanceMetrics { + + // Risk-adjusted return (annualized) + private double sharpeRatio; + + // Worst peak-to-trough decline (as negative %) + private double maxDrawdown; + + // Percentage of profitable trades + private double winRate; + + // Average profit on winning trades + private double avgWin; + + // Average loss on losing trades + private double avgLoss; + + // Ratio of average win to average loss + private double winLossRatio; + + // Total number of trades executed + private int totalTrades; + + // Number of winning trades + private int winningTrades; + + // Number of losing trades + private int losingTrades; + + // Annualized return percentage + private double annualizedReturn; + + // Profit factor: gross profit / gross loss + private double profitFactor; + + // Average holding period in days + private double avgHoldingPeriodDays; +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/PortfolioRequest.java b/src/main/java/com/rods/backtestingstrategies/entity/PortfolioRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..d5825a39283c4dd77be7e91d5859aa86c69acab2 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/PortfolioRequest.java @@ -0,0 +1,30 @@ +package com.rods.backtestingstrategies.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +/** + * Request body for portfolio-level backtesting. + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class PortfolioRequest { + + private List entries; + private double totalCapital; + private String strategy; // SMA, RSI, MACD, BUY_AND_HOLD + + @Data + @AllArgsConstructor + @NoArgsConstructor + public static class PortfolioEntry { + private String symbol; + private double weight; // 0.0 to 1.0 (e.g., 0.4 = 40% allocation) + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/PortfolioResult.java b/src/main/java/com/rods/backtestingstrategies/entity/PortfolioResult.java new file mode 100644 index 0000000000000000000000000000000000000000..a86dbb712e6d46049716a39dd885955169ad9e73 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/PortfolioResult.java @@ -0,0 +1,33 @@ +package com.rods.backtestingstrategies.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Map; + +/** + * Result of portfolio-level backtesting. + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class PortfolioResult { + + private double totalCapital; + private double finalValue; + private double totalPnL; + private double totalReturnPct; + private String strategyUsed; + + // Aggregate performance metrics across the portfolio + private PerformanceMetrics aggregateMetrics; + + // Per-symbol breakdown + private Map symbolResults; + + // Allocation info + private Map allocations; // symbol → allocated capital +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/QuoteSummary.java b/src/main/java/com/rods/backtestingstrategies/entity/QuoteSummary.java new file mode 100644 index 0000000000000000000000000000000000000000..64087c90ce907d14a1a5466356b9d37bf63759bb --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/QuoteSummary.java @@ -0,0 +1,48 @@ +package com.rods.backtestingstrategies.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; + +/** + * Real-time quote summary from Yahoo Finance + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class QuoteSummary { + + private String symbol; + private String name; + private String exchange; + private String currency; + + // Price info + private BigDecimal price; + private BigDecimal change; + private BigDecimal changePercent; + private BigDecimal previousClose; + private BigDecimal open; + private BigDecimal dayHigh; + private BigDecimal dayLow; + + // Volume + private Long volume; + private Long avgVolume; + + // 52-week range + private BigDecimal yearHigh; + private BigDecimal yearLow; + + // Fundamentals + private BigDecimal marketCap; + private BigDecimal pe; + private BigDecimal eps; + private BigDecimal dividendYield; + private BigDecimal bookValue; + private BigDecimal priceToBook; +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/RegisterRequest.java b/src/main/java/com/rods/backtestingstrategies/entity/RegisterRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..9dba284fc614a7d94c325006095ea9d58f9b097b --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/RegisterRequest.java @@ -0,0 +1,20 @@ +package com.rods.backtestingstrategies.entity; + +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class RegisterRequest { + + @NotBlank(message = "Username is required") + private String username; + + @NotBlank(message = "Password is required") + private String password; +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/SignalType.java b/src/main/java/com/rods/backtestingstrategies/entity/SignalType.java new file mode 100644 index 0000000000000000000000000000000000000000..10b96d4b8ce68c1ed5d4b004cc423f4d4dbb2dea --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/SignalType.java @@ -0,0 +1,9 @@ +package com.rods.backtestingstrategies.entity; + +import org.springframework.stereotype.Component; + + +public enum SignalType +{ + BUY , SELL , HOLD +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/Stock.java b/src/main/java/com/rods/backtestingstrategies/entity/Stock.java new file mode 100644 index 0000000000000000000000000000000000000000..59d2da8ccdcf4705504cee26cb8ddaa27de74c2b --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/Stock.java @@ -0,0 +1,22 @@ +package com.rods.backtestingstrategies.entity; + +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Stock { +// @Id +// @GeneratedValue(strategy = GenerationType.IDENTITY) +// private long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private String symbol; + private String name; +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/StockSymbol.java b/src/main/java/com/rods/backtestingstrategies/entity/StockSymbol.java new file mode 100644 index 0000000000000000000000000000000000000000..d65fec6913b5bd054b532fb354e55e51496632c2 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/StockSymbol.java @@ -0,0 +1,84 @@ +package com.rods.backtestingstrategies.entity; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + + +@Entity +@Table( + name = "stock_symbols", + uniqueConstraints = { + @UniqueConstraint(columnNames = {"symbol"}) + }, + indexes = { + @Index(name = "idx_symbol", columnList = "symbol"), + @Index(name = "idx_name", columnList = "name"), + @Index(name = "idx_exchange", columnList = "exchange"), + @Index(name = "idx_sector", columnList = "sector") + } +) +@Data +@AllArgsConstructor +@NoArgsConstructor +public class StockSymbol { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // e.g. AAPL, TSLA, RELIANCE.NS + @Column(nullable = false, length = 20) + private String symbol; + + // e.g. Apple Inc, Reliance Industries + @Column(nullable = false, length = 255) + private String name; + + // Equity, ETF, Index + @Column(length = 50) + private String type; + + // Exchange name: NASDAQ, NYSE, BSE, NSE + @Column(length = 50) + private String exchange; + + // Country / Region + @Column(length = 100) + private String region; + + @Column(length = 10) + private String marketOpen; + + @Column(length = 10) + private String marketClose; + + @Column(length = 20) + private String timezone; + + @Column(length = 10) + private String currency; + + // Sector: Technology, Finance, Healthcare, etc. + @Column(length = 100) + private String sector; + + // Industry sub-category + @Column(length = 150) + private String industry; + + // Search relevance score (1.0 = exact match) + @Column + private Double matchScore; + + // When this symbol was last fetched/refreshed + @Column(nullable = false) + private LocalDateTime lastFetched; + + // Data source tracker + @Column(length = 50) + private String source = "TICKER_SEED"; +} \ No newline at end of file diff --git a/src/main/java/com/rods/backtestingstrategies/entity/StrategyComparisonResult.java b/src/main/java/com/rods/backtestingstrategies/entity/StrategyComparisonResult.java new file mode 100644 index 0000000000000000000000000000000000000000..45df6cb1ed9f48aae6964ce12fbe17c026f9bcb4 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/StrategyComparisonResult.java @@ -0,0 +1,34 @@ +package com.rods.backtestingstrategies.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; +import java.util.Map; + +/** + * Result of comparing multiple strategies on the same stock data. + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class StrategyComparisonResult { + + private String symbol; + private double initialCapital; + + // Individual results keyed by strategy name + private Map results; + + // Ranking: best to worst by return % + private List rankByReturn; + + // Ranking: best to worst by Sharpe Ratio + private List rankBySharpe; + + // Best overall strategy name + private String bestStrategy; +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/TradeSignal.java b/src/main/java/com/rods/backtestingstrategies/entity/TradeSignal.java new file mode 100644 index 0000000000000000000000000000000000000000..16463922c2fed80ebe014bf89866007e9ae709e7 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/TradeSignal.java @@ -0,0 +1,85 @@ +package com.rods.backtestingstrategies.entity; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDate; + +@Entity +@Table( + name = "trade_signals", + indexes = { + @Index(name = "idx_trade_signal_date", columnList = "signalDate"), + @Index(name = "idx_trade_signal_type", columnList = "signalType") + } +) +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) // JPA requirement +@AllArgsConstructor(access = AccessLevel.PRIVATE) // Force factory usage +@EqualsAndHashCode(of = {"signalDate", "signalType", "price"}) +@ToString +public class TradeSignal { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // Date on which signal is generated + @Column(nullable = false) + private LocalDate signalDate; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 10) + private SignalType signalType; + + // Price at signal generation (usually close price) + @Column(nullable = false) + private double price; + + // Optional: identify which strategy generated this signal + @Column(length = 100) + private String strategyName; + + /* ========================== + Factory Methods + ========================== */ + + public static TradeSignal buy(Candle candle) { + return new TradeSignal( + null, + candle.getDate(), + SignalType.BUY, + candle.getClosePrice(), + null + ); + } + + public static TradeSignal sell(Candle candle) { + return new TradeSignal( + null, + candle.getDate(), + SignalType.SELL, + candle.getClosePrice(), + null + ); + } + + public static TradeSignal hold() { + return new TradeSignal( + null, + null, + SignalType.HOLD, + 0.0, + null + ); + } + + /* ========================== + Optional helpers + ========================== */ + + public TradeSignal withStrategyName(String strategyName) { + this.strategyName = strategyName; + return this; + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/Transaction.java b/src/main/java/com/rods/backtestingstrategies/entity/Transaction.java new file mode 100644 index 0000000000000000000000000000000000000000..2e9698e171b4a4898581d2b1d8bbabe763ec8270 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/Transaction.java @@ -0,0 +1,90 @@ +package com.rods.backtestingstrategies.entity; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDate; + +@Entity +@Table( + name = "transactions", + indexes = { + @Index(name = "idx_tx_date", columnList = "date"), + @Index(name = "idx_tx_type", columnList = "type") + } +) +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) // JPA requirement +@AllArgsConstructor(access = AccessLevel.PRIVATE) // force factory usage +@ToString +@EqualsAndHashCode(of = {"date", "type", "price", "shares"}) +public class Transaction { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // Execution date + @Column(nullable = false) + private LocalDate date; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 10) + private SignalType type; // BUY or SELL + + // Execution price + @Column(nullable = false) + private double price; + + // Number of shares traded + @Column(nullable = false) + private long shares; + + // Cash remaining after execution + @Column(nullable = false) + private double cashAfter; + + // Total equity after execution + @Column(nullable = false) + private double equityAfter; + + /* ========================== + Factory Methods + ========================== */ + + public static Transaction buy( + Candle candle, + double price, + long shares, + double cashAfter, + double equityAfter + ) { + return new Transaction( + null, + candle.getDate(), + SignalType.BUY, + price, + shares, + cashAfter, + equityAfter + ); + } + + public static Transaction sell( + Candle candle, + double price, + long shares, + double cashAfter, + double equityAfter + ) { + return new Transaction( + null, + candle.getDate(), + SignalType.SELL, + price, + shares, + cashAfter, + equityAfter + ); + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/entity/User.java b/src/main/java/com/rods/backtestingstrategies/entity/User.java new file mode 100644 index 0000000000000000000000000000000000000000..8f649ed6ef9d39d4dfb587df59723ffc701c68d7 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/entity/User.java @@ -0,0 +1,29 @@ +package com.rods.backtestingstrategies.entity; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(unique = true, nullable = false) + private String username; + + @Column(nullable = false) + private String password; + + @Column(nullable = false) + private String role; +} diff --git a/src/main/java/com/rods/backtestingstrategies/repository/CandleRepository.java b/src/main/java/com/rods/backtestingstrategies/repository/CandleRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..03dd181edef200b9f3744b3c9824e2bf66ab7245 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/repository/CandleRepository.java @@ -0,0 +1,22 @@ +package com.rods.backtestingstrategies.repository; + +import com.rods.backtestingstrategies.entity.Candle; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.time.LocalDate; +import java.util.List; + + +public interface CandleRepository extends JpaRepository { + List findBySymbolOrderByDateAsc(String symbol); + + + // Fetching the existing date from the Database --> To check whether there is a need to syncMarket() Data + // Before we used to fetch the entire data first and then check the last data --> very slow (in efficient) + @Query("SELECT c.date FROM Candle c WHERE c.symbol = :symbol") + List findExistingDates(@Param("symbol") String symbol); + + +} diff --git a/src/main/java/com/rods/backtestingstrategies/repository/StockSymbolRepository.java b/src/main/java/com/rods/backtestingstrategies/repository/StockSymbolRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..64b4d9e3bab31a20b8ee173e2ef3f762319d7d7e --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/repository/StockSymbolRepository.java @@ -0,0 +1,90 @@ +package com.rods.backtestingstrategies.repository; + +import com.rods.backtestingstrategies.entity.StockSymbol; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.time.LocalDateTime; +import java.util.List; + +public interface StockSymbolRepository extends JpaRepository { + + /** + * Fuzzy search by symbol prefix or company name substring. + * Ordered by match score descending. + */ + @Query(""" + SELECT s FROM StockSymbol s + WHERE LOWER(s.symbol) LIKE LOWER(CONCAT(:query, '%')) + OR LOWER(s.name) LIKE LOWER(CONCAT('%', :query, '%')) + ORDER BY s.matchScore DESC + """) + List searchSymbols(@Param("query") String query); + + /** + * Search symbols filtered by a specific exchange. + */ + @Query(""" + SELECT s FROM StockSymbol s + WHERE (LOWER(s.symbol) LIKE LOWER(CONCAT(:query, '%')) + OR LOWER(s.name) LIKE LOWER(CONCAT('%', :query, '%'))) + AND LOWER(s.exchange) = LOWER(:exchange) + ORDER BY s.matchScore DESC + """) + List searchSymbolsByExchange( + @Param("query") String query, + @Param("exchange") String exchange + ); + + /** + * Find a specific symbol (case-insensitive) + */ + @Query(""" + SELECT s FROM StockSymbol s + WHERE LOWER(s.symbol) = LOWER(:symbol) + """) + StockSymbol findBySymbol(@Param("symbol") String symbol); + + /** + * Get all symbols for a specific exchange + */ + @Query(""" + SELECT s FROM StockSymbol s + WHERE LOWER(s.exchange) = LOWER(:exchange) + ORDER BY s.symbol ASC + """) + List findByExchange(@Param("exchange") String exchange); + + /** + * Get all symbols for a specific sector + */ + @Query(""" + SELECT s FROM StockSymbol s + WHERE LOWER(s.sector) = LOWER(:sector) + ORDER BY s.symbol ASC + """) + List findBySector(@Param("sector") String sector); + + /** + * Get the last fetched timestamp for symbol search freshness check + */ + @Query(""" + SELECT MAX(s.lastFetched) + FROM StockSymbol s + WHERE LOWER(s.symbol) LIKE LOWER(CONCAT(:query, '%')) + """) + LocalDateTime findLastFetchedForQuery(@Param("query") String query); + + /** + * Get all distinct exchange names + */ + @Query("SELECT DISTINCT s.exchange FROM StockSymbol s ORDER BY s.exchange") + List findAllExchanges(); + + /** + * Get all distinct sectors + */ + @Query("SELECT DISTINCT s.sector FROM StockSymbol s WHERE s.sector IS NOT NULL ORDER BY s.sector") + List findAllSectors(); +} diff --git a/src/main/java/com/rods/backtestingstrategies/repository/UserRepository.java b/src/main/java/com/rods/backtestingstrategies/repository/UserRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..dae3c30c49a49205049d81b03c2000b6c48bc66b --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/repository/UserRepository.java @@ -0,0 +1,10 @@ +package com.rods.backtestingstrategies.repository; + +import com.rods.backtestingstrategies.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface UserRepository extends JpaRepository { + Optional findByUsername(String username); +} diff --git a/src/main/java/com/rods/backtestingstrategies/security/CustomUserDetailsService.java b/src/main/java/com/rods/backtestingstrategies/security/CustomUserDetailsService.java new file mode 100644 index 0000000000000000000000000000000000000000..0f1277655eaaefd4d6f1d98e2bbfd2bd880eecfb --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/security/CustomUserDetailsService.java @@ -0,0 +1,30 @@ +package com.rods.backtestingstrategies.security; + +import com.rods.backtestingstrategies.entity.User; +import com.rods.backtestingstrategies.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; + +@Service +@RequiredArgsConstructor +public class CustomUserDetailsService implements UserDetailsService { + + private final UserRepository userRepository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + User user = userRepository.findByUsername(username) + .orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + username)); + + return new org.springframework.security.core.userdetails.User( + user.getUsername(), + user.getPassword(), + new ArrayList<>() // Authorities/Roles can be added here + ); + } +} \ No newline at end of file diff --git a/src/main/java/com/rods/backtestingstrategies/security/JwtAuthenticationFilter.java b/src/main/java/com/rods/backtestingstrategies/security/JwtAuthenticationFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..f39800ffd095a862c243eff86bee0e057266c816 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/security/JwtAuthenticationFilter.java @@ -0,0 +1,59 @@ +package com.rods.backtestingstrategies.security; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.lang.NonNull; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@Component +@RequiredArgsConstructor +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private final JwtUtils jwtService; + private final UserDetailsService userDetailsService; + + @Override + protected void doFilterInternal( + @NonNull HttpServletRequest request, + @NonNull HttpServletResponse response, + @NonNull FilterChain filterChain) throws ServletException, IOException { + + final String authHeader = request.getHeader("Authorization"); + final String jwt; + final String userEmail; + + if (authHeader == null || !authHeader.startsWith("Bearer ")) { + filterChain.doFilter(request, response); + return; + } + + jwt = authHeader.substring(7); + userEmail = jwtService.extractUsername(jwt); + + if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) { + UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail); + + if (jwtService.isTokenValid(jwt, userDetails)) { + UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( + userDetails, + null, + userDetails.getAuthorities()); + authToken.setDetails( + new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(authToken); + } + } + filterChain.doFilter(request, response); + } +} \ No newline at end of file diff --git a/src/main/java/com/rods/backtestingstrategies/security/JwtUtils.java b/src/main/java/com/rods/backtestingstrategies/security/JwtUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..86832379644a4e43218591023c33323278bcd280 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/security/JwtUtils.java @@ -0,0 +1,97 @@ +package com.rods.backtestingstrategies.security; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import java.security.Key; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +@Component +public class JwtUtils { + + @Value("${jwt.secret}") + private String secret; + + @Value("${jwt.expiration}") + private long jwtExpiration; + + public String extractUsername(String token) { + return extractClaim(token, Claims::getSubject); + } + + public Date extractExpiration(String token) { + return extractClaim(token, Claims::getExpiration); + } + + public T extractClaim(String token, Function claimsResolver) { + final Claims claims = extractAllClaims(token); + return claimsResolver.apply(claims); + } + + private Claims extractAllClaims(String token) { + return Jwts.parserBuilder() + .setSigningKey(getSigningKey()) + .build() + .parseClaimsJws(token) + .getBody(); + } + + private Key getSigningKey() { + byte[] keyBytes = Decoders.BASE64.decode(secret); // Actually I used HEX in current example, but standard is + // often Base64. Let's stick to simple Bytes for now or assume + // secret is compatible. + // Wait, I put a HEX string in application.yml? + // Let's modify the code to parse hex if I used hex, or better, just use the + // string bytes if it's simpler. + // Actually, the standard JJWT way is to use a Base64 encoded key or just raw + // bytes. + // To be safe and consistent with the hex I generated: 5367566B5970... + // Hex decoding is safer for the string I put. But Decoders.BASE64 expects + // Base64. + // Let's assume I'll change the secret in YAML to a proper Base64 or just use + // string bytes. + // For simplicity, let's just use + // Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret)) and expect the user to + // provide a Base64 secret, OR + // Use the hex decoder if I want to support that specific hex string. + // I'll stick to Base64 for standardness. + // Wait, the secret I put `5367...` is clearly hex. + // I will change the code to use `Decoders.BASE64` and I will update the secret + // in YAML to a Base64 string to be clean. + // Or I can just use `secret.getBytes()` if I don't care about the format. + // Let's go with standard Base64. + return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret)); + } + + public String generateToken(UserDetails userDetails) { + return generateToken(new HashMap<>(), userDetails); + } + + public String generateToken(Map extraClaims, UserDetails userDetails) { + return Jwts.builder() + .setClaims(extraClaims) + .setSubject(userDetails.getUsername()) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + jwtExpiration)) + .signWith(getSigningKey(), SignatureAlgorithm.HS256) + .compact(); + } + + public boolean isTokenValid(String token, UserDetails userDetails) { + final String username = extractUsername(token); + return (username.equals(userDetails.getUsername())) && !isTokenExpired(token); + } + + private boolean isTokenExpired(String token) { + return extractExpiration(token).before(new Date()); + } +} \ No newline at end of file diff --git a/src/main/java/com/rods/backtestingstrategies/security/SecurityConfig.java b/src/main/java/com/rods/backtestingstrategies/security/SecurityConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..d80f087ae1c6649e87b53ac3d7540e5cda86c969 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/security/SecurityConfig.java @@ -0,0 +1,77 @@ +package com.rods.backtestingstrategies.security; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + + private final JwtAuthenticationFilter jwtAuthFilter; + private final UserDetailsService userDetailsService; + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .csrf(AbstractHttpConfigurer::disable) + .cors(Customizer.withDefaults()) + .authorizeHttpRequests(auth -> auth + .requestMatchers(org.springframework.http.HttpMethod.OPTIONS, "/**").permitAll() // Allow preflight checks + .requestMatchers("/api/auth/**", "/server/**", "/error").permitAll() // Whitelist public endpoints + .anyRequest().authenticated() // Secure everything else + ) + .sessionManagement(sess -> sess + .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authenticationProvider(authenticationProvider()) + .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } + + @Bean + public AuthenticationProvider authenticationProvider() { + DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + authProvider.setUserDetailsService(userDetailsService); + authProvider.setPasswordEncoder(passwordEncoder()); + return authProvider; + } + + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { + return config.getAuthenticationManager(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public org.springframework.web.cors.CorsConfigurationSource corsConfigurationSource() { + org.springframework.web.cors.CorsConfiguration configuration = new org.springframework.web.cors.CorsConfiguration(); + configuration.setAllowedOrigins(java.util.Arrays.asList("http://localhost:5173", "http://localhost:3000", "https://backtest-livid.vercel.app")); + configuration + .setAllowedMethods(java.util.Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH")); + configuration.setAllowedHeaders(java.util.Collections.singletonList("*")); + configuration.setAllowCredentials(true); + org.springframework.web.cors.UrlBasedCorsConfigurationSource source = new org.springframework.web.cors.UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } +} \ No newline at end of file diff --git a/src/main/java/com/rods/backtestingstrategies/service/BacktestService.java b/src/main/java/com/rods/backtestingstrategies/service/BacktestService.java new file mode 100644 index 0000000000000000000000000000000000000000..b2b730152eb7dff81dcad41711deb9a970f81419 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/service/BacktestService.java @@ -0,0 +1,419 @@ +package com.rods.backtestingstrategies.service; + +import com.rods.backtestingstrategies.entity.*; +import com.rods.backtestingstrategies.strategy.*; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class BacktestService { + + private final MarketDataService marketDataService; + private final StrategyFactory strategyFactory; + + /** + * Run a backtest with default strategy parameters. + */ + public BacktestResult backtest( + String symbol, + StrategyType strategyType, + double initialCapital + ) { + Strategy strategy = strategyFactory.getStrategy(strategyType); + return executeBacktest(symbol, strategy, initialCapital); + } + + /** + * Run a backtest with custom strategy parameters. + */ + public BacktestResult backtestWithParams( + String symbol, + StrategyType strategyType, + double initialCapital, + Map params + ) { + Strategy strategy = createParameterizedStrategy(strategyType, params); + return executeBacktest(symbol, strategy, initialCapital); + } + + /** + * Compare all available strategies on the same stock data. + */ + public StrategyComparisonResult compareStrategies( + String symbol, + double initialCapital + ) { + Map results = new LinkedHashMap<>(); + + for (StrategyType type : StrategyType.values()) { + try { + Strategy strategy = strategyFactory.getStrategy(type); + BacktestResult result = executeBacktest(symbol, strategy, initialCapital); + results.put(strategy.getName(), result); + } catch (IllegalArgumentException e) { + // Strategy not implemented yet, skip + } + } + + // Rank by return % + List rankByReturn = results.entrySet().stream() + .sorted((a, b) -> Double.compare(b.getValue().getReturnPct(), a.getValue().getReturnPct())) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + + // Rank by Sharpe Ratio + List rankBySharpe = results.entrySet().stream() + .sorted((a, b) -> Double.compare( + b.getValue().getMetrics().getSharpeRatio(), + a.getValue().getMetrics().getSharpeRatio())) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + + String best = rankByReturn.isEmpty() ? "N/A" : rankByReturn.getFirst(); + + return StrategyComparisonResult.builder() + .symbol(symbol) + .initialCapital(initialCapital) + .results(results) + .rankByReturn(rankByReturn) + .rankBySharpe(rankBySharpe) + .bestStrategy(best) + .build(); + } + + /** + * Run portfolio-level backtest across multiple symbols. + */ + public PortfolioResult backtestPortfolio(PortfolioRequest request) { + StrategyType strategyType = StrategyType.valueOf(request.getStrategy().toUpperCase()); + Strategy strategy = strategyFactory.getStrategy(strategyType); + + Map symbolResults = new LinkedHashMap<>(); + Map allocations = new LinkedHashMap<>(); + + double totalFinalValue = 0; + + for (PortfolioRequest.PortfolioEntry entry : request.getEntries()) { + double allocatedCapital = request.getTotalCapital() * entry.getWeight(); + allocations.put(entry.getSymbol(), allocatedCapital); + + BacktestResult result = executeBacktest(entry.getSymbol(), strategy, allocatedCapital); + symbolResults.put(entry.getSymbol(), result); + totalFinalValue += result.getFinalCapital(); + } + + double totalPnL = totalFinalValue - request.getTotalCapital(); + double totalReturnPct = request.getTotalCapital() == 0 ? 0 : + (totalPnL / request.getTotalCapital()) * 100.0; + + // Aggregate metrics weighted by allocation + PerformanceMetrics aggregateMetrics = calculateAggregateMetrics(symbolResults, allocations, request.getTotalCapital()); + + return PortfolioResult.builder() + .totalCapital(request.getTotalCapital()) + .finalValue(totalFinalValue) + .totalPnL(totalPnL) + .totalReturnPct(totalReturnPct) + .strategyUsed(strategy.getName()) + .aggregateMetrics(aggregateMetrics) + .symbolResults(symbolResults) + .allocations(allocations) + .build(); + } + + /* ========================== + Core Execution Engine + ========================== */ + + private BacktestResult executeBacktest(String symbol, Strategy strategy, double initialCapital) { + List candles = marketDataService.getCandles(symbol); + + if (candles == null || candles.isEmpty()) { + return BacktestResult.empty(initialCapital); + } + + candles.sort(Comparator.comparing(Candle::getDate)); + + double cash = initialCapital; + long shares = 0L; + + List equityCurve = new ArrayList<>(); + List transactions = new ArrayList<>(); + List crossovers = new ArrayList<>(); + + for (int i = 0; i < candles.size(); i++) { + Candle candle = candles.get(i); + double price = candle.getClosePrice(); + + TradeSignal signal = strategy.evaluate(candles, i) + .withStrategyName(strategy.getName()); + + switch (signal.getSignalType()) { + case BUY -> { + if (cash > 0 && shares == 0) { + long buyShares = (long) (cash / price); + if (buyShares > 0) { + cash -= buyShares * price; + shares += buyShares; + transactions.add( + Transaction.buy(candle, price, buyShares, cash, cash + shares * price) + ); + crossovers.add(CrossOver.bullish(candle)); + } + } + } + case SELL -> { + if (shares > 0) { + double proceeds = shares * price; + cash += proceeds; + transactions.add( + Transaction.sell(candle, price, shares, cash, cash) + ); + crossovers.add(CrossOver.bearish(candle)); + shares = 0; + } + } + case HOLD -> { /* no-op */ } + } + + double equity = cash + shares * price; + equityCurve.add(EquityPoint.of(candle, equity, shares, cash)); + } + + EquityPoint last = equityCurve.getLast(); + double finalValue = last.getEquity(); + double pnl = finalValue - initialCapital; + double returnPct = initialCapital == 0 ? 0 : (pnl / initialCapital) * 100.0; + + // Calculate advanced metrics + PerformanceMetrics metrics = calculateMetrics(equityCurve, transactions, initialCapital); + + return BacktestResult.builder() + .startCapital(initialCapital) + .finalCapital(finalValue) + .profitLoss(pnl) + .returnPct(returnPct) + .strategyName(strategy.getName()) + .metrics(metrics) + .equityCurve(equityCurve) + .transactions(transactions) + .crossovers(crossovers) + .build(); + } + + /* ========================== + Advanced Metrics Calculator + ========================== */ + + private PerformanceMetrics calculateMetrics( + List equityCurve, + List transactions, + double initialCapital + ) { + if (equityCurve.isEmpty()) { + return PerformanceMetrics.builder().build(); + } + + // --- Max Drawdown --- + double maxDrawdown = calculateMaxDrawdown(equityCurve); + + // --- Trade Analysis --- + List tradePnLs = calculateTradePnLs(transactions); + int totalTrades = tradePnLs.size(); + int winningTrades = (int) tradePnLs.stream().filter(p -> p > 0).count(); + int losingTrades = (int) tradePnLs.stream().filter(p -> p < 0).count(); + double winRate = totalTrades == 0 ? 0 : (double) winningTrades / totalTrades * 100.0; + + double avgWin = tradePnLs.stream().filter(p -> p > 0).mapToDouble(Double::doubleValue).average().orElse(0); + double avgLoss = tradePnLs.stream().filter(p -> p < 0).mapToDouble(Double::doubleValue).average().orElse(0); + double winLossRatio = avgLoss == 0 ? 0 : Math.abs(avgWin / avgLoss); + + double grossProfit = tradePnLs.stream().filter(p -> p > 0).mapToDouble(Double::doubleValue).sum(); + double grossLoss = Math.abs(tradePnLs.stream().filter(p -> p < 0).mapToDouble(Double::doubleValue).sum()); + double profitFactor = grossLoss == 0 ? 0 : grossProfit / grossLoss; + + // --- Sharpe Ratio --- + double sharpeRatio = calculateSharpeRatio(equityCurve); + + // --- Annualized Return --- + double finalEquity = equityCurve.getLast().getEquity(); + long days = ChronoUnit.DAYS.between( + equityCurve.getFirst().getDate(), + equityCurve.getLast().getDate() + ); + double years = Math.max(days / 365.25, 0.01); + double annualizedReturn = (Math.pow(finalEquity / initialCapital, 1.0 / years) - 1.0) * 100.0; + + // --- Average Holding Period --- + double avgHoldingDays = calculateAvgHoldingPeriod(transactions); + + return PerformanceMetrics.builder() + .sharpeRatio(round(sharpeRatio)) + .maxDrawdown(round(maxDrawdown)) + .winRate(round(winRate)) + .avgWin(round(avgWin)) + .avgLoss(round(avgLoss)) + .winLossRatio(round(winLossRatio)) + .totalTrades(totalTrades) + .winningTrades(winningTrades) + .losingTrades(losingTrades) + .annualizedReturn(round(annualizedReturn)) + .profitFactor(round(profitFactor)) + .avgHoldingPeriodDays(round(avgHoldingDays)) + .build(); + } + + private double calculateMaxDrawdown(List equityCurve) { + double peak = equityCurve.getFirst().getEquity(); + double maxDrawdown = 0; + + for (EquityPoint point : equityCurve) { + if (point.getEquity() > peak) { + peak = point.getEquity(); + } + double drawdown = (peak - point.getEquity()) / peak * 100.0; + if (drawdown > maxDrawdown) { + maxDrawdown = drawdown; + } + } + return -maxDrawdown; // Return as negative percentage + } + + private double calculateSharpeRatio(List equityCurve) { + if (equityCurve.size() < 2) return 0; + + // Daily returns + List dailyReturns = new ArrayList<>(); + for (int i = 1; i < equityCurve.size(); i++) { + double prevEquity = equityCurve.get(i - 1).getEquity(); + double currEquity = equityCurve.get(i).getEquity(); + if (prevEquity != 0) { + dailyReturns.add((currEquity - prevEquity) / prevEquity); + } + } + + if (dailyReturns.isEmpty()) return 0; + + double avgReturn = dailyReturns.stream().mapToDouble(Double::doubleValue).average().orElse(0); + double stdDev = Math.sqrt( + dailyReturns.stream() + .mapToDouble(r -> Math.pow(r - avgReturn, 2)) + .average() + .orElse(0) + ); + + if (stdDev == 0) return 0; + + // Annualized Sharpe (assuming 252 trading days, risk-free rate = 0) + return (avgReturn / stdDev) * Math.sqrt(252); + } + + private List calculateTradePnLs(List transactions) { + List pnls = new ArrayList<>(); + Double buyPrice = null; + long buyShares = 0; + + for (Transaction tx : transactions) { + if (tx.getType() == SignalType.BUY) { + buyPrice = tx.getPrice(); + buyShares = tx.getShares(); + } else if (tx.getType() == SignalType.SELL && buyPrice != null) { + double pnl = (tx.getPrice() - buyPrice) * buyShares; + pnls.add(pnl); + buyPrice = null; + buyShares = 0; + } + } + return pnls; + } + + private double calculateAvgHoldingPeriod(List transactions) { + List holdingDays = new ArrayList<>(); + Transaction buyTx = null; + + for (Transaction tx : transactions) { + if (tx.getType() == SignalType.BUY) { + buyTx = tx; + } else if (tx.getType() == SignalType.SELL && buyTx != null) { + long days = ChronoUnit.DAYS.between(buyTx.getDate(), tx.getDate()); + holdingDays.add(days); + buyTx = null; + } + } + + return holdingDays.isEmpty() ? 0 : + holdingDays.stream().mapToLong(Long::longValue).average().orElse(0); + } + + private PerformanceMetrics calculateAggregateMetrics( + Map symbolResults, + Map allocations, + double totalCapital + ) { + // Weighted average of individual metrics + double weightedSharpe = 0; + double weightedReturn = 0; + double totalMaxDrawdown = 0; + int totalTrades = 0; + int totalWins = 0; + int totalLosses = 0; + + for (var entry : symbolResults.entrySet()) { + double weight = allocations.getOrDefault(entry.getKey(), 0.0) / totalCapital; + PerformanceMetrics m = entry.getValue().getMetrics(); + + weightedSharpe += m.getSharpeRatio() * weight; + weightedReturn += m.getAnnualizedReturn() * weight; + totalMaxDrawdown = Math.min(totalMaxDrawdown, m.getMaxDrawdown()); + totalTrades += m.getTotalTrades(); + totalWins += m.getWinningTrades(); + totalLosses += m.getLosingTrades(); + } + + double winRate = totalTrades == 0 ? 0 : (double) totalWins / totalTrades * 100.0; + + return PerformanceMetrics.builder() + .sharpeRatio(round(weightedSharpe)) + .maxDrawdown(round(totalMaxDrawdown)) + .winRate(round(winRate)) + .totalTrades(totalTrades) + .winningTrades(totalWins) + .losingTrades(totalLosses) + .annualizedReturn(round(weightedReturn)) + .build(); + } + + /* ========================== + Parameterized Strategy Factory + ========================== */ + + private Strategy createParameterizedStrategy(StrategyType type, Map params) { + return switch (type) { + case SMA -> { + int shortPeriod = Integer.parseInt(params.getOrDefault("shortPeriod", "20")); + int longPeriod = Integer.parseInt(params.getOrDefault("longPeriod", "50")); + yield new SmaCrossoverStrategy(shortPeriod, longPeriod); + } + case RSI -> { + // RSI uses class constants — for custom params, create a new configurable version + yield strategyFactory.getStrategy(type); + } + case MACD -> { + int fast = Integer.parseInt(params.getOrDefault("fastPeriod", "12")); + int slow = Integer.parseInt(params.getOrDefault("slowPeriod", "26")); + int signal = Integer.parseInt(params.getOrDefault("signalPeriod", "9")); + yield new MacdStrategy(fast, slow, signal); + } + case BUY_AND_HOLD -> strategyFactory.getStrategy(type); + }; + } + + private double round(double value) { + return Math.round(value * 100.0) / 100.0; + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/service/MarketDataService.java b/src/main/java/com/rods/backtestingstrategies/service/MarketDataService.java new file mode 100644 index 0000000000000000000000000000000000000000..0720f55707a25bd9772908ad5dbfe1a7f94be065 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/service/MarketDataService.java @@ -0,0 +1,147 @@ +package com.rods.backtestingstrategies.service; + +import com.rods.backtestingstrategies.entity.Candle; +import com.rods.backtestingstrategies.entity.StockSymbol; +import com.rods.backtestingstrategies.repository.CandleRepository; +import com.rods.backtestingstrategies.repository.StockSymbolRepository; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.stereotype.Service; +import yahoofinance.histquotes.HistoricalQuote; + +import java.io.IOException; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.*; + +@Service +public class MarketDataService { + + private final YahooFinanceService yahooFinanceService; + private final CandleRepository candleRepository; + private final StockSymbolRepository symbolRepository; + + public MarketDataService(YahooFinanceService yahooFinanceService, + CandleRepository candleRepository, + StockSymbolRepository symbolRepository) { + this.yahooFinanceService = yahooFinanceService; + this.candleRepository = candleRepository; + this.symbolRepository = symbolRepository; + } + + /** + * Sync daily candle data from Yahoo Finance into the database. + * Only inserts candles for dates not yet stored. + */ + public void syncDailyCandles(String symbol) { + System.out.println("Sync Method Called for: " + symbol); + + try { + // Fetch 5 years of historical data for comprehensive backtesting + Calendar from = Calendar.getInstance(); + from.add(Calendar.YEAR, -5); + Calendar to = Calendar.getInstance(); + + List history = yahooFinanceService.getHistoricalData(symbol, from, to); + + if (history == null || history.isEmpty()) { + System.err.println("No historical data returned for: " + symbol); + return; + } + + // Fetch existing candle dates for this symbol + Set existingDates = new HashSet<>(candleRepository.findExistingDates(symbol)); + + List newCandles = new ArrayList<>(); + + for (HistoricalQuote quote : history) { + if (quote.getDate() == null || quote.getClose() == null) { + continue; + } + + LocalDate date = quote.getDate().getTime().toInstant() + .atZone(ZoneId.systemDefault()).toLocalDate(); + + // Skip if candle already exists + if (existingDates.contains(date)) { + continue; + } + + Candle candle = new Candle(); + candle.setSymbol(symbol.toUpperCase()); + candle.setDate(date); + candle.setOpenPrice(toDouble(quote.getOpen())); + candle.setHighPrice(toDouble(quote.getHigh())); + candle.setLowPrice(toDouble(quote.getLow())); + candle.setClosePrice(toDouble(quote.getClose())); + candle.setVolume(quote.getVolume() != null ? quote.getVolume() : 0L); + + newCandles.add(candle); + } + + // Bulk insert + if (!newCandles.isEmpty()) { + try { + candleRepository.saveAll(newCandles); + System.out.println("Inserted " + newCandles.size() + " new candles for " + symbol); + } catch (DataIntegrityViolationException e) { + System.err.println("Duplicate candles skipped for: " + symbol); + } + } + } catch (IOException e) { + System.err.println("Failed to fetch data from Yahoo Finance for: " + symbol + " - " + e.getMessage()); + } + } + + /** + * Get candles for a symbol. Fetches from DB first, syncs from API if needed. + */ + public List getCandles(String symbol) { + String upperSymbol = symbol.toUpperCase(); + List candles = candleRepository.findBySymbolOrderByDateAsc(upperSymbol); + + // CASE 1: No data in DB → sync + if (candles.isEmpty()) { + syncDailyCandles(upperSymbol); + return candleRepository.findBySymbolOrderByDateAsc(upperSymbol); + } + + // CASE 2: Data exists → check if stale (last candle > 1 day old) + LocalDate latestDate = candles.getLast().getDate(); + if (LocalDate.now().isAfter(latestDate.plusDays(1))) { + syncDailyCandles(upperSymbol); + candles = candleRepository.findBySymbolOrderByDateAsc(upperSymbol); + } + + return candles; + } + + /** + * Search stock symbols from the local pre-seeded database. + * Supports fuzzy matching on symbol and company name. + */ + public List searchSymbols(String query) { + return symbolRepository.searchSymbols(query); + } + + /** + * Search symbols filtered by exchange + */ + public List searchSymbolsByExchange(String query, String exchange) { + return symbolRepository.searchSymbolsByExchange(query, exchange); + } + + /** + * Get all symbols for a specific exchange + */ + public List getSymbolsByExchange(String exchange) { + return symbolRepository.findByExchange(exchange); + } + + /** + * Safe BigDecimal to double conversion + */ + private double toDouble(BigDecimal value) { + return value != null ? value.doubleValue() : 0.0; + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/service/TickerSeederService.java b/src/main/java/com/rods/backtestingstrategies/service/TickerSeederService.java new file mode 100644 index 0000000000000000000000000000000000000000..d9215b47ef9293bcb3d703f6e0370d841c15ae6d --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/service/TickerSeederService.java @@ -0,0 +1,111 @@ +package com.rods.backtestingstrategies.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.rods.backtestingstrategies.entity.StockSymbol; +import com.rods.backtestingstrategies.repository.StockSymbolRepository; +import jakarta.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.io.InputStream; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +/** + * Service to populate the stock_symbols table on startup + * from a curated JSON file of global exchange tickers. + * + * Covers: NASDAQ, NYSE/S&P 500, NSE (India), BSE (India), LSE (UK), TSE (Japan). + * Runs only when tickers are missing from the DB. + */ +@Service +public class TickerSeederService { + + private final StockSymbolRepository symbolRepository; + private final ObjectMapper objectMapper; + + @Value("${ticker.seeder.enabled:true}") + private boolean seederEnabled; + + public TickerSeederService(StockSymbolRepository symbolRepository) { + this.symbolRepository = symbolRepository; + this.objectMapper = new ObjectMapper(); + } + + @PostConstruct + public void seedTickers() { + if (!seederEnabled) { + System.out.println("Ticker seeder is disabled."); + return; + } + + long existingCount = symbolRepository.count(); + if (existingCount > 0) { + System.out.println("Ticker database already populated with " + existingCount + " symbols. Skipping seed."); + return; + } + + System.out.println("Seeding ticker database from ticker_data.json..."); + + try { + ClassPathResource resource = new ClassPathResource("ticker_data.json"); + InputStream inputStream = resource.getInputStream(); + JsonNode root = objectMapper.readTree(inputStream); + JsonNode exchanges = root.get("exchanges"); + + List allSymbols = new ArrayList<>(); + LocalDateTime now = LocalDateTime.now(); + + for (JsonNode exchange : exchanges) { + String exchangeName = exchange.get("name").asText(); + String region = exchange.get("region").asText(); + String currency = exchange.get("currency").asText(); + String timezone = exchange.get("timezone").asText(); + String marketOpen = exchange.get("marketOpen").asText(); + String marketClose = exchange.get("marketClose").asText(); + + JsonNode tickers = exchange.get("tickers"); + for (JsonNode ticker : tickers) { + StockSymbol symbol = new StockSymbol(); + symbol.setSymbol(ticker.get("symbol").asText()); + symbol.setName(ticker.get("name").asText()); + symbol.setType("Equity"); + symbol.setExchange(exchangeName); + symbol.setRegion(region); + symbol.setCurrency(currency); + symbol.setTimezone(timezone); + symbol.setMarketOpen(marketOpen); + symbol.setMarketClose(marketClose); + symbol.setSector(ticker.has("sector") ? ticker.get("sector").asText() : null); + symbol.setIndustry(ticker.has("industry") ? ticker.get("industry").asText() : null); + symbol.setMatchScore(1.0); + symbol.setLastFetched(now); + symbol.setSource("TICKER_SEED"); + + allSymbols.add(symbol); + } + } + + symbolRepository.saveAll(allSymbols); + System.out.println("Successfully seeded " + allSymbols.size() + " tickers across " + + exchanges.size() + " exchanges."); + + } catch (IOException e) { + System.err.println("Failed to seed ticker data: " + e.getMessage()); + } + } + + /** + * Manual re-seed: clears all existing symbols and re-imports from JSON. + * Use this endpoint for manual updates. + */ + public int reseedTickers() { + symbolRepository.deleteAll(); + seedTickers(); + return (int) symbolRepository.count(); + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/service/YahooFinanceService.java b/src/main/java/com/rods/backtestingstrategies/service/YahooFinanceService.java new file mode 100644 index 0000000000000000000000000000000000000000..36c5ffbdf8b7b959b5fca87ef031f982e9fa0413 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/service/YahooFinanceService.java @@ -0,0 +1,156 @@ +package com.rods.backtestingstrategies.service; + +import org.springframework.stereotype.Service; +import yahoofinance.Stock; +import yahoofinance.YahooFinance; +import yahoofinance.histquotes.HistoricalQuote; +import yahoofinance.histquotes.Interval; +import yahoofinance.quotes.stock.StockQuote; +import yahoofinance.quotes.stock.StockStats; + +import java.io.IOException; +import java.util.Calendar; +import java.util.List; +import java.util.Map; + +/** + * Service wrapping the Yahoo Finance API. + * No API key required. No enforced rate limits. + */ +@Service +public class YahooFinanceService { + + static { + // Set standard user-agent so Yahoo doesn't reject as bot with 429 Error + System.setProperty("http.agent", + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"); + } + + /** + * Fetch full stock info (quote, stats, dividend) + */ + public Stock getStock(String symbol) throws IOException { + return YahooFinance.get(symbol); + } + + /** + * Fetch stock with full historical data (default: 1 year, daily) + */ + public Stock getStockWithHistory(String symbol) throws IOException { + return YahooFinance.get(symbol, true); + } + + /** + * Fetch historical daily data for a custom date range using v8 API (Bypasses + * 429) + */ + public List getHistoricalData(String symbol, Calendar from, Calendar to) throws IOException { + String urlString = String.format( + "https://query1.finance.yahoo.com/v8/finance/chart/%s?period1=%d&period2=%d&interval=1d", + symbol, from.getTimeInMillis() / 1000, to.getTimeInMillis() / 1000); + + return fetchHistoryFromV8(symbol, urlString); + } + + /** + * Fetch historical daily data with default lookback (1 year) + */ + public List getHistoricalData(String symbol) throws IOException { + Calendar from = Calendar.getInstance(); + from.add(Calendar.YEAR, -1); + Calendar to = Calendar.getInstance(); + return getHistoricalData(symbol, from, to); + } + + private List fetchHistoryFromV8(String symbol, String urlString) throws IOException { + java.util.List history = new java.util.ArrayList<>(); + try { + java.net.URL url = new java.net.URL(urlString); + java.net.HttpURLConnection request = (java.net.HttpURLConnection) url.openConnection(); + request.setRequestMethod("GET"); + request.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"); + request.connect(); + + int responseCode = request.getResponseCode(); + if (responseCode == 404) + return history; // Stock not found + + com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); + com.fasterxml.jackson.databind.JsonNode root = mapper.readTree(request.getInputStream()); + com.fasterxml.jackson.databind.JsonNode result = root.path("chart").path("result").get(0); + + if (result == null || result.isMissingNode()) + return history; + + com.fasterxml.jackson.databind.JsonNode timestampNode = result.path("timestamp"); + com.fasterxml.jackson.databind.JsonNode quoteNode = result.path("indicators").path("quote").get(0); + com.fasterxml.jackson.databind.JsonNode adjCloseNode = result.path("indicators").path("adjclose").get(0); + + if (timestampNode.isMissingNode() || quoteNode.isMissingNode()) + return history; + + for (int i = 0; i < timestampNode.size(); i++) { + long timestamp = timestampNode.get(i).asLong(); + java.util.Calendar date = java.util.Calendar.getInstance(); + date.setTimeInMillis(timestamp * 1000); + + java.math.BigDecimal open = getBigDecimal(quoteNode.path("open").get(i)); + java.math.BigDecimal high = getBigDecimal(quoteNode.path("high").get(i)); + java.math.BigDecimal low = getBigDecimal(quoteNode.path("low").get(i)); + java.math.BigDecimal close = getBigDecimal(quoteNode.path("close").get(i)); + java.math.BigDecimal adjClose = adjCloseNode != null && !adjCloseNode.isMissingNode() + ? getBigDecimal(adjCloseNode.path("adjclose").get(i)) + : close; + long volume = quoteNode.path("volume").get(i) != null ? quoteNode.path("volume").get(i).asLong() : 0L; + + if (close != null) { + history.add(new HistoricalQuote(symbol, date, open, low, high, close, adjClose, volume)); + } + } + } catch (Exception e) { + throw new IOException("Failed to fetch custom Yahoo v8 API for " + symbol, e); + } + return history; + } + + private java.math.BigDecimal getBigDecimal(com.fasterxml.jackson.databind.JsonNode node) { + if (node == null || node.isNull() || node.isMissingNode()) + return null; + return new java.math.BigDecimal(node.asText()); + } + + /** + * Fetch multiple stocks at once (single batch request) + */ + public Map getMultipleStocks(String[] symbols) throws IOException { + return YahooFinance.get(symbols); + } + + /** + * Validate if a symbol exists on Yahoo Finance + */ + public boolean isValidSymbol(String symbol) { + try { + Stock stock = YahooFinance.get(symbol); + return stock != null && stock.getQuote() != null && stock.getQuote().getPrice() != null; + } catch (IOException e) { + return false; + } + } + + /** + * Get real-time quote data + */ + public StockQuote getQuote(String symbol) throws IOException { + Stock stock = YahooFinance.get(symbol); + return stock.getQuote(); + } + + /** + * Get stock statistics (PE, EPS, market cap, etc.) + */ + public StockStats getStats(String symbol) throws IOException { + Stock stock = YahooFinance.get(symbol); + return stock.getStats(); + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/strategy/BuyAndHoldStrategy.java b/src/main/java/com/rods/backtestingstrategies/strategy/BuyAndHoldStrategy.java new file mode 100644 index 0000000000000000000000000000000000000000..7fd78e73c2556992501784e221c27a349637d85a --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/strategy/BuyAndHoldStrategy.java @@ -0,0 +1,41 @@ +package com.rods.backtestingstrategies.strategy; + +import com.rods.backtestingstrategies.entity.Candle; +import com.rods.backtestingstrategies.entity.SignalType; +import com.rods.backtestingstrategies.entity.TradeSignal; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class BuyAndHoldStrategy implements Strategy { + + @Override + public TradeSignal evaluate(List candles, int index) { + + Candle candle = candles.get(index); + + // BUY on first candle + if (index == 0) { + return TradeSignal.buy(candle); + } + + // SELL on last candle + if (index == candles.size() - 1) { + return TradeSignal.sell(candle); + } + + // Otherwise HOLD + return TradeSignal.hold(); + } + + @Override + public StrategyType getType() { + return StrategyType.BUY_AND_HOLD; + } + + @Override + public String getName() { + return "Buy & Hold"; + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/strategy/MacdStrategy.java b/src/main/java/com/rods/backtestingstrategies/strategy/MacdStrategy.java new file mode 100644 index 0000000000000000000000000000000000000000..6edfbec72cb6e7413045e5a59f78248cb2dcaf56 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/strategy/MacdStrategy.java @@ -0,0 +1,141 @@ +package com.rods.backtestingstrategies.strategy; + +import com.rods.backtestingstrategies.entity.Candle; +import com.rods.backtestingstrategies.entity.TradeSignal; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * MACD (Moving Average Convergence Divergence) Strategy. + * + * MACD Line = EMA(fastPeriod) - EMA(slowPeriod) + * Signal Line = EMA(signalPeriod) of MACD Line + * + * BUY → MACD crosses above Signal Line + * SELL → MACD crosses below Signal Line + */ +@Component +public class MacdStrategy implements Strategy { + + private final int fastPeriod; + private final int slowPeriod; + private final int signalPeriod; + + public MacdStrategy() { + // Standard MACD(12, 26, 9) + this.fastPeriod = 12; + this.slowPeriod = 26; + this.signalPeriod = 9; + } + + public MacdStrategy(int fastPeriod, int slowPeriod, int signalPeriod) { + this.fastPeriod = fastPeriod; + this.slowPeriod = slowPeriod; + this.signalPeriod = signalPeriod; + } + + @Override + public TradeSignal evaluate(List candles, int index) { + + // Need enough data: slowPeriod + signalPeriod candles minimum + int minRequired = slowPeriod + signalPeriod; + if (index < minRequired) { + return TradeSignal.hold(); + } + + Candle candle = candles.get(index); + + // Calculate MACD and Signal for current and previous index + double currMacd = calculateMacd(candles, index); + double prevMacd = calculateMacd(candles, index - 1); + + double currSignal = calculateSignalLine(candles, index); + double prevSignal = calculateSignalLine(candles, index - 1); + + // MACD crosses above Signal → BUY + if (prevMacd <= prevSignal && currMacd > currSignal) { + return TradeSignal.buy(candle); + } + + // MACD crosses below Signal → SELL + if (prevMacd >= prevSignal && currMacd < currSignal) { + return TradeSignal.sell(candle); + } + + return TradeSignal.hold(); + } + + /** + * Calculate MACD line = EMA(fast) - EMA(slow) + */ + private double calculateMacd(List candles, int index) { + double fastEma = calculateEma(candles, index, fastPeriod); + double slowEma = calculateEma(candles, index, slowPeriod); + return fastEma - slowEma; + } + + /** + * Calculate Signal line = EMA(signalPeriod) of MACD values + */ + private double calculateSignalLine(List candles, int index) { + // We need 'signalPeriod' MACD values ending at 'index' + double multiplier = 2.0 / (signalPeriod + 1); + + // Seed with the oldest MACD value in the window + double signalEma = calculateMacd(candles, index - signalPeriod + 1); + + for (int i = index - signalPeriod + 2; i <= index; i++) { + double macdValue = calculateMacd(candles, i); + signalEma = (macdValue - signalEma) * multiplier + signalEma; + } + + return signalEma; + } + + /** + * Calculate Exponential Moving Average at a given index. + * Uses the standard EMA formula with SMA as the seed value. + */ + private double calculateEma(List candles, int index, int period) { + if (index < period - 1) { + // Not enough data, return SMA + return sma(candles, index, Math.min(period, index + 1)); + } + + double multiplier = 2.0 / (period + 1); + + // Seed EMA with SMA of the first 'period' candles + double ema = sma(candles, period - 1, period); + + // Calculate EMA from period to index + for (int i = period; i <= index; i++) { + double price = candles.get(i).getClosePrice(); + ema = (price - ema) * multiplier + ema; + } + + return ema; + } + + /** + * Simple Moving Average helper + */ + private double sma(List candles, int endIndex, int period) { + double sum = 0.0; + int start = Math.max(0, endIndex - period + 1); + for (int i = start; i <= endIndex; i++) { + sum += candles.get(i).getClosePrice(); + } + return sum / (endIndex - start + 1); + } + + @Override + public String getName() { + return "MACD (" + fastPeriod + ", " + slowPeriod + ", " + signalPeriod + ")"; + } + + @Override + public StrategyType getType() { + return StrategyType.MACD; + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/strategy/RsiStrategy.java b/src/main/java/com/rods/backtestingstrategies/strategy/RsiStrategy.java new file mode 100644 index 0000000000000000000000000000000000000000..00145f3690785b8eac45f16a9da216fbf0f2c9f5 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/strategy/RsiStrategy.java @@ -0,0 +1,78 @@ +package com.rods.backtestingstrategies.strategy; + +import com.rods.backtestingstrategies.entity.Candle; +import com.rods.backtestingstrategies.entity.TradeSignal; +import com.rods.backtestingstrategies.entity.SignalType; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class RsiStrategy implements Strategy { + + private static final int PERIOD = 14; + private static final double OVERSOLD = 30.0; + private static final double OVERBOUGHT = 70.0; + + @Override + public TradeSignal evaluate(List candles, int index) { + + // Not enough data + if (index < PERIOD) { + return TradeSignal.hold(); + } + + double rsi = calculateRsi(candles, index); + + Candle candle = candles.get(index); + + if (rsi < OVERSOLD) { + return TradeSignal.buy(candle); + } + + if (rsi > OVERBOUGHT) { + return TradeSignal.sell(candle); + } + + return TradeSignal.hold(); + } + + @Override + public StrategyType getType() { + return StrategyType.RSI; + } + + @Override + public String getName() { + return "RSI Mean Reversion (14)"; + } + + /* ========================== + RSI Calculation + ========================== */ + + private double calculateRsi(List candles, int index) { + + double gain = 0.0; + double loss = 0.0; + + for (int i = index - PERIOD + 1; i <= index; i++) { + double change = + candles.get(i).getClosePrice() + - candles.get(i - 1).getClosePrice(); + + if (change > 0) { + gain += change; + } else { + loss -= change; + } + } + + if (loss == 0) { + return 100.0; + } + + double rs = gain / loss; + return 100.0 - (100.0 / (1.0 + rs)); + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/strategy/SmaCrossoverStrategy.java b/src/main/java/com/rods/backtestingstrategies/strategy/SmaCrossoverStrategy.java new file mode 100644 index 0000000000000000000000000000000000000000..8cd862360c3775d3ca977ed8ec849aa1137d7417 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/strategy/SmaCrossoverStrategy.java @@ -0,0 +1,86 @@ +package com.rods.backtestingstrategies.strategy; + +import com.rods.backtestingstrategies.entity.Candle; +import com.rods.backtestingstrategies.entity.TradeSignal; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class SmaCrossoverStrategy implements Strategy { + + private final int shortPeriod; + private final int longPeriod; + + public SmaCrossoverStrategy() { + // Default values (can later be injected / configured) + this.shortPeriod = 20; + this.longPeriod = 50; + } + + public SmaCrossoverStrategy(int shortPeriod, int longPeriod) { + if (shortPeriod >= longPeriod) { + throw new IllegalArgumentException("Short period must be less than long period"); + } + this.shortPeriod = shortPeriod; + this.longPeriod = longPeriod; + } + + @Override + public TradeSignal evaluate(List candles, int index) { + + Candle candle = candles.get(index); + + // Not enough data to evaluate → HOLD with candle context + if (index < longPeriod) { + return TradeSignal.hold(); + } + + double prevShortSma = sma(candles, index - 1, shortPeriod); + double prevLongSma = sma(candles, index - 1, longPeriod); + + double currShortSma = sma(candles, index, shortPeriod); + double currLongSma = sma(candles, index, longPeriod); + + // Cross up → BUY + if (prevShortSma <= prevLongSma && currShortSma > currLongSma) { + return TradeSignal.buy(candle); + } + + // Cross down → SELL + if (prevShortSma >= prevLongSma && currShortSma < currLongSma) { + return TradeSignal.sell(candle); + } + + // No crossover → HOLD + return TradeSignal.hold(); + } + + + + /** + * Simple Moving Average at a specific index + */ + private double sma(List candles, int index, int period) { + double sum = 0.0; + for (int i = index - period + 1; i <= index; i++) { + sum += candles.get(i).getClosePrice(); + } + return sum / period; + } + + + + @Override + public String getName() { + return "SMA Crossover (" + shortPeriod + ", " + longPeriod + ")"; + } + + + @Override + public StrategyType getType() { + return StrategyType.SMA; + } + + +} diff --git a/src/main/java/com/rods/backtestingstrategies/strategy/Strategy.java b/src/main/java/com/rods/backtestingstrategies/strategy/Strategy.java new file mode 100644 index 0000000000000000000000000000000000000000..a69bbafd27ca5a2a31687f0f347e050fd5596c5a --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/strategy/Strategy.java @@ -0,0 +1,29 @@ +package com.rods.backtestingstrategies.strategy; + +import com.rods.backtestingstrategies.entity.Candle; +import com.rods.backtestingstrategies.entity.TradeSignal; + +import java.util.List; + +public interface Strategy { + + /** + * Evaluate market state at a given candle index + * and return a trading signal. + * + * @param candles ordered historical candles + * @param index current candle index (time step) + * @return TradeSignal BUY / SELL / HOLD + */ + + TradeSignal evaluate(List candles, int index); + + /** + * Human-readable name of the strategy + */ + String getName(); + + // Type of strategy being implemented + StrategyType getType(); + +} diff --git a/src/main/java/com/rods/backtestingstrategies/strategy/StrategyFactory.java b/src/main/java/com/rods/backtestingstrategies/strategy/StrategyFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..7bddadf3188116593f04de50c223f3d90903e0a1 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/strategy/StrategyFactory.java @@ -0,0 +1,37 @@ +package com.rods.backtestingstrategies.strategy; + +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Component +public class StrategyFactory { + + +// Finds all Strategy beans +// +// Injects them as a List +// +// Factory maps them by StrategyType + + + private final Map strategies; + + public StrategyFactory(List strategyList) { + this.strategies = strategyList.stream() + .collect(Collectors.toMap( + Strategy::getType, + s -> s + )); + } + + public Strategy getStrategy(StrategyType type) { + Strategy strategy = strategies.get(type); + if (strategy == null) { + throw new IllegalArgumentException("Unsupported strategy: " + type); + } + return strategy; + } +} diff --git a/src/main/java/com/rods/backtestingstrategies/strategy/StrategyType.java b/src/main/java/com/rods/backtestingstrategies/strategy/StrategyType.java new file mode 100644 index 0000000000000000000000000000000000000000..9d641c8ec1def55d5fc1078563a3b95038e9e998 --- /dev/null +++ b/src/main/java/com/rods/backtestingstrategies/strategy/StrategyType.java @@ -0,0 +1,8 @@ +package com.rods.backtestingstrategies.strategy; + +public enum StrategyType { + SMA, + RSI, + MACD, + BUY_AND_HOLD +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..ab0cb176020bebdf51086de0b17c72aa488eba92 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,30 @@ +spring: + application: + name: BacktestingStrategies + + datasource: + url: ${DB_URL} + username: ${DB_USERNAME} + password: ${DB_PASSWORD} + + jpa: + hibernate: + ddl-auto: ${JPA_DDL_AUTO:update} + show-sql: ${JPA_SHOW_SQL:true} + properties: + hibernate: + format_sql: true + +# Ticker seeder configuration +ticker: + seeder: + enabled: ${TICKER_SEEDER_ENABLED:true} + +server: + tomcat: + basedir: ${java.io.tmpdir}/tomcat + +jwt: + # 256-bit Base64 secret --> include it in the environment variables + secret: ${JWT_SECRET} + expiration: 86400000 # 24 hours in milliseconds --> TOKEN_EXPIRY \ No newline at end of file diff --git a/src/main/resources/ticker_data.json b/src/main/resources/ticker_data.json new file mode 100644 index 0000000000000000000000000000000000000000..2f84decd4877abdf9900f63389503f3ad3ff3641 --- /dev/null +++ b/src/main/resources/ticker_data.json @@ -0,0 +1,244 @@ +{ + "exchanges": [ + { + "name": "NASDAQ", + "region": "United States", + "currency": "USD", + "timezone": "US/Eastern", + "marketOpen": "09:30", + "marketClose": "16:00", + "tickers": [ + {"symbol": "AAPL", "name": "Apple Inc.", "sector": "Technology", "industry": "Consumer Electronics"}, + {"symbol": "MSFT", "name": "Microsoft Corporation", "sector": "Technology", "industry": "Software"}, + {"symbol": "AMZN", "name": "Amazon.com Inc.", "sector": "Consumer Cyclical", "industry": "Internet Retail"}, + {"symbol": "GOOGL", "name": "Alphabet Inc. (Class A)", "sector": "Technology", "industry": "Internet Services"}, + {"symbol": "GOOG", "name": "Alphabet Inc. (Class C)", "sector": "Technology", "industry": "Internet Services"}, + {"symbol": "META", "name": "Meta Platforms Inc.", "sector": "Technology", "industry": "Social Media"}, + {"symbol": "TSLA", "name": "Tesla Inc.", "sector": "Consumer Cyclical", "industry": "Auto Manufacturers"}, + {"symbol": "NVDA", "name": "NVIDIA Corporation", "sector": "Technology", "industry": "Semiconductors"}, + {"symbol": "AVGO", "name": "Broadcom Inc.", "sector": "Technology", "industry": "Semiconductors"}, + {"symbol": "ADBE", "name": "Adobe Inc.", "sector": "Technology", "industry": "Software"}, + {"symbol": "NFLX", "name": "Netflix Inc.", "sector": "Communication Services", "industry": "Entertainment"}, + {"symbol": "CSCO", "name": "Cisco Systems Inc.", "sector": "Technology", "industry": "Networking"}, + {"symbol": "INTC", "name": "Intel Corporation", "sector": "Technology", "industry": "Semiconductors"}, + {"symbol": "AMD", "name": "Advanced Micro Devices Inc.", "sector": "Technology", "industry": "Semiconductors"}, + {"symbol": "QCOM", "name": "Qualcomm Inc.", "sector": "Technology", "industry": "Semiconductors"}, + {"symbol": "TXN", "name": "Texas Instruments Inc.", "sector": "Technology", "industry": "Semiconductors"}, + {"symbol": "PYPL", "name": "PayPal Holdings Inc.", "sector": "Financial Services", "industry": "Payments"}, + {"symbol": "COST", "name": "Costco Wholesale Corporation", "sector": "Consumer Defensive", "industry": "Retail"}, + {"symbol": "PEP", "name": "PepsiCo Inc.", "sector": "Consumer Defensive", "industry": "Beverages"}, + {"symbol": "CMCSA", "name": "Comcast Corporation", "sector": "Communication Services", "industry": "Telecom"}, + {"symbol": "SBUX", "name": "Starbucks Corporation", "sector": "Consumer Cyclical", "industry": "Restaurants"}, + {"symbol": "INTU", "name": "Intuit Inc.", "sector": "Technology", "industry": "Software"}, + {"symbol": "ISRG", "name": "Intuitive Surgical Inc.", "sector": "Healthcare", "industry": "Medical Devices"}, + {"symbol": "AMGN", "name": "Amgen Inc.", "sector": "Healthcare", "industry": "Biotechnology"}, + {"symbol": "GILD", "name": "Gilead Sciences Inc.", "sector": "Healthcare", "industry": "Biotechnology"}, + {"symbol": "BKNG", "name": "Booking Holdings Inc.", "sector": "Consumer Cyclical", "industry": "Travel"}, + {"symbol": "ADP", "name": "Automatic Data Processing Inc.", "sector": "Technology", "industry": "Software"}, + {"symbol": "MDLZ", "name": "Mondelez International Inc.", "sector": "Consumer Defensive", "industry": "Food"}, + {"symbol": "REGN", "name": "Regeneron Pharmaceuticals Inc.", "sector": "Healthcare", "industry": "Biotechnology"}, + {"symbol": "VRTX", "name": "Vertex Pharmaceuticals Inc.", "sector": "Healthcare", "industry": "Biotechnology"}, + {"symbol": "LRCX", "name": "Lam Research Corporation", "sector": "Technology", "industry": "Semiconductor Equipment"}, + {"symbol": "KLAC", "name": "KLA Corporation", "sector": "Technology", "industry": "Semiconductor Equipment"}, + {"symbol": "MRVL", "name": "Marvell Technology Inc.", "sector": "Technology", "industry": "Semiconductors"}, + {"symbol": "ABNB", "name": "Airbnb Inc.", "sector": "Consumer Cyclical", "industry": "Travel"}, + {"symbol": "MU", "name": "Micron Technology Inc.", "sector": "Technology", "industry": "Semiconductors"}, + {"symbol": "SNPS", "name": "Synopsys Inc.", "sector": "Technology", "industry": "EDA Software"}, + {"symbol": "CDNS", "name": "Cadence Design Systems Inc.", "sector": "Technology", "industry": "EDA Software"}, + {"symbol": "FTNT", "name": "Fortinet Inc.", "sector": "Technology", "industry": "Cybersecurity"}, + {"symbol": "CRWD", "name": "CrowdStrike Holdings Inc.", "sector": "Technology", "industry": "Cybersecurity"}, + {"symbol": "PANW", "name": "Palo Alto Networks Inc.", "sector": "Technology", "industry": "Cybersecurity"}, + {"symbol": "MELI", "name": "MercadoLibre Inc.", "sector": "Consumer Cyclical", "industry": "Internet Retail"}, + {"symbol": "WDAY", "name": "Workday Inc.", "sector": "Technology", "industry": "Software"}, + {"symbol": "ORLY", "name": "O'Reilly Automotive Inc.", "sector": "Consumer Cyclical", "industry": "Auto Parts"}, + {"symbol": "DXCM", "name": "DexCom Inc.", "sector": "Healthcare", "industry": "Medical Devices"}, + {"symbol": "ZS", "name": "Zscaler Inc.", "sector": "Technology", "industry": "Cybersecurity"}, + {"symbol": "TEAM", "name": "Atlassian Corporation", "sector": "Technology", "industry": "Software"}, + {"symbol": "LULU", "name": "Lululemon Athletica Inc.", "sector": "Consumer Cyclical", "industry": "Apparel"}, + {"symbol": "MRNA", "name": "Moderna Inc.", "sector": "Healthcare", "industry": "Biotechnology"}, + {"symbol": "COIN", "name": "Coinbase Global Inc.", "sector": "Financial Services", "industry": "Crypto Exchange"}, + {"symbol": "ROKU", "name": "Roku Inc.", "sector": "Technology", "industry": "Streaming"} + ] + }, + { + "name": "NYSE", + "region": "United States", + "currency": "USD", + "timezone": "US/Eastern", + "marketOpen": "09:30", + "marketClose": "16:00", + "tickers": [ + {"symbol": "BRK-B", "name": "Berkshire Hathaway Inc. (Class B)", "sector": "Financial Services", "industry": "Conglomerate"}, + {"symbol": "JPM", "name": "JPMorgan Chase & Co.", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "V", "name": "Visa Inc.", "sector": "Financial Services", "industry": "Payments"}, + {"symbol": "JNJ", "name": "Johnson & Johnson", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "UNH", "name": "UnitedHealth Group Inc.", "sector": "Healthcare", "industry": "Health Insurance"}, + {"symbol": "WMT", "name": "Walmart Inc.", "sector": "Consumer Defensive", "industry": "Retail"}, + {"symbol": "MA", "name": "Mastercard Inc.", "sector": "Financial Services", "industry": "Payments"}, + {"symbol": "PG", "name": "Procter & Gamble Co.", "sector": "Consumer Defensive", "industry": "Household Products"}, + {"symbol": "HD", "name": "The Home Depot Inc.", "sector": "Consumer Cyclical", "industry": "Home Improvement"}, + {"symbol": "XOM", "name": "Exxon Mobil Corporation", "sector": "Energy", "industry": "Oil & Gas"}, + {"symbol": "CVX", "name": "Chevron Corporation", "sector": "Energy", "industry": "Oil & Gas"}, + {"symbol": "KO", "name": "The Coca-Cola Company", "sector": "Consumer Defensive", "industry": "Beverages"}, + {"symbol": "LLY", "name": "Eli Lilly and Company", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "MRK", "name": "Merck & Co. Inc.", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "PFE", "name": "Pfizer Inc.", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "ABBV", "name": "AbbVie Inc.", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "BAC", "name": "Bank of America Corporation", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "DIS", "name": "The Walt Disney Company", "sector": "Communication Services", "industry": "Entertainment"}, + {"symbol": "CRM", "name": "Salesforce Inc.", "sector": "Technology", "industry": "Software"}, + {"symbol": "NKE", "name": "Nike Inc.", "sector": "Consumer Cyclical", "industry": "Apparel"}, + {"symbol": "TMO", "name": "Thermo Fisher Scientific Inc.", "sector": "Healthcare", "industry": "Life Sciences"}, + {"symbol": "ACN", "name": "Accenture plc", "sector": "Technology", "industry": "IT Services"}, + {"symbol": "DHR", "name": "Danaher Corporation", "sector": "Healthcare", "industry": "Diagnostics"}, + {"symbol": "ORCL", "name": "Oracle Corporation", "sector": "Technology", "industry": "Software"}, + {"symbol": "ABT", "name": "Abbott Laboratories", "sector": "Healthcare", "industry": "Medical Devices"}, + {"symbol": "VZ", "name": "Verizon Communications Inc.", "sector": "Communication Services", "industry": "Telecom"}, + {"symbol": "T", "name": "AT&T Inc.", "sector": "Communication Services", "industry": "Telecom"}, + {"symbol": "NEE", "name": "NextEra Energy Inc.", "sector": "Utilities", "industry": "Renewable Energy"}, + {"symbol": "LOW", "name": "Lowe's Companies Inc.", "sector": "Consumer Cyclical", "industry": "Home Improvement"}, + {"symbol": "UNP", "name": "Union Pacific Corporation", "sector": "Industrials", "industry": "Railroads"}, + {"symbol": "SPGI", "name": "S&P Global Inc.", "sector": "Financial Services", "industry": "Financial Data"}, + {"symbol": "GS", "name": "Goldman Sachs Group Inc.", "sector": "Financial Services", "industry": "Investment Banking"}, + {"symbol": "MS", "name": "Morgan Stanley", "sector": "Financial Services", "industry": "Investment Banking"}, + {"symbol": "BLK", "name": "BlackRock Inc.", "sector": "Financial Services", "industry": "Asset Management"}, + {"symbol": "CAT", "name": "Caterpillar Inc.", "sector": "Industrials", "industry": "Machinery"}, + {"symbol": "BA", "name": "The Boeing Company", "sector": "Industrials", "industry": "Aerospace"}, + {"symbol": "GE", "name": "GE Aerospace", "sector": "Industrials", "industry": "Aerospace"}, + {"symbol": "RTX", "name": "RTX Corporation", "sector": "Industrials", "industry": "Defense"}, + {"symbol": "IBM", "name": "International Business Machines", "sector": "Technology", "industry": "IT Services"}, + {"symbol": "MMM", "name": "3M Company", "sector": "Industrials", "industry": "Diversified Industrials"}, + {"symbol": "DE", "name": "Deere & Company", "sector": "Industrials", "industry": "Farm Equipment"}, + {"symbol": "UPS", "name": "United Parcel Service Inc.", "sector": "Industrials", "industry": "Logistics"}, + {"symbol": "SYK", "name": "Stryker Corporation", "sector": "Healthcare", "industry": "Medical Devices"}, + {"symbol": "MDT", "name": "Medtronic plc", "sector": "Healthcare", "industry": "Medical Devices"}, + {"symbol": "SCHW", "name": "Charles Schwab Corporation", "sector": "Financial Services", "industry": "Brokerage"}, + {"symbol": "C", "name": "Citigroup Inc.", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "WFC", "name": "Wells Fargo & Company", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "AXP", "name": "American Express Company", "sector": "Financial Services", "industry": "Credit Cards"}, + {"symbol": "F", "name": "Ford Motor Company", "sector": "Consumer Cyclical", "industry": "Auto Manufacturers"}, + {"symbol": "GM", "name": "General Motors Company", "sector": "Consumer Cyclical", "industry": "Auto Manufacturers"} + ] + }, + { + "name": "NSE", + "region": "India", + "currency": "INR", + "timezone": "Asia/Kolkata", + "marketOpen": "09:15", + "marketClose": "15:30", + "tickers": [ + {"symbol": "RELIANCE.NS", "name": "Reliance Industries Limited", "sector": "Energy", "industry": "Conglomerate"}, + {"symbol": "TCS.NS", "name": "Tata Consultancy Services", "sector": "Technology", "industry": "IT Services"}, + {"symbol": "INFY.NS", "name": "Infosys Limited", "sector": "Technology", "industry": "IT Services"}, + {"symbol": "HDFCBANK.NS", "name": "HDFC Bank Limited", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "ICICIBANK.NS", "name": "ICICI Bank Limited", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "HINDUNILVR.NS", "name": "Hindustan Unilever Limited", "sector": "Consumer Defensive", "industry": "FMCG"}, + {"symbol": "ITC.NS", "name": "ITC Limited", "sector": "Consumer Defensive", "industry": "FMCG"}, + {"symbol": "SBIN.NS", "name": "State Bank of India", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "BHARTIARTL.NS", "name": "Bharti Airtel Limited", "sector": "Communication Services", "industry": "Telecom"}, + {"symbol": "KOTAKBANK.NS", "name": "Kotak Mahindra Bank", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "LT.NS", "name": "Larsen & Toubro Limited", "sector": "Industrials", "industry": "Engineering"}, + {"symbol": "AXISBANK.NS", "name": "Axis Bank Limited", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "WIPRO.NS", "name": "Wipro Limited", "sector": "Technology", "industry": "IT Services"}, + {"symbol": "HCLTECH.NS", "name": "HCL Technologies Limited", "sector": "Technology", "industry": "IT Services"}, + {"symbol": "ASIANPAINT.NS", "name": "Asian Paints Limited", "sector": "Materials", "industry": "Paints"}, + {"symbol": "MARUTI.NS", "name": "Maruti Suzuki India Limited", "sector": "Consumer Cyclical", "industry": "Auto Manufacturers"}, + {"symbol": "TATAMOTORS.NS", "name": "Tata Motors Limited", "sector": "Consumer Cyclical", "industry": "Auto Manufacturers"}, + {"symbol": "SUNPHARMA.NS", "name": "Sun Pharmaceutical Industries", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "BAJFINANCE.NS", "name": "Bajaj Finance Limited", "sector": "Financial Services", "industry": "NBFC"}, + {"symbol": "TATASTEEL.NS", "name": "Tata Steel Limited", "sector": "Materials", "industry": "Steel"}, + {"symbol": "TITAN.NS", "name": "Titan Company Limited", "sector": "Consumer Cyclical", "industry": "Jewelry"}, + {"symbol": "NESTLEIND.NS", "name": "Nestle India Limited", "sector": "Consumer Defensive", "industry": "Food"}, + {"symbol": "ULTRACEMCO.NS", "name": "UltraTech Cement Limited", "sector": "Materials", "industry": "Cement"}, + {"symbol": "POWERGRID.NS", "name": "Power Grid Corporation of India", "sector": "Utilities", "industry": "Power"}, + {"symbol": "NTPC.NS", "name": "NTPC Limited", "sector": "Utilities", "industry": "Power"}, + {"symbol": "ONGC.NS", "name": "Oil & Natural Gas Corporation", "sector": "Energy", "industry": "Oil & Gas"}, + {"symbol": "JSWSTEEL.NS", "name": "JSW Steel Limited", "sector": "Materials", "industry": "Steel"}, + {"symbol": "TECHM.NS", "name": "Tech Mahindra Limited", "sector": "Technology", "industry": "IT Services"}, + {"symbol": "DRREDDY.NS", "name": "Dr. Reddy's Laboratories", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "CIPLA.NS", "name": "Cipla Limited", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "M&M.NS", "name": "Mahindra & Mahindra Limited", "sector": "Consumer Cyclical", "industry": "Auto Manufacturers"}, + {"symbol": "DIVISLAB.NS", "name": "Divi's Laboratories Limited", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "ADANIENT.NS", "name": "Adani Enterprises Limited", "sector": "Industrials", "industry": "Conglomerate"}, + {"symbol": "ADANIPORTS.NS", "name": "Adani Ports and SEZ Limited", "sector": "Industrials", "industry": "Ports"}, + {"symbol": "COALINDIA.NS", "name": "Coal India Limited", "sector": "Energy", "industry": "Coal"}, + {"symbol": "EICHERMOT.NS", "name": "Eicher Motors Limited", "sector": "Consumer Cyclical", "industry": "Auto Manufacturers"}, + {"symbol": "HEROMOTOCO.NS", "name": "Hero MotoCorp Limited", "sector": "Consumer Cyclical", "industry": "Auto Manufacturers"}, + {"symbol": "BAJAJFINSV.NS", "name": "Bajaj Finserv Limited", "sector": "Financial Services", "industry": "Financial Services"}, + {"symbol": "INDUSINDBK.NS", "name": "IndusInd Bank Limited", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "SBILIFE.NS", "name": "SBI Life Insurance Company", "sector": "Financial Services", "industry": "Insurance"} + ] + }, + { + "name": "BSE", + "region": "India", + "currency": "INR", + "timezone": "Asia/Kolkata", + "marketOpen": "09:15", + "marketClose": "15:30", + "tickers": [ + {"symbol": "RELIANCE.BO", "name": "Reliance Industries Limited", "sector": "Energy", "industry": "Conglomerate"}, + {"symbol": "TCS.BO", "name": "Tata Consultancy Services", "sector": "Technology", "industry": "IT Services"}, + {"symbol": "INFY.BO", "name": "Infosys Limited", "sector": "Technology", "industry": "IT Services"}, + {"symbol": "HDFCBANK.BO", "name": "HDFC Bank Limited", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "ICICIBANK.BO", "name": "ICICI Bank Limited", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "HINDUNILVR.BO", "name": "Hindustan Unilever Limited", "sector": "Consumer Defensive", "industry": "FMCG"}, + {"symbol": "ITC.BO", "name": "ITC Limited", "sector": "Consumer Defensive", "industry": "FMCG"}, + {"symbol": "SBIN.BO", "name": "State Bank of India", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "BHARTIARTL.BO", "name": "Bharti Airtel Limited", "sector": "Communication Services", "industry": "Telecom"}, + {"symbol": "LT.BO", "name": "Larsen & Toubro Limited", "sector": "Industrials", "industry": "Engineering"}, + {"symbol": "WIPRO.BO", "name": "Wipro Limited", "sector": "Technology", "industry": "IT Services"}, + {"symbol": "HCLTECH.BO", "name": "HCL Technologies Limited", "sector": "Technology", "industry": "IT Services"}, + {"symbol": "MARUTI.BO", "name": "Maruti Suzuki India Limited", "sector": "Consumer Cyclical", "industry": "Auto Manufacturers"}, + {"symbol": "TATAMOTORS.BO", "name": "Tata Motors Limited", "sector": "Consumer Cyclical", "industry": "Auto Manufacturers"}, + {"symbol": "SUNPHARMA.BO", "name": "Sun Pharmaceutical Industries", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "BAJFINANCE.BO", "name": "Bajaj Finance Limited", "sector": "Financial Services", "industry": "NBFC"}, + {"symbol": "TATASTEEL.BO", "name": "Tata Steel Limited", "sector": "Materials", "industry": "Steel"}, + {"symbol": "TITAN.BO", "name": "Titan Company Limited", "sector": "Consumer Cyclical", "industry": "Jewelry"}, + {"symbol": "ASIANPAINT.BO", "name": "Asian Paints Limited", "sector": "Materials", "industry": "Paints"}, + {"symbol": "ADANIENT.BO", "name": "Adani Enterprises Limited", "sector": "Industrials", "industry": "Conglomerate"} + ] + }, + { + "name": "LSE", + "region": "United Kingdom", + "currency": "GBP", + "timezone": "Europe/London", + "marketOpen": "08:00", + "marketClose": "16:30", + "tickers": [ + {"symbol": "SHEL.L", "name": "Shell plc", "sector": "Energy", "industry": "Oil & Gas"}, + {"symbol": "AZN.L", "name": "AstraZeneca PLC", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "HSBA.L", "name": "HSBC Holdings plc", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "ULVR.L", "name": "Unilever PLC", "sector": "Consumer Defensive", "industry": "FMCG"}, + {"symbol": "BP.L", "name": "BP p.l.c.", "sector": "Energy", "industry": "Oil & Gas"}, + {"symbol": "GSK.L", "name": "GSK plc", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "RIO.L", "name": "Rio Tinto Group", "sector": "Materials", "industry": "Mining"}, + {"symbol": "LSEG.L", "name": "London Stock Exchange Group", "sector": "Financial Services", "industry": "Exchanges"}, + {"symbol": "DGE.L", "name": "Diageo plc", "sector": "Consumer Defensive", "industry": "Beverages"}, + {"symbol": "BATS.L", "name": "British American Tobacco", "sector": "Consumer Defensive", "industry": "Tobacco"} + ] + }, + { + "name": "TSE", + "region": "Japan", + "currency": "JPY", + "timezone": "Asia/Tokyo", + "marketOpen": "09:00", + "marketClose": "15:00", + "tickers": [ + {"symbol": "7203.T", "name": "Toyota Motor Corporation", "sector": "Consumer Cyclical", "industry": "Auto Manufacturers"}, + {"symbol": "6758.T", "name": "Sony Group Corporation", "sector": "Technology", "industry": "Consumer Electronics"}, + {"symbol": "6861.T", "name": "Keyence Corporation", "sector": "Technology", "industry": "Industrial Automation"}, + {"symbol": "9984.T", "name": "SoftBank Group Corp.", "sector": "Technology", "industry": "Investments"}, + {"symbol": "6902.T", "name": "Denso Corporation", "sector": "Consumer Cyclical", "industry": "Auto Parts"}, + {"symbol": "8306.T", "name": "Mitsubishi UFJ Financial Group", "sector": "Financial Services", "industry": "Banking"}, + {"symbol": "9433.T", "name": "KDDI Corporation", "sector": "Communication Services", "industry": "Telecom"}, + {"symbol": "4502.T", "name": "Takeda Pharmaceutical Company", "sector": "Healthcare", "industry": "Pharmaceuticals"}, + {"symbol": "7741.T", "name": "HOYA Corporation", "sector": "Healthcare", "industry": "Medical Devices"}, + {"symbol": "6501.T", "name": "Hitachi Ltd.", "sector": "Technology", "industry": "Diversified Electronics"} + ] + } + ] +} diff --git a/src/test/java/com/rods/backtestingstrategies/BacktestingStrategiesApplicationTests.java b/src/test/java/com/rods/backtestingstrategies/BacktestingStrategiesApplicationTests.java new file mode 100644 index 0000000000000000000000000000000000000000..be6aec49480d8bb5c13dc14e515f14ae652cfda6 --- /dev/null +++ b/src/test/java/com/rods/backtestingstrategies/BacktestingStrategiesApplicationTests.java @@ -0,0 +1,19 @@ +package com.rods.backtestingstrategies; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest( + properties = { + "spring.autoconfigure.exclude=" + + "org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration," + + "org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration" + } +) +class BacktestingStrategiesApplicationTests { + + @Test + void contextLoads() { + } + +}