Wednesday, September 16, 2020

Leetcode discuss: 146. LRU Cache

 Here is the link. 

C# Work on double linked list and learn from mistakes

Sept. 15, 2020
146. LRU Cache

Introduction
I like to take some time to learn how to write a working solution using double linked list written by myself. I started to work on coding, and I plan to make it work first.

Case study
Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]

The idea is to use double linked list so that it is O(1) time complexity to remove a node from double linked list and also insertion.

Second idea is to use a hashmap to save each key and it's pointer in double linked list.

A key has to be removed if it is least used and capacity is reached to upper limit. Also a key is visited by calling Get(int key), the node in the double linked list should be found using O(1) time, and then it is inserted in the double linked list.

To make it easy, recently used should be inserted at the beginning of double linked list, in other words, as a head. I choose to insert in the end of double linked list.

Step by step:
step 1: set double linked list capacity as 2
step 2: [1, 1], insert key and value node(1, 1) object into double linked list as last node or tail node
step 3: [2, 2], insert key and value node(2, 2) object into double linked list as last node or tail node
double linked list:
head tail
1 <-> 2
step 4: [1], get key 1
In the above step 2 and step 3, save each node in double linked list into a hashmap by key value, so it will take O(1) time complexity to find node using key value
Since key 1 is visited, head node with key value 1 will be deleted first, and a new node with key value 1 is added as last node in double linked list.

Do it yourself
I also like to write a double linked list by myself, instead of using dummy head and dummy tail two nodes, I study Microsoft C# LinkedList source code, and I like to copy ideas from LinkedList. Here is the link.

The idea of double linked list design is to use a head node, and then head is connected to tail of double linked list using head.Prev = tail.Next.

There are a few challenges, so that I failed each test case in my code listed as test case 1 and 2 and 3.

I like to try a few ideas to make the implementation easy. Add a new node to the head of double linked list instead, and also extra a double linked list class to include minimum functionalities to make solution work.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace L146_LRU_cache_practice
{
    class Program
    {
        static void Main(string[] args)
        {
            //RunTestcase1();
            //RunTestcase2();
            RunTestcase3();            
        }

        public static void RunTestcase1()
        {
            var cache = new LRUCache(2);
            cache.Put(1, 1);
            cache.Put(2, 2);

            var value = cache.Get(1);
            cache.Put(3, 3);
            var result = cache.Get(2);
            Debug.Assert(result == -1);
            cache.Put(4, 4);
            var result2 = cache.Get(1);
            Debug.Assert(result2 == -1);
        }

        public static void RunTestcase2()
        {
            var cache = new LRUCache(2);
            cache.Put(2, 1);
            cache.Put(1, 1);
            cache.Put(2, 3);
            cache.Put(4, 1);

            var result1 = cache.Get(1);
            var result2 = cache.Get(2);
        }

        // [[3],[1,1],[2,2],[3,3],[4,4],[4],[3],[2],[1],[5,5],[1],[2],[3],[4],[5]]
        // [null,null,null,null,null,4,3,2,-1,null,-1,2,-1,4,5]
        // [null,null,null,null,null,4,3,2,-1,null,-1,2,3,-1,5]
        public static void RunTestcase3()
        {
            var cache = new LRUCache(3);
            cache.Put(1, 1);
            cache.Put(2, 2);
            cache.Put(3, 3);
            cache.Put(4, 4);

            var result1 = cache.Get(4);
            var result2 = cache.Get(3);
            var result3 = cache.Get(2);
            var result4 = cache.Get(1);

            cache.Put(5, 5);
            var resultB1 = cache.Get(1);
            var resultB2 = cache.Get(2);
            var resultB3 = cache.Get(3);
            var resultB4 = cache.Get(4);
            var resultB5 = cache.Get(5);
        }        
    }

    public class LRUCache
    {
        internal class Node
        {
            public Node Next { get; set; }
            public Node Prev { get; set; }

            public int key, val;
            public Node(int key, int value)
            {
                this.key = key;
                this.val = value;
            }
        }

        private Dictionary<int, Node> map;
        private Node head;
        private int capacity;

        /// <summary>
        /// double linked list 
        /// reference:
        /// C# LinkedList class implementation
        /// https://referencesource.microsoft.com/#system/compmod/system/collections/generic/linkedlist.cs
        /// </summary>
        /// <param name="capacity"></param>
        public LRUCache(int capacity)
        {
            this.capacity = capacity;

            map = new Dictionary<int, Node>();
        }

        /// <summary>
        /// LRU - put least recently used - last one out
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public int Get(int key)
        {
            if (!map.ContainsKey(key))
                return -1;

            var node = map[key];

            var newNode = new Node(node.key, node.val);

            // remove the node -> add to the tail - last one - refreshed    
            if (node != node.Prev)
            {
                var isHead = node == head;
                if (isHead)
                {
                    head = head.Next;
                }

                // remove existing one first, connect node.Prev with node.Next
                node.Prev.Next = node.Next;
                node.Next.Prev = node.Prev;                

                // add new node at the end of double linked list
                head.Prev.Next = newNode;
                newNode.Prev = head.Prev;

                newNode.Next = head;
                head.Prev = newNode;

                node.Prev = null;
                node.Next = null;
            }
            else
            {
                head = newNode;

                head.Prev = head;
                head.Next = head;
            }

            // update key's address
            map[key] = newNode;

            return node.val;
        }

        public void Put(int key, int value)
        {
            var update = map.ContainsKey(key);
            var eviction = map.Count == capacity;

            if (!update)
            {
                if (eviction)
                {
                    // remove one
                    var removed = head;
                    // remove from the map
                    map.Remove(removed.key);

                    if (head == head.Prev)
                    {
                        head = null;
                    }
                    else
                    {
                        head.Prev.Next = head.Next;
                        head.Next.Prev = head.Prev;

                        head = head.Next;
                    }
                }
            }
            else
            {
                // if key is existed, then it should be removed first and also
                // map should be updated as well.                 
                var removed = map[key];
                if (map.Count == 1)
                {
                    head = null;
                }
                if (map.Count == 2) // added after debugging
                {
                    head = head == removed ? head.Next : head;
                    head.Next = head;
                    head.Prev = head;
                }
                else
                {
                    removed.Prev.Next = removed.Next;
                    removed.Next.Prev = removed.Prev;

                    head = head == removed ? head.Next : head;
                }
            }

            // add the node 
            var newNode = new Node(key, value);

            if (head == null)
            {
                head = newNode;

                // caught by debugger - connect head and tail in double linked list
                // avoid null pointer bug
                head.Prev = head;
                head.Next = head;
            }
            else
            {
                head.Prev.Next = newNode;
                newNode.Prev = head.Prev;

                // head and tail get connected
                head.Prev = newNode;
                newNode.Next = head;
            }

            map[key] = newNode;
        }
    }
}

OXY stock: Why Energy Stocks Core Laboratories, Occidental Petroleum, and SM Energy Jumped Today

Here is the article. 

Shares of small U.S. oil and gas company SM Energy (NYSE:SM) rose as much as 11% on Sept. 16. Fellow driller Occidental Petroleum (NYSE:OXY) were up roughly 10% at one point. Drilling services provider Core Laboratories (NYSE:CLB) also joined the energy sector uptick, rising around 9%. All three had given back some of their gains by 1 p.m. EDT, but were still holding on to high-single-digit advances.

Crude oil price is lower

Each of the sizable daily advances here is owed, in great part, to a notable rise in the price of oil today. But to attribute the entirety of the moves to this single factor would miss the bigger picture. Oil prices have fallen to painfully low levels in 2020 because of the dramatic reduction in demand that resulted from the economic shutdowns used to slow the spread of COVID-19. It was so bad that, at one point, oil fell below zero. Although economies around the world are opening up again and oil prices have risen well off the zero bound, they remain mired at a level that makes it difficult for exploration and production companies to turn a profit. That's partly because of weak demand and partly because excess supply earlier in the year has created an overhang of oil sitting in storage. This backdrop is vital to understanding the situations in which Core Labs, Occidental Petroleum, and SM Energy find themselves today. 

Hurricane - swift rises - falling lower again - gulf of Mexico region

Oil is a commodity prone to big price moves, and news (such as a hurricane working its way through the Gulf of Mexico region) can result in swift rises. But there are many things that can result in them quickly falling lower again. Today's oil advance lifted the shares of Core Labs, Occidental, and SM Energy and there's good reason for that. However, it's difficult to suggest that oil's advance today really changes anything about the bigger supply/demand imbalance or the headwinds that these specific energy names are facing right now. Core Labs, Occidental, and SM Energy are not stocks for the faint of heart, as more volatility is highly likely.

 

finviz.com: Sector - energy sector big rebound since crude oil over 6% rebound

 Here is the link. 


Sept 16, 2020 rebound

Since TFSA account is tax free, it has 15% tax for US stocks. It is tax deducted ETF for Canada market. 





Think big, think hard: Sept. 16 2020 crude oil 6% rebound

 Sept. 16, 2020

Introduction

I like to do a quick comparison using re-balance, passive investment technique, avoid big loss - cut loss, catch rebound in a few hours. I think that most important is to stay confident, no matter which solution I may choose, later I make changes, I should stay positive, and always there is more than solutions than problems. Stay confident, and stay positive. When market rebounds, it is better to take extra time to think about big, think hard. Try to make biggest bet when market rebound is strong. 

Oil sector return 

I like to check oil and energy sector return on Sept. 16, 2020. 


One idea is to rebalance, I can put together a plan for my portfolio, for example, SU.TO stock 1000 shares, 50%, another 50% cash, if SU.TO continues to go down, then I can buy more SU.TO, and then keep ratio of cash/ SU.TO position market value in the same ratio. 

The second idea is to stop loss early, and then try to catch a rebound in short time. For example, bet on other oil stock like CVE.TO with 8% rebound today, and invest $30,000 - $60,000 to have 5% gains. 

In the long run, if I can purchase 1000 shares of SU.TO in lowest price, then it is best investment for me. But SU.TO stock price may go down another 10 to 20%. It is better for me to catch a rebound if I can. 


Energy stock: Crude oil over 5% rebound on Sept. 16, 2020

 Sept. 16, 2020

Introduction

It is so hard for me to be a good trader to make gains today on crude oil rebound. I did not take big risk to get biggest gains I can, instead I just stopped when I see CVE.TO 1010 shares with more than $200 dollars return. 

My research 

Here is the article I like to build a portfolio and then look into. 

Energy stocks post gains as U.S. crude tops $40/bbl

Energy (XLE +4.2%) tops today's S&P sector leaderboard, with crude oil extending its rally following an unexpected drop in crude inventories.

October WTI +4.6% to $40.05/bbl; November Brent +3.9% to $42.11/bbl.

U.S. crude stocks fell by 4.4M barrels last week to 496M, the U.S. Energy Administration reported, compared with analyst expectations for a 1.3M-barrel rise.

Lackluster gasoline consumption figures from the EIA and a dropoff in diesel demand kept prices from moving higher, says Again Capital's John Kilduff.

Four of today's top five gainers on the S&P 500 are in the oil and gas sector: FANG +9.8%FTI +9.2%OXY +9%FTI +9%EOG +7%.

Other noteworthy winners include OKE +6.8%APA +6.6%MRO +6.5%SLB +6.1%HAL +5.8%.

Oil majors XOM +4%CVX +3.4%BP +2.4%RDS.B +2.2%.

ETFs: XLEXOPVDEGUSHOIHBGRERXDRIPFENYXES

My yahoo finance portfolio - Sept 16 2020 big gains oil stocks





SNOW stock: Debut on stock market - double the price

 Here is the article. 

Cloud company Snowflake shares surged more than 111% in its market debut on the New York Stock Exchange on Wednesday in the largest ever software IPO. 

The stock began trading at $245 per share and closed at $253.93. A day earlier, Snowflake priced shares at $120, higher than the $100 to $110 range it estimated on Monday, and a huge bump from the $75 to $85 range it proposed last week. 

Snowflake was worth $70.4 billion at the end of trading, more than five times its $12.4 billion valuation in February.


Opportunity loss: CVE.TO stock went up 8%

 Sept. 16, 2020

Introduction

It is challenge for me to figure out what to do best for my own interest. This morning crude oil went up $1.8 dollars, and later over 4%, XLE went up more than 4%. I did sell CVE.TO 1010 shares, and also 1010 HSE.TO shares. But I learned that I should work on more ideas from 6:30 AM to 9:30 AM. 

Ideas to catch momentum

CVE.TO has around 3.0% gains, I decided to sell 1010 shares of CVE.TO. What I should do is to set trailing stop, so that I can sell when CVE.TO makes 8% gains, drop 1% to 7% gains. Furthermore, I should bet on CVE.TO makes 8% gains, so that I can purchase $60,000 dollars to have 5% gain using trailing stop. 

There are around 5,596,900 shares today. In total there are 25 million dollars to sell, it may not be ideal place to bet on 8% return. I should consider other big oil companies instead. 

1010 CVE.TO shares of sale





Also I should purchase XOM stock using my cash in my Ameritrade.com account, so that I can get 4% return on crude oil price gains over 5%. 


Actionable Items

Every time I sell a stock, I should build a good habit to think about using trailing stop first; I am not sure the momentum of CVE.TO stock, and I should make most of profit I can. 

Also since crude oil price goes up, I should consider other big oil companies, and get gains from those stocks as well. 

I lost over $6,000 dollars on SU.TO, IMO.TO, HSE.TO, but those stocks did not get big rebound. 

I should work on my knowledge of oil industry, know more about stocks and ETF as well. 

If I think about carefully about CVE.TO momentum, and then put an order of trailing limit order, then I can make more than $0.10/ share for those 1010 share. The total gain is $101 dollars. 

If I learn that the probability to go higher is almost 100%, I checked XLE ETF, and all other big oil stocks go up, I should purchase $60,000 dollars on CVE.TO and put a trailing limit order to sell, so that I can make profit in less than three hours with 5%. That is around $3,000 dollars. 

So I should do more research, and learn more about business about crude oil, energy stock, and wait for those opportunity to rebound over 5% with high probability. 

Sept 16 2020

My portfolio



Risk management: Stock market is scary, wall street is tough to play with

 Sept. 16, 2020

Introduction

Knowledge is power. I have losses over $6000 in Sept. 2020 since wall street likes to cool down stock market, energy sector also has over 10% losses. I like to write a short report on this. 

My bias

I choose to invest $70,000 dollars on August 31, 2020. I thought that technology stock is too hot to purchase, there will be correction any time around the clock. Actually energy stock is the same. 

I chose volatile stocks and then SU.TO has over 15% loss from August 31 to Sept 15. Today there is a mistake about crude oil calculation, now there is around 2% rebound on SU.TO stock, XLE ETF. 

My attitude

When I scare, I should think and push myself hard to get back. It is hard for me to do that. I used to get same response when I worked on first year Ph.D. study in Florida Atlantic university. 

I tried to pass Ph.D. qualification exam, but I also took those heavy courses related to technologies, I did not have too much time to learn and prepare for the exam. 

Of course, at that time, I have a classmate who used to Microsoft principle engineer after 15 years, who helped me a lot, answered my questions patiently. So many classmates help me, I do not enumerate them one by one here. 

It is hard for me to stay consistency. Work hard, and push hard to myself. No matter what I do, algorithm and data structure practice, system design, stock market investment, I should push myself and stay positive. 

I need to keep learning and understand how business works. 

Cheers! Say goodbye to over $7000 dollars loss. I got $400 dollars rebound, I sold them. I need to get back using small amount investment capital first. 

Gmail: Explore all features - go to, label

 Sept. 16, 2020

Introduction

I took 10 minutes a time to explore Gmail feature recently, and I have such great benefit. I like to encourage myself to better manage myself using Gmail. 


Product features

I like to list those features and how they are helpful for me to manage my daily activities. Stay tuned. 


CVE.TO stock: More news

Here is the article.  

