Sunday, September 29, 2019

Scripts: How I partially automated my finance tracking system

I am currently studying computer science. One of my interests is in using my computer science knowledge to aid me in my personal finance and investing journey. So I wondered since I update my finances every week, why not automate a portion of my finance tracking system?

So I decided to write a script that could update my Excel spreadsheet with current prices.

What I used:
  • Python - I decided to use Python as I have done several scripts in Python. It is easy to use and has the packages I need to get started
  • openpyxl - a Python module that can edit Excel sheets.
  • cronjob - I wrote a cronjob to automate the running of the script.

Portfolio set up:

1. Open an Excel sheet to create your portfolio. It's better if you already have your own portfolio in Excel. 
2. Go to Yahoo Finance and search for the stocks you want to include in your portfolio. Copy the URL into a row in your portfolio. 

Python set up:

1. If you don't already have Python installed, head over to python.org to install Python. 
2. Install pip on your computer. Pip is a Python Package Installer which will make installing our required packages easy. 
3. We need to install these packages: bs4, openpyxl, urllib2
4. Go to the command line and type in these commands, one after another:
pip install openpyxl
pip install bs4
pip install urllib2

Retrieving prices from Yahoo Finance:

Now that we have the prerequisites, let's start coding! Our first step is to create a function:
retrieve_price(url)
that retrieves prices from a given URL.

Start by importing the relevant modules:

  • bs4 is a Python module that allows us to web scrape websites. 
  • urllib2 is a module that allows us to read from a URL.
  • openpyxl is a Python module that allows us to edit Excel sheets.

Import these packages into our script:

import openpyxl
from bs4 import BeautifulSoup
import urllib2
def retrieve_price(url):
    //code here
In our retrieve_price function, we need to retrieve the contents of a web page and get the stock price from the contents. To do so, make use of the urllib2 module to read from a script: 
content = urllib2.urlopen(url).read() 

This creates a BeautifulSoup object out of the contents of a webpage. 
soup = BeautifulSoup(content, 'html.parser') 

To find the stock price, we have to look through the HTML script and find the code that represents the stock price. In the Yahoo Finance page, move your cursor to the price, right-click and click 'Inspect'. The price is tagged under 'span' tags, in the <insert class here>. Based on our BeautifulSoup object, we can find information relating to that tag:
price = soup.find('span', {'class', 'Trsdu(0.3)'}).string

But at this point, price is a string and not a number that we want. So we need to convert it to the type we want:
price = float(price)

After we have the price, return it from the function. Putting it all together, this is how our script should look like now:

import openpyxl
from bs4 import BeautifulSoup
import urllib2

def retrieve_price(url):
 content = urllib2.urlopen(url).read()
 soup = BeautifulSoup(content, 'html.parser')
 #get this from original webscraping script
 price = soup.find('span', {'class':'Trsdu(0.3s)'}).string
 price = float(price) #convert from unicode to string
 return price


Opening and Editing portfolio in Excel:

1. Get the path of your Excel stock portfolio. 
2. Opening a workbook in our script is similar to opening an Excel file. To open a workbook in our script, we use the openpyxl module. Open the excel file:

savings_workbook = openpyxl.load_workbook('NAME_OF_EXCEL_FILE')

3. Replace 'EXCEL_PORTFOLIO' with the path to your excel portfolio.

4. In a workbook, there are worksheets that we can edit. This is similar to how when we edit an Excel file, we can create and edit many worksheets. To access a particular workbook:
portfolio = savings_workbook.get_sheet_by_name('Portfolio 2019')


5. The goal is to: read the URL from the excel sheet, scrape the current stock price, then update a specific cell in the excel workbook with the price. For this tutorial, I will paste the Yahoo Finance link of the stock to cell B2, and assign cell G2 to where the stock prices will be updated.

6. To access the URL from cell B2 [column = 2, row = 2], we have to access a cell from our Worksheet:
start_column = 2
start_row = 2


current_cell = portfolio.cell(row=start_row, column=start_column)

7. To access the URL from the cell:
url = current_cell.value

8. To update the stock prices for all the stocks, include a loop to access the URLs for all the stocks in the Excel sheet.

current_cell = portfolio.cell(row=start_row, column=start_column)
 while current_cell.value is not None:
  if current_cell.value != 'SOLD':
   url = current_cell.value
   #go to url to retrieve price
   price = retrieve_price(url)
   #update stock price value
   portfolio.cell(row=start_row+2, column=start_column+5, value=price)


  start_row += 4
  current_cell = portfolio.cell(row=start_row, column=start_column)


9. After this, we need to save the workbook:

savings_workbook.save('NAME_OF_EXCEL_FILE') 


Scheduling a cronjob

Now that our script is completed, we have to schedule the script to run periodically to update our portfolio automatically. We can schedule a cronjob for Mac or Linux computers. Windows users can use the Task Scheduler.

This cronjob I scheduled runs the Python script at every Saturday, at 12pm:
0 12 * * 6 python <link to python script> 

This is a good link to learn how to schedule a cronjob: https://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800

Conclusion

Now you have learned how to create a stock portfolio in Excel and to retrieve the stock prices automatically. To look at the full code, visit this link: https://github.com/C-likethis123/Portfolio-Update-Script/tree/master

You can also add on to the script provided, for example by including a function to automatically retrieve dividend data. Happy coding!

Tuesday, August 20, 2019

Trading Journal - Sasseur REIT

I bought 5000 shares of Sasseur REIT at 0.802.

Reason:

  • High ROE
  • Low P/E ratio 
  • High dividend yield
  • The REIT invests in the China retail market 

Tuesday, August 6, 2019

Trading Journal - NAC CT

I bought North Asia Commercial Trust (RW0U) at 1.33.

Reasons:

  • I wanted to invest in REITs with exposure to China's retail. I did a comparison between Sasseur REIT, EC World REIT, Dasin Retail Trust, and North Asia Commercial Trust. 
  • This REIT seems to be able to manage its debt well, and its DPU have been increasing.
  • Consistent dividends, and payout ratio is 46.82%, quite okay. Personally I am wary of companies whose payout ratio is > 100%. 
  • Also based on Yahoo Finance, PE ratio is 6.67 (as of the time of writing)
  • Based on the AGM (source: https://fifthperson.com/2019-mapletree-north-asia-commercial-trust-agm/), I think that it is good that the company is managing crises well. I think having a strong management is key to running a business and ensuring continuous profits. 

Trading Journal - Sold Singtel

I sold 1000 shares of Singtel at 3.30.

Reasons for selling:

  • Profits dropping 
  • Telco industry is now very competitive, hard to increase profits 
  • Prices have been dropping recently. 


Saturday, August 3, 2019

Reflections - Retiring early

Background


I am sure everyone thought of retiring early. It is tough to work for a living, and given a choice, I am sure many people will stop working. When I first started my investing journey, I wanted to retire too. Initially, my goal is to retire at the age of 30. But now, I want to closely examine why I felt the urge to retire.

Why did I not want to work?

I think it was attributed to a few reasons:

Escapism

I hated working in FnB. I hated the long working hours, I hated the physically demanding work I had to do. I hated having to face customers. I hated the relatively low pay. I hated the management, the bosses, everything. 

I had just started working and realised how hard it was to earn for a living. I thought that if I could retire earlier than others, I do not have to face these problems that were making me so depressed. 

Looking back, even though FnB isn't the greatest environment to work in, I lacked interpersonal skills to thrive at my jobs and thought early retirement is an easy way out. But early retirement will not solve the root cause of my problems.

I did not want to be stuck in the rat race

I wanted to enjoy life while I was still young instead of being stuck in the rat race. I did not want to slave away for bosses for my whole life.

I wanted to enjoy life with my boyfriend

I had thoughts of marrying my boyfriend and enjoying life with him. I know how much people spend their lives in the workplace instead of with their family and spouses and I did not want that.

What made me change my view?

When I had achievements at work

When I achieved something at work, I felt proud of myself. Achieving something at work is also contributing to a company and an industry. I think this is very meaningful.

I still have so much at the age of 30 to contribute to an industry, to work at a job I love

Realistically, after serving my scholarship bond, I will be 23-24. This means that I will only have 6-7 years before I retire. I think the tech industry is very broad and I don't think 6-7 years is enough to explore the various fields of computer science. I like programming, I like developing even though I am not very good at it yet. But I don't think I want to give up a job that I love

I still have a lot to learn

I was fortunate that my colleagues and supervisors were helpful and taught me a lot during my work there. They gave me insights which made me appreciate the tech industry more. I don't think I will be able to learn that much without working in a company that specialises in IT. In the workplace, companies are forced to learn as much as they can and employees have to collaborate with each other to gain competitive advantages in the market. I get to learn of the latest trends and best practices from my colleagues, who may be the top experts in my field. I don't think this is something I can gain if I retire early.

Living in Singapore is expensive

Realistically, I don't think I will earn enough to be able to cover my living expenses for the rest of my life. Price of basic necessities are increasing, and there are many catastrophic events that can wipe out my savings/investing assets that I will not be able to fully plan for. Insurance/savings can only help me so much. Working beyond 30 helps me to accumulate a better cash buffer.

What are my future plans?

So if I don't want to retire at 30 anymore, what do I want to do beyond 30? To be honest, I don't really know what I would want to do at that age. Maybe I would want to try working in a new environment? I will be working in IT consultancy after graduation, but I have always wanted to try out research and study for my Masters and Phd. Maybe I would want to consider working part time, maybe I would want to consider travelling or taking up a new hobby.


What should I do?

Here are some things I think I should do:

Develop skills needed to thrive in the workplace

  • Look out for new trends/skillsets I should learn and seek to apply them
  • Learn how to socialise, network and manage relationships
  • Learn how to learn
  • Learn emotional management
  • Learn about the industry and how I can/should contribute to it with my skillsets
  • Learn from the good and bad

Continue managing my finances

Finances are important even if I don't want to retire. I want to get to a point where I am financially free so I can support myself and the people around me. 


Continue exploring myself

I think I should continuously explore what I like and don't like, what I am good and bad at. 

ETF Watchlist

S&P fund focused on technology stocks - I will buy if I have a trading account with DBS Vickers or Phillips. Because I don't know how to deal with the taxes portion and would rather offload it to the brokerage firms to do it for me.
STI ETF - I will buy at a dip.

REITs Watchlist

Fortune REIT
Capitaland Mall Trust (will buy more)
Frasers Centrepoint Trust
Mapletree North Asia Commercial Trust

Stock Watchlist

SBS Transit
Thaibev (with a PE > 30, I think this stock is overpriced)
OCBC
UOB

Trading Journal - DBS

DBS is a good stock choice because of increasing dividends over time and increasing profits. But I refrained from buying it at $22 at that time, which I regret now. Again, the lesson about not being greedy, I should buy it at a dip.

I bought 1 lot at $25.57 I think.

I think it was good I didn't buy it at $28, because I had FOMO about missing out on such a good stock. Because the prices dipped anyway.

Trading Journal - Capitaland Mall Trust

I bought 4 lots of CMT with FSMOne. On hindsight I should have invested more money. But I was also much more cautious with my investing and I felt that I should invest wisely and not based on my emotions. So I should not beat myself over it. Investing wisely should be priority.

Why I bought Capitaland Mall Trust:

  • Strong and stable earnings even in recessions
  • Malls are frequented by people 
  • Regular dividends

Reflections - REITs

When I first got into investing, I have always wanted to buy REITs, especially Capitaland Mall Trust. Reason being I go malls often and could see how popular these malls were. Plus because of regulation they are required to give 90% of their distributable income to investors. So it was a safe and relatively high yield investment.

These malls prices also remained stable, even increased during financial crises. Even when there was the hooha about increase in taxes affecting profits of REITs, the prices of REITs are still increasing steadily.

However I didn't know what to do to buy stocks and I thought FSMOne didn't offer REITs at that time. Had I known they offered REITs, I would have bought them much earlier.

Trading Journal - Singtel

I bought Singtel at 3.04. I think it's a good price on hindsight. But on the day after I bought it, prices dipped to the 2.98 range, which made my heart sink. Lol.
I thought that Singtel was a good investment at that time, because:

  • Singtel had a consistent dividend policy
  • Was always seen as a good stock.
  • Biggest market player in its industry in SG and has overseas investments
  • Leading the 5G technology wave (?)
  • Was anticipating that telco war with tpg ends with tpg losing and Singtel gaining an upper hand.


But investors in general didn't want to invest in Singtel because the telco industry wasn't doing well with all that competition and regulation. I was worried because I bought Singtel on impulse.

Trading Journal - STI ETF

I bought 9 lots (1 lot of 100 shares) of STI ETF via FSMOne in December 2018.

I don't think there was much cost savings from buying in bulk because I only put 3k in the account.
I was too greedy. I wanted to buy at the lowest point. So once I saw the prices increased to 3.22, I bought immediately, thinking this was a signal of a price increase. However that day was an anomaly. After that day, prices continued dipping as usual.

I learnt a lesson to just buy at a dip, and not to look at the 'minimum'. It's hard to accurately time the market. But I don't regret buying into STI ETF at that price much. Because over 2019, the prices increased steadily.

Trading Journal - Funding Societies

I discovered Funding Societies, a P2P lending platform where I would lend money to SMEs to fund their businesses. I decided to try it out, so I just put in 1k in August 2018 to try out.

Reflections - Strong emotions in investing

During the period of time after I got my scholarship, I had intense feelings towards investing. I wanted to invest in the right time and would time the market. On hindsight that wasn't a very healthy outlook towards investing and money. With the 10k goal, while it pushed me to be more financially prudent, it also caused a lot of anxiety with regards to investing and spending.

I was anxiously waiting for the scholarship money, waiting to invest. When the emotions are strong, this is why I shouldn't invest because I would make rash decisions. There was no logical decision as to why I should buy into an investing instrument. I just had blind faith, hoping it would pay money over the long run.

When I have strong emotions, I think what I should do is to not touch that money, and put it in a high interest savings account. Of course while I thought of consulting people who were good with money, I didn't feel comfortable approaching my parents for help, and they discouraged me from investing in the stock market too. My friends weren't that prudent with investing either.

Trading Journal - STI ETF

I stopped the regular savings plan with POSB because I realised the expense fees are really high as compared to if I bought at a lump sum. I found FSMOne that has lower investing fees. I also realised I have been making losses with this investment. At first I thought index funds would not lose money because of automatic rebalancing etc. But when the market is not doing well as a whole, index funds lose money.

I also learnt that in Singapore it makes more sense to create my own stock portfolio because with STI ETF I am paying for the top 30 companies. But if I create my own stock portfolio I can focus my investments in a few companies.

Does this mean I will stop investing in STI ETF? No. It just means I will time the market. Yes, timing the market is not a good idea. However I think it makes sense to wait for the prices to dip below average and buying more during a dip, then to blindly buy into the index when it is overpriced. Because the STI ETF does not increase in price over time.

Trading Journal - SSB

I liquidated March and April SSB. I learnt the technique of swapping SSB investments. Eg if a previous SSB issue had lower interest rates than the current one, I will liquidate low interest ssb for new ssb. On hindsight I shouldn't have done that because I didn't earn enough accrued interest to pay for the application fee. So I made a slight loss.

I think what I should have done is to buy the current SSB, wait a few months before liquidating. Since I didn't need the money urgently, I could afford to put more money in the SSB investments. I also learnt that I didn't need to hurry to invest and should have waited and prepared for good investing opportunities.

Trading Journal - SSB

I think I spent $1000 on August 2018 SSB. Because interest rates were increasing and the previous point on saving on the application fee.

Trading Journal - STI ETF

I bought 29 units of STI ETF, I think in July 2018. Prices started to dip and I was worried about my investments. But I didn't pull out my investments because I believed the price would increase one day since it is an index fund with automatic rebalancing.

Also I didn't want to lock in my losses by cashing out.

Trading Journal - SSB

I think it was around this point where I increased the amount I invested. Because I need to pay an application fee per trade I make. So it was better for me to invest more in one go. If I remember correctly, I bought July SSB for $1000.

Trading Journal - STI ETF

I bought 28 units of STI ETF on June 2018.

Trading Journal - SSB

I bought June SSB for $500 in June 2018, I think.

Trading Journal - STI ETF

I bought 27 units of STI ETF in May 2018.

Trading Journal - SSB

I bought $500 of SSB in May 2018.

Trading Journal - STI ETF

I bought 27 units of STI ETF at April 2018.

Trading Journal - STI ETF

I bought 27 units of STI ETF in March 2018. Price increased. At that time I was happy for the little price increase, as compared to if I kept the money in the bank.

Trading Journal - April SSB

I bought April's SSB.

Trading Journal - March SSB

Singapore Savings Bond was also one of my initial investments. Initial investing amount is $500, with $2 application fee. It is easy because I didn't need a brokerage account, just a CDP account. And I can apply for the bond via a bank, so it is easy application. Every month I will excitedly wait for the new bonds lmao. As I continued my investing journey, I realised SSB gives really low interest lmao, as compared to other financial instruments. But investing also has risk, and I think the low risk nature of ssb helps beginners to get started.

I bought the March SSB.

Trading Journal - STI ETF

STI ETF was my first investment. Reason being I did not need a CDP account to start investing using POSB Invest Saver and minimum investing amount is $100. On hindsight, I invested during a bad timing and Singapore index funds don't do as well as US index funds which increases prices over time. Singapore stock indices just increases and decreases by the same amount, so I realised that the timing is important.

I bought 28 units of STI ETF, I think in February 2018.

Financial Goals - 2019

For now, my financial goals will include scholarship monies, because I am actively investing with the scholarship money. I will divide this into three tiers, so I can continue to push myself even though I have already achieved my initial goal. After all, life is about continuously improving myself.

Initial tier: 30k
Level 2: 35k
Level 3: 40k

With my scholarship money, I think I'll achieve 30k relatively easy. But to have more money I'll need to save and invest wisely. I am also trying to find gigs to do (eg FnB, or programming work) so I can sustain myself. I want to do an external internship so I can learn more too.

Financial Goals - 2018

Last year, I set a financial goal for me to reach 10k in one year. This is quite substantial as I am just a student and do not hold a full time job. So my money will come from savings + parent's allowance. Here were some things I did:

-Worked at FnB. These places are good as they provide meal and transport allowance, thus I would not have that much expenses. FnB customers will also tip occasionally, depending on the quality of customer service I am able to provide. However the work is physically demanding and I realised I did not know how to interact well with customers and the staff there. This is when I realised the importance of interpersonal communication skills.

-Did an internship. While the internship does not pay a lot (800 before CPF), I learnt a lot of programming/technical expertise from the job. I had good supervisors and met helpful interns who were willing to share some tips with me. I believe this helped me land my scholarship as well. Food there was also relatively cheap as the canteen food was subsidised. Transport wise, I did not spend a lot since my dad was willing to drive me to work. Definitely a much better environment than FnB.

-Tuition. Definitely tuition earns a lot more than FnB, but the amount I earn is depending on how much I hustle. There is a limit to how much I can hustle per day because I needed to factor in time taken to prepare for lessons. This job allowed me to manage a business in a way. I needed to advertise myself to potential clients, I needed to learn how to deal with clients. I needed to manage payments, and chase clients for patients. Money was good, but increasingly difficult to manage workload once university started. I also realised I wasn't as good a teacher as I thought.

Teaching is a job that requires a lot of commitment, patience, and interpersonal communication skills. The students typically will not tell you when they don't understand. So as a teacher I also need to read their body language, and make them comfortable with me. I learnt how to code in Latex, I learnt the aspects of managing a business. But perhaps I'm not as good as I thought I was, so I am slowly letting go of this teaching career. I think I should just focus on programming expertise.

-Scholarship. The annual payments alone are much more than 10k. But still I wanted to earn 10k of my own money, so I disregarded the scholarship as a contribution to my 10k goal. I earnt the remaining via tuition. But since my dad stopped giving me allowance, it was harder for me to reach my 10k goal. My expenses also increased a lot since I stopped having meals at home. The stock mrket also wasn't doing well so despite my investments, it was harder for me to reach 10k.

At the end, while I couldn't reach 10k in this year alone, I reached it around January 2019. I think it was still a journey that taught me a lot of skills. I had to learn to persevere even with bad jobs and a toxic environment. I had to learn how to protect myself while freelancing (tuition). I learnt how to talk to people etc. I got myself a scholarship. And I learnt to be more financially literate.