Saturday, February 25, 2023

Operations on Python Dictionaries

 In previous chapter "python Dictionaries" we have detailed  how to create a python dictionary and insert an element to python dictionary. In this chapter we will look into more operations on python dictionaries. Here we will be using the dictionaries created in previous chapter to demonstrate different operations. Two dictionaries created in previous chapter are as below



Accessing keys and values: 


Accessing Individual Elements:

Dictionary elements are key value pairs, dictionary individual elements are accessed using the keys


Deleting/Removing Dictionary Elements:

Deleting/Removing of elements from dictionary is done using the del keyword. del deletes the key value pair from the dictionary. Dictionary element to be deleted is accessed using the key

eg: del dict[key] 

Element 10 is deleted from the dictionary using the del keyword. Dictionary elements are shown prior and after deletion of element 10.

pop on Dictionary Element:

pop deletes key value pair from dictionary and returns the value of the deleted element. Dictionary element to pop is accessed using the key.

eg: dict.pop(key)

In above example element A is popped from dict2 and value of A is returned after pop operation

update on Dictionary Element:

update keyword inserts a new element if key is not present in the element list. value of key is updated when element exists in the dictionary. Dictionary does not support duplicate keys.

eg: dict.update({key:value})


Renaming Dictionary Key:

To achieve this functionality, use pop operation which deletes the element and returns value of that key. Using the value returned during pop operation, insert a new element to dictionary.



Python dictionaries

Here we will be discussing an important python data type dict. Python dict is an unordered collection of items. Each dictionary item holds a key:value pair, python dictionaries are optimized to retrieve values when key is known.
In python, an empty dictionary is defined using empty curly braces {}.

Inserting an Element to Python Dictionary:
Length of dictionary is 0 zero, dictionary do not contain any element and its empty. We will see how we can add elements to an empty dictionary.

Elements can also be added during the initialization of dictionary itself. Let us see an example 

Dictionary created above has strings in both keys and values. It can also contain mixed data types. Python Dictionary is a heterogenous.

In the next chapter operations on Python Dictionaries we will discuss different operations on dictionary like accessing elements, updating elements, removing elements, Listing all the keys  

Wednesday, February 22, 2023

Python Program Convert Text to Speech

In this article we will see how to convert text to speech in python and the libraries required by python program to enable this functionality.

Lets start with Offline Text to Speech conversion, to achieve this install pyttsx3 library using the command pip install pyttsx3

import pyttsx3

Initialize the Text to Speech library by invoking init function

TXT2SPCH_ENGINE =  pyttsx3.init()

text = "Python programming makes coding simple"

TXT2SPCH_ENGINE.say(text)

To play the converted speech

TXT2SPCH_ENGINE.runAndWait()

This library also provides different properties that can be set on the speech like rate (speed of voice), voice (different types of voices), save_to_file (save speech to a file).

rate = TXT2SPCH_ENGINE.getProperty("rate")

print(rate)

Default rate is 200. Setting any value above 200 sets the voice to a faster rate and value below 200 sets the voice to a slower rate.

faster rate:

TXT2SPCH_ENGINE.setProperty("rate", 300)

slower rate:

TXT2SPCH_ENGINE.setProperty("rate", 100)

Fetch the details of all voices available in the library

voices = TXT2SPCH_ENGINE.getProperty("voices") 

Set a new voice to the speech engine

TXT2SPCH_ENGINE.setProperty("voice", voices[1].id)

Saving Speech to file

TXT2SPCH_ENGINE.save_to_file(text, "audioSpeech.mp3")

A sample program with complete details is available at GitHub The program reads the input from a file and converts the text to speech.

Saturday, February 18, 2023

Python Program to fetch Live Stock Data from NSE

To process live data from NSE using python we need two libraries nsepy and nsetools. We can extract all the details like Last Traded price, Total Traded Quantity, Delivery Quantity, Upper Price Band and all other values on real time basis for a particular stock from NSE. In the below example we have shown an example to fetch last traded price and close price. 

In the next program we will use this data to evaluate technical indicator values.


import os

os.system('pip install nsepy')

os.system('pip install nsetools')


import pandas as pd


from nsepy.live import get_holidays_list

from datetime import date, timedelta


from nsetools import Nse

import nsepy as NSE


nse = Nse()


all_stock_codes = nse.get_stock_codes()

symbols = all_stock_codes.keys()

series = "EQ"

for data_symbol in symbols:

    tradingSymbol = data_symbol

    series = "EQ"

    quote = NSE.live.get_quote(symbol=tradingSymbol)

    stock_data = quote["data"]

    #print(pd.DataFrame(quote["data"]).T)

    if(len(stock_data) == 0):

      continue

    Close_Price = stock_data[0]["closePrice"]

    Last_Price = stock_data[0]["lastPrice"]

    print('symbol: {}, LastPrice: {}, ClosePrice: {}'.format(tradingSymbol, Last_Price, Close_Price))


Source Code can be downloaded from GitHub

Friday, February 17, 2023

Python Program to fetch historical Stock Data from NSE

To fetch historical data from NSE using python we need two libraries nsepy and nsetools.End date is set as current date and start date is set to a value for the period that is decided to fetch the historical data. Here we fetch the historical data for a period of 365 days. In the next program we will use this data to evaluate technical indicator values.


import os

os.system('pip install nsepy')

os.system('pip install nsetools')


import pandas as pd

from nsepy import get_history as gh

import dateutil.relativedelta as dr

import math

from nsepy.live import get_holidays_list

from datetime import date, timedelta

from nsetools import Nse

nse = Nse()


all_stock_codes = nse.get_stock_codes()

symbols = all_stock_codes.keys()

dt_today = date.today()

series = "EQ"


for data_symbol in symbols:

    tradingSymbol = data_symbol

    endDate = dt_today

    startDate = endDate - dr.relativedelta(days=365)

    series = "EQ"

    stockData_EQ = pd.DataFrame()

    stockData_EQ = gh(symbol=tradingSymbol, start=startDate, end=endDate,index=False, futures=False, option_type="",

                expiry_date=None, strike_price="",series='EQ')

    print(stockData_EQ)


program can be downloaded from GitHub

AES Encryption and Decryption using OpenSSL in CPP

#include <iostream>

using namespace std;

#include <string>

#include <openssl/evp.h>

#include <openssl/objects.h>


/*

* Define your own KEY for Encryption and Decryption of Data

*/

static const unsigned char DCPKey[] = {0xC2,0x3B,0x73,0xCC,0xF0,0x2E,0x4D,0xBA,

0xAF,0xDE,0x73,0x54,0x90,0xCD,0xAB,0xEF,

0xA1,0xC8,0x02,0x3A,0xFC,0x40,0xA8,0xB4,

0xB4,0x70,0x0A,0x3E,0xCA,0xA7,0x04,0xE3};


string AES_Decrypt(string ENCstr)

{

EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();

EVP_CIPHER_CTX_init(ctx);

EVP_CIPHER_CTX_set_padding(ctx, 0);

int ret = EVP_DecryptInit_ex(ctx, EVP_aes_256_cfb(), NULL, DCPKey, NULL);

    unsigned char* result = new unsigned char[ENCstr.length()]; // Make a big enough space

    int *len1 = new int();;

    ret = EVP_DecryptUpdate(ctx, result, len1, (const unsigned char*)ENCstr.data(), ENCstr.length());

    int *len2 = new int();

    ret = EVP_DecryptFinal_ex(ctx, result+ *len1, len2); 

    ret = EVP_CIPHER_CTX_cleanup(ctx);

    string res((char*)result, *len1+ *len2);

    delete[] result;

delete len1;

delete len2;

EVP_CIPHER_CTX_free(ctx);


    return res;

}


string AES_Encrypt(const std::string source)

{

EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();

EVP_CIPHER_CTX_init(ctx);


    int ret = EVP_EncryptInit_ex(ctx, EVP_aes_256_cfb(), NULL, DCPKey, NULL);

EVP_CIPHER_CTX_set_padding(ctx, 0);

    unsigned char* result = new unsigned char[source.length() + 64]; // Make a big enough space

    int *len1 = new int();

    ret = EVP_EncryptUpdate(ctx, result, len1, (const unsigned char*)source.data(), source.length());

    int *len2 = new int();

    ret = EVP_EncryptFinal_ex(ctx, result+*len1, len2); 

    ret = EVP_CIPHER_CTX_cleanup(ctx);

    std::string res((char*)result, *len1 + *len2);

    delete[] result;

delete len1;

delete len2;

EVP_CIPHER_CTX_free(ctx);

    return res;

}


int main(int argc, char* argv[])

{

cout << "AES Encryption Decryption in progress.. Keep Waiting" << endl;


char buf[1024*100];

    FILE* ifp = fopen("input.txt", "rb");

  int bytes = fread(buf, 1, 1024*100, ifp);

  fclose(ifp);

std::string source(buf, bytes); // binary data


string Encrypted_Data = AES_Encrypt (source);

//cout << "Encrypted Data: " << Encrypted_Data << endl;

FILE* efp =  fopen("encrypted.txt", "wb");

  fwrite(Encrypted_Data.data(), 1, Encrypted_Data.length(), efp);

fclose(efp);


string Decrypted_Data = AES_Decrypt (Encrypted_Data);

FILE* dfp =  fopen("output.txt", "wb");

  fwrite(Decrypted_Data.data(), 1, Decrypted_Data.length(), dfp);

fclose(dfp);

return 0;

}

Compilation:
g++ -o aes AES.cpp -lssl -lcrypto
./aes

input.txt -- Source data to encrypt
encrypted.txt -- Encrypted Source Data after processing
output.txt -- Decrypted Data

sample contents of input.txt
[openssl]
CPP program to encrypt data using openSSL library
Also decrypt the same using openSSL library
Using builtin cipher Algorithm present in OpenSSL

Code can be accessed from GitHub

Operations on Python Dictionaries