Cenovus Energy Inc. (TSX:CVE). Unchanged at $5.40. A year after construction was allowed to restart on the Trans Mountain pipeline expansion, its chief executive says the project is on budget and on schedule for completion by the end of 2022. The project is advancing as expected despite challenges including the COVID-19 pandemic, a global slump in demand for fuel, a $5.2-billion rise in its estimated cost to $12.6 billion in February and ongoing protests by opponents, said CEO Ian Anderson in an interview. The expansion project is designed to triple the capacity of the existing pipeline between Edmonton and a shipping terminal in Burnaby, B.C., to about 890,000 barrels per day of products including diluted bitumen, lighter crudes and refined fuels such as gasoline. Calgary-based Cenovus Energy Inc. used Trans Mountain this summer to collect oil from Alberta to fill an oil tanker in Burnaby and ship it through the Panama Canal to an Irving Oil refinery on the other side of the country in Saint John.

Tuesday, September 15, 2020

TRADING SKILLS & ESSENTIALS RISK MANAGEMENT Limiting Losses

 Here is the article. 


Be patient: Work on small amount investment portfolio

 Sept. 15, 2020

Introduction

It is hard for me to do good project management on stock investment. After I lose all my gains on my TFSA, I start to think about investing on small amount, less than $10,000 dollars, I like to learn from those small amount. 

Only work on gains

Ideally I should think about only investing using gains. I have to write down my thoughts, and then take less risk. As a beginner, I learn two big lessons, one time is to purchase $13,000 dollars on SPX 3300, and then on August 31, 2020, purchase of over $70,000 dollars, without taking profit, and back in February, China has coronavirus, I bet on stock market go up, invest another over $20,000 dollars. 

I do not learn the importance to stop loss, money management problems I have over 30 years, and I do not make good plans. 

All those areas I like to take review one by one. All my problems show up on stock market investment. Those are excellent places for me to work on my improvement. 

Knowledge is power

I need to read more about business, and also learn some basics as well. 


The Art of Cutting Your Losses

 Here is the article. 


The Art of Selling a Losing Position

 Here is the article. 

SU.TO stock: Sept. 11 - Sept. 15, 2020 three business day 1000 share journey

 Sept. 15, 2020

Introduction

It is my short of research and ownership understanding.  I like to put together and think about more, what are my problems and what I should work on. 

Emotions - I need to take all possible chances

It is so scary since I ran out of all my gains. I do not lose my capital. I purchased on Sept. 11 at price 18.06, but I did not set sell of those shares when price hitting high on Sept. 14, 2020 at $18.37 and Sept. 15 at price $18.27. 

I should set GTC order and put limit of price, and I should be able to have some gains. I did sell on Sept. 15, 2020 when I watched the market this morning. 

It is hard for me to make a good plan and then make profit. 





Crude oil: My research of historical data

I plan to look into historical data, and then figure out what are those changing point at the end of summer and holiday season. 


Monday, September 14, 2020

SU.TO stock: One more article is like a cup of tea

Here is the article. 

The most obvious would be that stocks are getting expensive. Beyond that, the Buffett Indicator can’t tell you much. It’s a metric for the market as a whole, not for individual stocks. However, if you think that the Buffett Indicator is useful, you could use similar metrics to analyze individual stocks.

One stock that appears undervalued based on such metrics is Suncor Energy (TSX:SU)(NYSE:SU). It’s a Canadian energy company that got hit extremely hard by the COVID-19 recession. Down 57% year to date, it has been one of the TSX’s biggest losers.

However, it’s also a very cheap stock with a high dividend yield. Trading at 0.76 times book value, it technically costs less than the net value of its assets. It’s also cheap relative to sales, with a 0.9 price-to-sales ratio. Its projected forward P/E ratio is a little high at 27.5. But remember, that “forward P/E” is an estimated ratio. The estimates could be wrong.

On the one hand, Suncor Energy is cheap for a reason. The energy industry has been doing very poorly over the past five years, and it did extremely poorly in 2020. On the other hand, the extreme downward pressure on oil prices that produced Suncor’s current valuation won’t last forever. It should bounce back, at least somewhat. In the meantime, the stock has a juicy yield of 4.8%. It’s a pretty solid income play that Buffett himself owns.

The post Warren Buffett’s #1 Indicator Predicts Market Crashes appeared first on The Motley Fool Canada.

