Programming performance/ArthurVanLeeuwen Haskell
Jump to navigation
Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
Didn't feel like thinking at all, so this is a trivial recursive solution.
Code
main = do xs <- getContents
let cashheld = runStrategy 10000 . reverse . getDays . filter (\l -> head l /= '#') . filter (not . null) $ lines xs
putStrLn $ "Cash held: " ++ show cashheld
getDays :: [String] -> [(String,Double,Double,Double,Double,Integer,Double)]
getDays = map getDay
getDay :: String -> (String,Double,Double,Double,Double,Integer,Double)
getDay s = getDay' $ words s
where getDay' [date,open,high,low,close,volume,adjustedclose] = (date,read open,read high,read low,read close,read volume,read adjustedclose)
runStrategy cash lines = runStrategy' cash lines []
runStrategy' cash lines shares =
case lines of
(c1:c2:_) -> if (closing c2 - closing c1) / closing c1 < - 0.03 then
runStrategy' (cash * 0.9) (tail lines) ((((cash * 0.1) / closing c2), closing c2): shares)
else if not . null $ shares then
if (closing c2 - (snd . head $ shares)) / (snd . head $ shares) > 0.06 then
runStrategy' (cash + (fst . head $ shares) * closing c2) (tail lines) (tail shares)
else runStrategy' cash (tail lines) shares
else runStrategy' cash (tail lines) shares
[c1] -> cash + sellOff (closing c1) shares
[] -> cash
sellOff price shares = sum . map (* price) . map fst $ shares
closing (date,open,high,low,close,volume,adjustedclose) = close
- Bug/Question: This solution will only perform one sale per day, even if multiple sales qualify, right? If recursion after a sale used lines instead of tail lines, then multiple sales could occur. Newsham 18:08, 8 March 2007 (UTC)