Created
November 13, 2019 23:50
-
-
Save sheland/9a80d44136e061ba91f93718230c19ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
A classic stock trading pattern happens when a 9-Day Moving Average (9-DMA) crosses the 50-Day Moving Average (50-DMA). | |
This can be indicative of a bullish or a bearish setup, depending on the direction. When the 9-DMA crosses below the 50-DMA | |
from above, it is Bearish. When the 9-DMA cross above the 50-DMA from below, it is Bullish. | |
Write a program that reads in a series of dates and prices, calculates the 9-DMA and 50-DMA, | |
then returns the dates of any bullish signals that occurred. | |
NOTE: The Moving Average cannot be calculated for a given day if there is not enough historical data to cover | |
the period in question. For example, a series of prices that begin on January 1 cannot have a 9-DMA calculated | |
before January 9 since 9 days of historical prices do not exist until January 9. Input: A series of Date|Price | |
pairs in non-localized format. Dates will follow ISO 8601 format YYYY-MM-DD. Prices will be a two-decimal value | |
with no currency indications. | |
*/ | |
function checkBullish () { | |
let prices = [] | |
let dates = [] | |
let bullish = "" | |
for (let i = 0; i < input.length; i++){ | |
dates.push(input[i].split("|").first) //capture only dates from input and push to [] | |
prices.push(input[i].split("|").last) //capture only prices from input and push to [] | |
} | |
//set beginning and end limits for 9-DMA & 50-DMA | |
let beginNineDma = 0 | |
let endNineDma = 8 | |
let beginFiftyDma = 0 | |
let endFiftyDma = 49 | |
while(endFiftyDma < prices.length - 1) { //while 50-DMA's limit is valid | |
let subarray9 = prices.splice(beginNineDma, endNineDma) //target the 9-day period | |
let sumNine = subarray9.reduce((previous, current) => current += previous) //sum to calculate avg | |
let avgNine = sumNine/subarray9.length //9-Day Moving Average | |
let subarray50 = prices.splice(beginFiftyDma, endFiftyDma) //target the 50-day period | |
let sumFifty = subarray50.reduce((previous, current) => current += previous) //sum to calculate avg | |
let avgFifty = sumFifty/subarray50.length //50-Day Moving Average | |
if(avgNine > avgFifty){ //if bullish | |
bullish = dates[endNineDma] //capture 9-DMA's last day | |
return bullish | |
} else { | |
beginNineDma = endNineDma + 1 //increment beginning and end limits for 9-DMA | |
endNineDma += 9 | |
beginFiftyDma = endFiftyDma + 1 //increment beginning and end limits for 50-DMA | |
endFiftyDma += 50 | |
} | |
} | |
} | |
if (bullish == "") { //bullish was not found | |
return null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment