Contemporary – Dinesh Thakali https://dineshthakali.com.np A Perspective View Fri, 09 Jun 2023 15:38:30 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 Scrutinizing Stock Prices in Eye of Benford’s Law Using Python https://dineshthakali.com.np/scrutinizing-stock-prices-in-eye-of-benfords-law-using-python/ https://dineshthakali.com.np/scrutinizing-stock-prices-in-eye-of-benfords-law-using-python/#respond Fri, 09 Jun 2023 15:34:41 +0000 https://dineshthakali.com.np/?p=384

The Law

One and half decade back while I was pursuing my Chartered Accountancy, I had come across interesting topic on fraud detection in accounting and taxation, using Benford’s Law. Benford’s Law is nothing complex, it just states that unless any data is manipulated, the occurrence of first digit of naturally occurring numbers follows a pattern and shows consistent probability of occurrence. This is because of simple logic that the first digit if it is 1 must increase by 100 percent to change to 2 while for 2 to change to 3, it only needs to increase by 50 percent. Newcomb first noticed and Frank Benford rediscovered this occurrence of logarithmically decaying distribution of first digit from 1 to 9 represented by the formula.

P(D1=d) = log10(1 + 1/d) (Where d is the number from 1 to 9)

Being in a role of Investment Banker at present, I wondered whether the often controversy of anomalies in the trading of stock in market could be scrutinized using same law. While there seemed difficulty as for Benford’s Law to hold true, there needs to be large sample size, but manipulations or malpractices in any trading stock happens for a short period. However, few have tried to scrutinize the rampant trading manipulations of cryptos like Bitcoin. This law however has been effectively used in fraud detection in accountancy, taxation, elections etc.

Dataset

For veracity of whether the Benford’s Law applies truly, I took the NEPSE Closing prices from the inception. Further data of closing prices of two highly volatile scrips from Finance Companies Sector was taken for testing purpose.

Python Codes

Step 1-Import necessary Python Libraries and Defining Benford’s Percentages

#Importing required Libraries

import numpy as np

import pandas as pd

import collections

import matplotlib.pyplot as plt

#Probabilities as per Benford’s Law

benfords_prob = [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6]

Step 2-Import NEPSE Closing Indexes and Sample Finance Company Prices

#Reading closing index of NEPSE

NEPSE_data = pd.read_csv("NEPSE.csv")
NEPSE_close=NEPSE_data["Close"]
 #Reading prices of sample Finance Company No. 1
F01_data = pd.read_csv("F01.csv")
F01_data.columns = "Date","Prices"
F01_prices=F01_data["Prices"]

#Reading prices of sample Finance Company No. 1

F02_data = pd.read_csv("F02.csv")
F02_data.columns = "Date","Prices"
F02_prices=F02_data["Prices"]

Step 3-Creating Function for the purpose of calculating percentage

#Function to calculate percentage of first digit occurrences

def calc_percentage(data):
     first_digit_percentage = [] #Defining List to accumulate values
     first_digits = list(map(lambda n: str(n)[0], data))
     first_digit_frequencies = collections.Counter(first_digits)
     for n in range(1, 10):
        data_frequency = first_digit_frequencies [str(n)]
        data_frequency_percent = (data_frequency / len(data))*100
        first_digit_percentage.append(data_frequency_percent)
     return (first_digit_percentage)

Outcomes (Visualization)

Step-4 Plotting and Visualizing the Graphs

#Calculating first digit of NEPSE closing prices and plotting using Matplotlib alongside Benford’s line

x=np.arange(1,10)
y=calc_percentage(NEPSE_close)
plt.title("Fig 1: Benford vs NEPSE First Digit Occurences")
plt.xlabel("First Digit")
plt.ylabel("Occurance %")
plt.plot(x,y,label='NEPSE',linewidth=3,linestyle="dashed")
plt.plot(x,benfords_prob,label='Benford',linewidth=3,linestyle="solid")
plt.grid()
plt.legend()

#Calculating first digit of Sample Finance Co # 1 Prices and plotting using Matplotlib alongside Benford’s line

x=np.arange(1,10)
y=calc_percentage(F01_prices)
plt.title("Fig 2: Benford vs Finance Co # 1 First Digit Occurrences")
plt.xlabel("First Digit")
plt.ylabel("Occurance %")
plt.plot(x,y,label='F01 Prices',linewidth=3,linestyle="dashed")
plt.plot(x,benfords_prob,label='Benford',linewidth=3,linestyle="solid")
plt.grid()
plt.legend()
#Calculating first digit of Sample Finance Co # 2 Prices and plotting using Matplotlib alongside Benford's line
x=np.arange(1,10)
y=calc_percentage(F02_prices)
plt.title("Fig 3: Benford vs Finance Co # 2 First Digit Occurrences")
plt.xlabel("First Digit")
plt.ylabel("Occurance %")
plt.plot(x,y,label='F01 Prices',linewidth=3,linestyle="dashed")
plt.plot(x,benfords_prob,label='Benford',linewidth=3,linestyle="solid")
plt.grid()
plt.legend()

Conclusions:

While as initially disclaimed, Benford’s law can not be litmus test for finding manipulations, but given that there is adequately large data, the prescribed probability distribution of Benford’s Law should certainly hold true if it is naturally occurring data. In Figure No. 1 when NEPSE Closing Indexes are plotted over Benford’s distribution, the plots seem to be nearly overlapping each other except at digit 6 and 7. Indexes which are mix of large number of various scrips can hardly be manipulated in huge amount and hence seems to follow the Law. In case of sample Finance Companies which had largely volatile price movements in recent periods, the plot seemed hugely deviating from the Law specially where the first digit is 1 (so possibly somebody wanted to keep prices above 1000 😉)

CA. Dinesh Thakali (Author is employee of Prabhu Bank Ltd and currently Managing Director at Prabhu Capital Ltd. Views expressed are personal and Author intends only to illustrate the results of Law but doesn’t prescribes or authenticates usage of the methods for any purpose) —Published in ShareSansar.com — 2022-April-18

]]>
https://dineshthakali.com.np/scrutinizing-stock-prices-in-eye-of-benfords-law-using-python/feed/ 0
Towards premature maturity https://dineshthakali.com.np/towards-premature-maturity/ Sun, 13 Oct 2019 06:00:52 +0000 http://www.dineshthakali.com.np/?p=270

As a student, I was an ardent fan of Financial Times columnist Lucy Kellaway, who wrote a regular column on modern corporate culture. A successful writer, she suddenly interrupted her regular profession to start teaching and establishing Now Teach, a forum to take onboard other successful professionals to take a break and start teaching.

On July 13, 2018, she admitted that though her change of the regular profession had many hiccups, the foremost being her slashed income by 80 per cent, she said it was wonderful to start all over again and that there seemed a lot of people out there who felt the same way.

One revered musician in his 90’s said in an interview, “Life goes like a lightening, I just feel like I blinked my eyes, and 90 years have passed already.” I had a similar feeling the other day when I sat with my college friend for lunch. It seemed like yesterday that we were together jogging or scoring baskets in the basketball court or going up and down the hills of Nainital. Alas, that was 20 years ago. I realized that we had been running with life so hard that we seem to have missed what we went through in between.

Modern life has become such that we are running on an inescapable treadmill of time. Only its ambience changes to give us the different flavors of life, like graduation, jobs, marriage, children and promotions.

The realization that life’s too short for worries and stress is coming faster to the new generation. Every now and then we hear them say, “Why worry so much? What’s in life?” Amazingly that was what we used to hear from our grandparents in our childhood. Come holidays and there are flocks of people now trying to go out on a vacation, even to destinations abroad.

The determination to lead a quality life has got diminished by being confined to the mundane routine life. We are being time and again misled into believing that happiness means money, jobs, promotion and respect. Many banker friends, who are well revered in their profession, want to leave the job the very next day as they feel suffocated.

Recently I met a senior banker, who pointed to packed personal stuffs, ready to move out at any instance. A cousin sister of mine, who recently left a good bank job, said about her new life, “To be frank, I’m enjoying this phase, I loved my work, but I was not happy with the everyday routine”.

Indeed, we seem to be moving towards premature maturity, perhaps for good.

 

(Published in The Himalayan Times on 2019 October 13)

]]>
Micro Woes https://dineshthakali.com.np/micro-woes/ Mon, 29 Sep 2008 07:10:00 +0000 http://www.dineshthakali.com.np/?p=296

Many friends of mine compare my bike wid a horse, and I have no option other than to accept it coz its mileage is such that it eats like what horse eats gram. However its not the cause I don't prefer riding bike, its no more same passion when I used to ride my uncle's or brother's bike without asking them (the workshop ppl taught me how to direct the line and start without key). Unless extremely needed, I give complete rest to my metal giant.

 
That brings to the main story. As riding a cab is jus like being robbed soberly emptying your wallet without protest, micro busses are the very next and only option (forget abt busses unless u have some quarrel wid time and wanna kill it). If you are from an urban area and haven't seen how people stack lots and lots of hay inside a sack, practical illustration is a micro bus (for proper illustration observe during late hours or office time). I remember my management story where the professor fills up whole the bottle wid large stones and asks is the bottle full? Answer comes yes and he fills it with pebbles and asks again is it full? Ans comes yes again and he goes on till he fills it with water. Same is the case with micro busses. Firstly the seats are to go, ppl who ride micro wud be astonished to know that it has only 14 valid seats. Then the slang fuche starts like a meticulous professor. He adjusts 5 in last seat, 3 each in 3 rows of mid seats, 5 above the engine turning backwards (its not seat at all hae), 3 or 4 in front seat and 3 in door side window. There it goes altogether 27, thats double of it.
 
Ppl who don't get on micro bus wud think thats enough, but who have got the taste of its ride wud know that its jus half filled. Now real filling up goes, here's the real test of the skill of the "khalasi" (for stubborn passengers there's the big boss on the steering wheel). You go a bit back, u get up the stair, you turn left, you get in between, you get a bit further inside, you catch here, you hang outside and last but not least you get up the hood. Worst routes I've faced are the swayambhu route through naya bazaar, which unfortunately is my route and other is bypass jumbo. You never get a seat, if you get its worse coz you will get over a dozen ppl taking your support leaning over you. Moreover when there's time to get off, unless you jump just like the frog that our finance minister often illustrated during budget, you'll get stuck.
 
You might think its enough, but let me end it like this have you got on the roller coaster in Bhrikuti Mandap? If not, similar is the experience the way micro drivers ride. Added to the entertainment is the bumpy roads which is like a "find differences" puzzle for a kid between black topped and horse road. You will occasionally see the black pitched road on your ride, bit of patches actually. So get on the micro bus leaving all your cars and bikes at home, its the micro woes, you get to your destination and all free fun. Oh I almost forgot, there's fun show also going on in between of the fake cards with rubbered dates, replaced photos and fake signatures.
]]>