TSE:CVE stock: Could The Cenovus Energy Inc. (TSE:CVE) Ownership Structure Tell Us Something Useful?

 Here is the article. 

It is such good learning article for me to learn more about business. I paid over $1500 dollars tuition on this stock. 


MU stock: Why Micron Stock Just Jumped 7%

 Here is the article.

Shares of computer-memory maker Micron (NASDAQ: MU) are up a strong 6.7% in mid-morning trading Monday, at around 10:50 a.m. EDT. If you own shares of the stock, you can thank Goldman Sachs for that. This morning, Goldman upgraded shares of Micron to buy, and assigned the $49 stock a $58 price target

Actionable Items

WDC stock goes up over 3% as well. I should sell SU.TO and then purchase WDC stock. 


SU.TO stock: an Altman Z score of one - incredibly close to potentially filing for bankruptcy

 Sept. 14, 2020

Introduction

It is my stock research. I have to learn more about Su.to stock. 

Close to file for bankruptcy

Here is the article. 

Suncor

Suncor Energy (TSX:SU)(NYSE:SU) has been unfairly treated during this pandemic. On the one hand, it’s true that the company has seen a loss from cutting production. However, the energy giant is the largest fully integrated energy company in Canada. So, when one area of the business is down, Suncor sees an uptick in its other services.

But that only work if the company has a long-term solution. True, it has long-term contracts, but that won’t help as the company continues to bring on more and more debt. In fact, as of its recent earnings quarter, the company has an Altman Z score of one, meaning it is getting incredibly close to potentially filing for bankruptcy.

So, it’s no wonder that the company cut dividends, and it’s highly likely Suncor could cut dividends even further before the year is out. Once another market crash hits, investors could see the once major dividend player cut dividends altogether.

TSX:CGX: My learning as a stock investor

 Sept. 14, 2020

Here is the article. 

Why this year and next are so important for Cineplex

Cineplex owns and operates movie theatres across Canada. Its shares have dropped 70% in 2020. However, the stock has climbed 10% over the past month.

Back in August, I’d discussed whether theatre re-openings could propel the stock in the second half of 2020. On August 20, Cineplex announced that all 164 theatres and 10 entertainment venues would open across Canada. However, it will still operate under limited capacity due to COVID-19 restrictions.

In previous articles, I’d discussed the challenges facing Cineplex. The pandemic has thrust even more consumers into the arms of home entertainment providers like Netflix. However, Cineplex CEO Jacob Ellis has continued to strike and optimistic tone. Disney stirred controversy with its decision to release Mulan exclusively on its Disney+ platform.

Ellis argues that theatres are still “the engine that drives the train . . . it’s trading dimes for nickels when you go directly to streaming, because you don’t have that $40 million worth of revenue from theatrical releases around the world.”

Despite his confidence, Disney will also be forced to respond to consumer behaviour. If this leans away from movie theatres, Cineplex will be in more trouble in the years ahead. Shares of Cineplex last had a P/B value of 1.7. It was forced to withdraw its monthly dividend earlier this year.

SU.TO stock: Better Recovery Stock: Suncor (TSX:SU) or Cineplex (TSX:CGX)?

Sept. 14, 2020

Here is the article. 

Suncor: Can this energy stock return to form?

Suncor is a Calgary-based integrated energy company. Its shares have dropped 55% in 2020 as of close on September 10. Investors can expect to get a look at its third-quarter 2020 results in October.

In Q2 2020, the company lamented lower demand for crude oil and refined products due to the COVID-19 pandemic. Unfortunately, this combined with a supply increase from OPEC, which drove down commodity prices, generating downward pressure on the Canadian energy sector. Funds from operations came in at $488 million, or $0.32 per share compared to $3.00 billion or $1.92 per share in the prior year.

Last spring, I’d discussed why Suncor was a stock that was worth stashing in a TFSA. The stock last had a favourable price-to-book value of 0.7. Suncor last dropped its quarterly dividend of $0.21 per share, which still represents a solid 4.6% yield.

Actionable item

As long as Suncor will not file bankrupt, I like to continue to work on investment on Su.To. I like to recover my capital loss around $17,00 dollars first.