Stock Chart Pattern Recognition in Python

I have been following Part Time Larry’s Youtube channel and learning a lot about Python and trading. Here I was doing this video series tutorial. It was missing source code. It is always good idea to type in the code, so I can see why Larry didn’t publish the code but here is mine.

import yfinance as yf

pizza = yf.Ticker("pzza")

dataframe = pizza.history(period="1y")


import csv

def is_bearish_candlestick(candle):
    return candle['Close'] < candle['Open']

def is_bullish_engulfing(candles, index):
    current_day = candles[index]
    previous_day = candles[index-1]

    if is_bearish_candlestick(previous_day) \
        and current_day['Close'] > previous_day['Open'] \
        and current_day['Open'] < previous_day['Close']:
        return True

    return False

with open('pizza.csv') as f:
    reader = csv.DictReader(f)
    candles = list(reader)

for i in range(1, len(candles)):

    if is_bullish_engulfing(candles, i):
        print("{} is a bullish engulfing".format(candles[i]['Date']))

import yfinance as yf
import csv

companies = csv.reader(open('sp500_companies.csv'))

for company in companies:

    symbol, name = company

    history_filename = 'history/{}.csv'.format(symbol)

    f = open(history_filename, 'w')
    ticker = yf.Ticker(symbol)
    df = ticker.history(period="1y")

import csv

def is_bullish_candlestick(candle):
    return float(candle['Close']) > float(candle['Open'])

def is_bearish_candlestick(candle):
    return float(candle['Close']) < float(candle['Open'])

def is_bullish_engulfing(candles, index):
    current_day = candles[index]
    previous_day = candles[index-1]

    if is_bearish_candlestick(previous_day) \
        and float(current_day['Close']) > float(previous_day['Open']) \
        and float(current_day['Open']) < float(previous_day['Close']):
        return True

    return False

def is_bearish_engulfing(candles, index):
    current_day = candles[index]
    previous_day = candles[index-1]

    if is_bullish_candlestick(previous_day) \
        and float(current_day['Open']) > float(previous_day['Close']) \
        and float(current_day['Close']) < float(previous_day['Open']):
        return True

    return False

sp500_file = open('sp500_companies.csv')
sp500_companies = csv.reader(sp500_file)

for company in sp500_companies:
    ticker, company_name = company
    history_file = open('history/{}.csv'.format(ticker))
    reader = csv.DictReader(history_file)
    candles = list(reader)
    candles = candles[-2:]

    if len(candles) > 1:
        if is_bullish_engulfing(candles, 1):
            print('{} - {} is bullish engulfing'.format(ticker, candles[1]['Date']))
        if is_bearish_engulfing(candles, 1):
            print('{} - {} is bearish engulfing'.format(ticker, candles[1]['Date']))    

HackerRank: New Year Chaos in JavaScript

This problem is rated as medium difficulty. Had to look up clues in comments section though.

My initial solution was very straight forward:

function minimumBribes(q) {
    let bribes = 0;
    for (let i=0; i<q.length-2; i++) {
        if (q[i] - (i+1) > 2) {
            console.log('Too chaotic');
        // compare index to element, works great except when a smaller element is pushed way back
        if (q[i] - (i+1) > 0) {
          bribes += q[i] - (i+1);

Second solution had n**2 complexity but still easy to understand

function minimumBribes(q) {
    let bribes = 0;
    for (let i=0; i<q.length; i++) {
        if (q[i] - (i+1) > 2) {
            console.log('Too chaotic');
        // if there is a bigger  element before this element
        // then that element must have bribed this element
        for (let j=0; j<i; j++) {
            if (q[i]<q[j]) {

Above solution timed out, so finally I looked in discussion section and used copied this solution, since it is O(n) and easy to understand.

function minimumBribes(q) {
    let bribes = 0;
    let expectedFirst = 1;
    let expectedSecond = 2;
    let expectedThird = 3;
    for (let i=0; i<q.length-0; i++) {
        if (q[i] == expectedFirst) {
            expectedFirst = expectedSecond;
            expectedSecond = expectedThird;
        } else if (q[i] == expectedSecond) {
            expectedSecond = expectedThird;
        } else if (q[i] == expectedThird) {
            bribes += 2;
        } else {
            console.log("Too chaotic");

Old bookmarks

This is slightly a mess, basically various links my bookmarks are here.

  4. Ask HN: Developers with kids, how do you skill up? -
  5. Ask HN: How can I learn how to paint? -
  6. Children aren’t born smart. They’re made smart by conversation. -
  7. Maker Faire and Science Education: American kids should be building rockets and robots, not taking standardized tests. -
  9. On Parenthood -
  10. reddit: parenting reading list -
  11. Resistance Training May Lower Type 2 Diabetes Risk: Study -
  12. Everything You Wanted to Know About STEM for Toddlers -
  13. Plano Is the Happiest Place in America -
  14. Good Vibes Are Contagious -
  15. Teens and Young Adults Are More Depressed Now Than in the Mid-2000s -
  16. How Inuit Parents Raise Kids Without Yelling — And Teach Them To Control Anger -
  17. Expert Says Don’t Teach Kids to Code -
  18. The Longevity Research Institute -
  20. When Ancient Societies Hit a Million People, Vengeful Gods Appeared -
  21. A morning fitness routine that’s good for your brain, too -
  22. Teaching Children to Walk Independently! - One of the first reassurances I can give families is that Motor Milestones exist on a continuum. Each child achieves these skills at their own time, in their own way. Though we learn motor development from textbooks positing neurodevelopment theory to explain skill acquisition and motor patterning, the manifestation of this progression takes on distinct characteristics when we look at each child as a unique creation. -
  23. Posture Power: How To Correct Your Body’s Alignment -
  24. Best Camping Near Me | Hipcamp’s Interactive Map of Private and Public Land -
  25. How to increase serotonin in the human brain without drugs (2007) | Hacker News -
  26. Scientists have also administered cognitive tests right after exercise—for example, measuring the flicker fusion threshold (the rate at which a flashing light begins to look like it’s steadily glowing) and found the same thing: After exercise, one’s senses are heightened and thus can detect the flashing at a higher frequency than before exercise.Taken together, these findings indicate that “people see more clearly and immediately after exercise,” Maddock says. “They can make finer visual distinctions; their perceptions are sharper.” -
  28. How do I ensure my only child isn’t socially isolated? -
  30. Atomic ML | Resources to help you learn data science and machine learning. -
  33. A five-minute workout called Inspiratory Muscle Strength Training (IMST) lowers blood pressure in middle-aged to older adults; it also improves artery function and scores on memory tests, according to new research. -
  35. Notably, most improvements in GI symptoms were maintained, and autism-related symptoms improved even more after the end of treatment. Important changes in gut microbiota at the end of treatment remained at follow-up, including significant increases in bacterial diversity and relative abundances of Bifidobacteria and Prevotella. Our observations demonstrate the long-term safety and efficacy of MTT as a potential therapy to treat children with ASD who have GI problems, and warrant a double-blind, placebo-controlled trial in the future. -
  36. Anything you can do to keep from packing up your shit and leaving is called love. -
  37. It is hard sometimes to keep in mind the growth-promoting potential of the mismatches between parent and child goals because the parents’ empathy for the child can make them feel as if it is their fault that they cannot fulfill the child’s wishes. -
  38. The basic premise of attachment theory is that toddlers can grow into happy and competent children if they can rely on at least one adult who makes them feel safe and protected. From this basic feeling of security in relationships grows the impetus to explore how things work in the world and to try out new skills. -
  39. Toddlers walk through life like we all wish we could: confident, demanding, and 100 percent positive that they are the center of the universe. -
  41. Ask HN: What is your money-making side project outside programming? | Hacker News -
  45. It has been said that children need to take 3,000 steps or cover  24 foot ball fields before they can learn to walk by themselves.  Lets just say they need to do 100’s of steps/day -best if it is in a condensed period of time- to learn to walk. -
  47. Trading and Data Science -
  50. The dangers of over-parenting -
  51. Evidence-based parenting: how to deal with aggression, tantrums and defiance -
  52. No matter what you accomplish, achieve or do, somebody is always up to something far more epic than you are if you live your life through the lens of your Facebook news feed. -
  56. Ask HN: Should I quit my job? | Hacker News -
  58. Ask HN: What is the real Value of Real Estate Agent? | Hacker News -
  59. Do you ever get that feeling when listening to a great song that makes all the hairs on your arm stand on end? -
  60. The key to physical fitness isn’t exercise, it’s movement — Quartzy -
  62. How to Automatically Backup a Linux VPS to a Separate Cloud Storage Service | Hacker News -
  63. How to parent more predictably (2018) | Hacker News -
  64. It also appears that belonging to the London cluster made writers substantially more productive. Mitchell finds that the average writer in London saw their productivity go up by 12 percent. By comparison, writers in smaller clusters, in Dublin, Edinburgh, Oxford, and Cambridge, saw no such gains. Furthermore, being part of the London cluster increased the likelihood of an author having their work published in any given year by 24 percent. -
  65. Research led by the University of Exeter, published in Scientific Reports and funded by NIHR, found that people who spend at least 120 minutes in nature a week are significantly more likely to report good health and higher psychological wellbeing than those who don’t visit nature at all during an average week. However, no such benefits were found for people who visited natural settings such as town parks, woodlands, country parks and beaches for less than 120 minutes a week. -
  66. The difference a dad can make -
  67. Ask HN: Has anybody successfully changed their career to become a writer? | Hacker News -
  68. Ask HN: Have any former developers successfully changed careers? | Hacker News -
  69. Ask HN: How do I get into electronics from scratch? | Hacker News -
  70. Ask HN: If you were a coder who successfully changed careers, what do you do now? | Hacker News -
  71. Ask HN: What do I tell my students about starting Freelancing? | Hacker News -
  72. so you want to be a writer? by Charles Bukowski:
  73. The 10 books that changed my career as a software engineer:
  74. In May 2012 I made a commitment that changed my career: A simple task, completed every day, that skyrocketed my blog and allowed me to make over $30,000 in 6 weeks:
  75. What is the Average Profit on a House Flip? -
  76. How This Real Estate Agent Made $100,000 In One Month From His YouTube Channel -
  77. Vonnegut: Can you believe this guy? He makes more money in a single day than we’ll make in our entire lives. And you wrote Catch-22! > Heller: Sure, but I have something he’ll never have. > Vonnegut: Yeah, Joe? What’s that? > Heller: Enough:
  78. Books for Quants – Towards Data Science -
  79. The deliberate dog body language of curving is used in polite greetings, negotiation, or as a calming signal. A head-on, frontal approach can be seen as confrontational. The curving could be the curving of the dog’s body (which makes a slight c-shape), or a directional curve in the path the dog walks on approach. Some have described it as a ‘banana walk’, an easy descriptive way to imagine the direction of walk, due to the shape of the path taken by the dog.
  80. These writers got their start after age 35—there’s still hope for you:
  81. 6 Alternatives To Freelancing For Engineers –
  82. How Long It’s Safe to Leave Food Unrefrigerated -
  83. Anxiety Looks Different in Men –
  84. The $61,392 Book Launch That Let Me Quit My Job:
  85. “The most important emotional accomplishment of the toddler years is reconciling the urge to become competent and self-reliant with the simultaneous and sometimes contradictory longing for parental love and protection.” — The Emotional Life of the Toddler by Alicia F. Lieberman -
  86. The Essential 6 Month Calisthenics Workout Plan -
  87. Pop culture lionizes the dazzling brilliance of money managers on the autism spectrum. Reality rarely measures up:
  88. “It is neither possible nor desirable to be always attuned and responsive to the moods and wishes of children.” — The Emotional Life of the Toddler by Alicia F. Lieberman -
  89. Most knowledge worth having comes from practice. It comes from doing. It comes from creating. Reading about the trade war with China doesn’t make you smarter—it gives you something to say at dinner parties. It gives you the illusion that you have the vaguest idea what is happening in our enormously complex world:
  90. “but the often observed increased involvement of fathers in the toddler years may be linked to findings that fathers as a group are more likely than mothers to promote the adventurous exploration and challenging play that toddlers are now ready to join.” — The Emotional Life of the Toddler by Alicia F. Lieberman -
  91. “One study, for example, found that children who showed a secure attachment to their fathers by seeking them out for comfort when feeling stressed had fewer behavior problems and showed more competence in school and peer groups than did those who had an insecure relationship with their fathers.” — The Emotional Life of the Toddler by Alicia F. Lieberman -
  92. Living cells in the human body experience forces of various frequencies (for example breathing, heartbeats, walking, running, jumping and singing), typically ranging from 0.2 hertz to hundreds of hertz,” the researchers wrote. At the highest frequencies, cells became stiffer and the enzymes that guide gene transcription could not bind to the DNA, the team found.Cells’ immediate responsiveness to force makes sense from an evolutionary perspective, Wang said.”Cells must be able to respond quickly to things in their environment so they can survive,” he said. -
  93. Senate Stock Watcher - See What Senators are Trading:
  94. Analyzing HN readers’ personal blogs | Hacker News ->
  95. Six super-short sci-fi stories that explore the post-COVID-19 world. -
  96. How A Goat Farmer Built A Doomsday Machine That Just Booked A 4,144% Return:
  97. How long does it take to beat your favorite games? -
  98. Find out how to entertain a two-year-old here! 40+ best activities for two-year-olds. Inside you will find indoor play ideas, sensory play prompts, and painting play activities. -
  99. An important point to note here is that automated trading does not mean it is free from human intervention. Automated trading has caused the focus of human intervention to shift from the process of trading to a more behind-the-scenes role, which involves devising newer alpha-seeking strategies on a regular basis:
  100. In this article we’ll look into a real options trading strategy, like the strategies that we code for clients. This one however is based on a system from a trading book. As mentioned before, options trading books often contain systems that really work – which can not be said about day trading or forex trading books. The system examined here is indeed able to produce profits. Which is not surprising, since it apparently never loses. But it is also obvious that its author has never backtested it:
  101. Algorithmic Trading at home – how should I get started? | QuantNet Community:
  102. This is the fourth part of a series of articles on backtesting trading strategies in Python. The previous ones described the following topics:introducing the zipline framework and presenting how to test basic strategies:
  103. Algorithmic Trading Bot: Python - Towards Data Science:
  104. If you’re considering algo trading as a career then be sure to talk to a lot of people doing it. I spent several years trying to break in to the industry at a few prop firms with only middling success. Here are my observations:1. The vast majority of firms only hire people with CS or math degrees from top 10 schools, with an MS being the minimum. There are few exceptions.2. Nobody is making as much money as they used to.3. Depending on what firm you end up at you will probably spend a lot less time building cool strategies and a lot more time trying to shave off a few microseconds here and there.4. Be prepared for a pretty rough work environment. Swearing, violent outbursts, people being secretive and not sharing ideas.5. If you’re lucky, management will be STEM people. If you’re not, they will be former floor traders who have managed to stay alive this long. - Ask HN: How do I get started with Algo trading? | Hacker News -
  105. Ask HN: How to launch an algo trading side project? | Hacker News:
  106. I write (program, paint, animate, market, and so on) computer games like this one[1]. The recent economic troubles haven’t effected me negatively that much, instead it’s been a positive thing as more people are home and playing more games. I don’t necessarily want to ‘profit’ from all the hardship around, but I’m glad to provide products that entertain and hopefully make the current situation a bit more bearable – that feels good.I got started over 10 years ago now, making Flash-based games and licensing them to various web portal and publishers, which was good money for a student back then! A little indie game developer golden age where you’d get a lot of players and also a few thousand dollars per game without too much trouble. I went on from there doing self-published games that anyone can buy on Steam or the Mac Store, both of which provide about 90% of my revenue, and the remaining 10% are from smaller stores and game distributors.[1]… <- My current project. - Ask HN: Successful one-person online businesses? | Hacker News:
  107. Ask HN: Those making $500/month on side projects in 2019 – Show and tell | Hacker News:
  108. Ask HN: What is your passive income 2019? | Hacker News:
  109. Build a Day-Trading Algorithm and Run it in the Cloud Using Only Free Services -
  110. How To Be A Professional Author And Not Die Screaming And Starving In A Lightless Abyss – Chuck Wendig:
  111. How to Find Consulting Clients:
  112. Introduction to Algotrading (2011) [pdf] | Hacker News:
  113. Questions to ask a company during a job interview | Hacker News:
  114. Toddler Development: What Every Parent Needs to Know:
  115. What’s good career advice you wouldn’t want to have your name on? | Hacker News:
  116. Ask HN: Why did you leave tech industry? | Hacker News:
  117. Ask HN: What did you do to get extra streams of income for yourself? | Hacker News:
  118. Using Reinforcement Learning in the Algorithmic Trading Problem | Hacker News:
  119. Analysis of 41k dev agencies with hourly rates, team size and tech stack | Hacker News:
  120. Ask HN: Mind bending books to read and never be the same as before? | Hacker News:
  121. Things You Learn After 1 Year of Day Trading for a Living:
  122. Early Child Development Abilities by Age:
  123. Youtube Workouts for Every Activity and Fitness Level | Outside Online -
  124. Ask HN: Ways to generate income when you’re at home without pay? | Hacker News:
  125. Lots of Oppurtunities to make money online:
  126. Ask HN: If you could work remote where would you live? | Hacker News:
  127. Autism severity can change substantially during early childhood:
  128. Ask HN: I recently lost my job, I want to pursue blogging as a career. Thoughts? | Hacker News:
  129. Ask HN: How do I start my own consulting firm? | Hacker News:
  130. Ask HN: I implemented the life I designed: perfect but I feel lost. What now? | Hacker News:
  131. Ask HN: What is the smartest career path to take? | Hacker News:
  132. Some possible career goals:
  133. Ask HN: Is working as a developer on technical route until retirement feasible? | Hacker News:
  134. Machine Learning Field Guide:
  135. Aging on Nautilus: Why You Can’t Help But Act Your Age:
  136. deerawan/react-native-flashcard-app · GitHub:
  137. GitHub – wesbos/burner-email-providers: A list of temporary email providers:
  138. Ask HN: Consulting in tech. How to start? | Hacker News:
  139. Ask HN: If given freedom to choose, what full-time job would you choose and why?
  140. Learnings From A Year of Being Indie:
  141. DIY Video Hosting:
  142. Why Helicopter Parenting Fosters Failure | Psychology Today:
  143. How you attach to people may explain a lot about your inner life | Science | The Guardian:
  144. Tech Jobs for Good helps you find tech jobs at mission driven companies around the US:
  145. Ask HN: Former software engineers, what are you doing now? | Hacker News:
  146. GitHub – jeltehomminga/pubquiz: pubquiz:
  147. Why Success Won’t Make You Happy – The Atlantic:
  148. Is Making Advanced GUI Applications with Godot the Future? | by Erik Engheim
  149. 50 Magazines and Anthologies That Pay for Horror Fiction:
  150. I Quit My Job. Here’s How I Planned the Start as an Entrepreneur | by Sjors van Dongen:
  151. How do you find your passion? Am I off course? | Hacker News:
  152. Notes on “Anthropology of Childhood” by David Lancy:
  153. Most favorited Hacker News posts of all time:
  154. Algorithmic Trading Using Logistic Regression – Hands-Off Investing:
  155. Ask HN: What is your favorite motto? | Hacker News:
  156. Texas Agent FAQ’s | Park and Refer:
  157. All 149 Combined Ark Invest ETF Holdings:

Docker in 5 minutes

I have been using Docker and Kubernetes for several years now but never really took any time to really read about it. There were a lot of gaps in my understanding of how Docker works and what really is possible with it. Just recently my employer started to offer Udemy’s subscription, so I took Hands on Docker course. Here are some of the important things I learned in this course.

Where do you run Docker containers

You run these in Windows or MacOS but most likely you will use Linux in production. And unlike Windows and MacOS, you can run Docker on Linux VPS.

Important Docker commands

# get running docker containers
docker ps 

# get all docker containers including those that have exited
docker ps -a

# stop container by its id or name
docker stop first_few_chars_of_id

# list docker images stored on the host
docker images

# remove image 
docker rmi image_name

# download a new image
docker pull image_name
docker pul image_name:specific_tag

# append a command
docker run image_name command to run with parameters
docker run ubuntu sleep 5

# execute command in a conatiner
docker exec container_id cat /etc/hosts

# interactive session inside container
docker exec -it conatiner_id /bin/bash

# run container in background/daemon mode
docker run -d webapp

# tail logs
docker logs -f conatiner_id

# attach to conatiner running in detach/daemon mode
docker attach container_id

# map ports, for example, to map port 80 on host to port 8080 in container
dokcer run -p 80:8080 webapp

WordPress to Hugo to WordPress to Hugo

I moved all my blogs back to Hugo. I have gone back and forth between Wordpress and Hugo several times. WordPress makes it really easy to write and publish content. On this domain, I was using WordPress as a bookmarking service. With PressThis plugin, I was able to use a bookmarklet and publish a new post from any page on the web. But that plugin has not been updated in a while and it seems with every new WordPress release something would break. A few times, I was able to hack it to keep going. But lately, I cannot keep up with it. I will have to figure out a better way to bookmark but for now, I didn’t want to deal with WordPress. And easy bookmarking was the only reason why I was using WordPress.

My other blogs were on WordPress as it is not a lot of work to host additional blogs on an existing server. But now that I don’t really need WordPress, I didn’t want the additional overhead of maintaining a server. So I migrated all blogs back to Hugo. I will slowly work on updating theme and everything.

New Focus in 2021

Over last few weeks, I have been doing a lot of leet code and learning data science. I will focus this blog on basically what I am learning. Which is basically what my bookmarks were. Now I am thinking maybe once a week, I summarize and post here what I have learned or read in that week.

I am also very impressed with Part-time Larry, and want emulate him. Trading and algorithmic tradings are some of my favorite hobbies, and I have following his tutorials as fun way to learn python and algotrading. The main topics of this blog will be:

  1. LeetCode (JavaScript and Python)
  2. Data Science
  3. Algorithmic Trading
  4. Trading

I want to make it a resource for learning especially for those who don’t like to watch videos.

Leetcode #13: Roman to Integers

class Solution {

    private $v = ['M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5, 'I' => 1];
     * @param String $s
     * @return Integer
    function romanToInt($s) {
        $n = 0;
        $last = '';
        for ($i=0;$i<strlen($s); $i++) {
            $n += $this->v[$s[$i]];
            if (($s[$i] == 'V' || $s[$i] == 'X') && $last == 'I') { 
                $n = $n - 2;
            } elseif (($s[$i] == 'L' || $s[$i] == 'C') && $last == 'X') {
                $n -= 20;
            } elseif (($s[$i] == 'D' || $s[$i] == 'M') && $last == 'C') {
                $n -= 200;
            $last = $s[$i];
        return $n;

Leetcode 690 Employee Importance Solution

This is my solution in PHP.

* Definition for Employee.
* class Employee {
*     public $id = null;
*     public $importance = null;
*     public $subordinates = array();
*     function __construct($id, $importance, $subordinates) {
*         $this->id = $id;
*         $this->importance = $importance;
*         $this->subordinates = $subordinates;
*     }
* }

class Solution {
 * @param Employee[] $employees
 * @param Integer $id
 * @return Integer

function getImportance($employees, $id) {
  if (empty($employees)) return 0;
  $emap = [];
  foreach ($employees as $e) {
    $emap[$e->id] = $e;

  return $this->recurse($emap, $id);

function recurse($emap, $id) {
  $e = $emap[$id];
  $ans = $e->importance;
  foreach ($e->subordinates as $sub) {
    $ans += $this->recurse($emap, $sub);
  return $ans;

LeetCode 42. Trapping Rain Water

 * @param {number[]} height
 * @return {number}
var trap = function(height) {
    let maxLeft = 0, maxRight = 0;
    let left = 0;
    let right = height.length -1;
    let total = 0;
    while (left < right) {
        if (height[left] < height[right]) {
            if (height[left]>maxLeft) {
                maxLeft = height[left];
            } else {
               total += maxLeft-height[left]
        } else {
            if (height[right]>maxRight) {
                maxRight = height[right];
            } else {
               total += maxRight-height[right]
    return total;

LeetCode 11. Container With Most Water

 * @param {number[]} height
 * @return {number}
var maxArea = function(height) {
    let left = 0;
    let right = height.length-1;
    let maxWater = 0;
    while (left < right) {
        const water = (right-left) * Math.min(height[left], height[right]);

        if (water > maxWater) {
            maxWater = water;
        if (height[left] < height[right]) {
        } else {
    return maxWater;