Tag Archives: python

Create csv file ordered with highest yield dividend paying stock

For this script to work Yahoo Finance is needed. It can be easily installed with pip. Stock tickers are taken from a file called tickers.txt.

#!/usr/bin/env python

import time
from yahoo_finance import Share

dict = {}
f = open("tickers.txt", "r")
for ticker in f.readlines():
        dividend = Share(ticker).get_dividend_yield()
        if dividend is not None:
                print ticker.rstrip()+": "+dividend
                if float(dividend) > 0:
                        dict[float(dividend)] = ticker.rstrip()

filename = "dividends-"+time.strftime("%Y%m%d")+".csv"
f = open(filename, "a")
f.write("Ticker, Dividend Yield, Dividend Share, Stock Price\n")
print "Ticker; Dividend Yield; Dividend Share; Stock Price\n"
for k in reversed(sorted(dict.keys())):
        escribir = dict[k]+","+str(k)+","+str(float(Share(dict[k]).get_dividend_share()))+","+str(float(Share(dict[k]).get_price()))+"\n"
        print dict[k]+";"+str(k)+";"+Share(dict[k]).get_dividend_share()+";"+Share(dict[k]).get_price()

When done it creates a csv (named dividends-YYYYMMDD.csv) file ordered by highest dividend yield paying stocks.

00:55:40 [me@server Finance]$ head -5 dividends-20160414.csv
Ticker, Dividend Yield, Dividend Share, Stock Price
00:55:49 [me@server Finance]$

Python mechanize to automate WordPress login

I had to play around with Mechanize lib to automate wordpress login. Proved out to be pretty handy.

#!/usr/bin/env python

from mechanize import Browser #pip install mechanize

br = Browser()
br.addheaders = [("User-agent","Python Script using mechanize")]

sign_in = br.open("https://www.wordpress.com/wp-login.php")  #the login url

br.select_form(nr = 0) #accessing form by their index. Since we have only one form in this example, nr =0.
br["log"] = "user@domain" #the key "username" is the variable that takes the username/email value
br["pwd"] = "passwd"    #the key "password" is the variable that takes the password value

logged_in = br.submit()   #submitting the login credentials

logincheck = logged_in.read()  #reading the page body that is redirected after successful login

print logged_in.code   #print HTTP status code(200, 404...)
print logged_in.info() #print server info
#print logincheck #printing the body of the redirected url after login


user@server: ~/Python $ python wordpress-login.py 
Server: nginx
Date: Fri, 04 Mar 2016 16:45:40 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 5762
Connection: close
Vary: Accept-Encoding
X-Frame-Options: SAMEORIGIN
X-ac: 1.ams _dfw
Strict-Transport-Security: max-age=15552000
X-UA-Compatible: IE=Edge

user@server: ~/Python $

If you uncomment the last line in the script above it would print out the HTML code of the logged in page.

Python script to download all NASDAQ and NYSE ticker symbols

Below is a short python script to get all NASDAQ and NYSE common stock tickers. You can then use the resulting file to get a lot of info using yahoofinance library.

#!/usr/bin/env python

import ftplib
import os
import re

# Connect to ftp.nasdaqtrader.com
ftp = ftplib.FTP('ftp.nasdaqtrader.com', 'anonymous', 'anonymous@debian.org')

# Download files nasdaqlisted.txt and otherlisted.txt from ftp.nasdaqtrader.com
for ficheiro in ["nasdaqlisted.txt", "otherlisted.txt"]:
        localfile = open(ficheiro, 'wb')
        ftp.retrbinary('RETR ' + ficheiro, localfile.write)

# Grep for common stock in nasdaqlisted.txt and otherlisted.txt
for ficheiro in ["nasdaqlisted.txt", "otherlisted.txt"]:
        localfile = open(ficheiro, 'r')
        for line in localfile:
                if re.search("Common Stock", line):
                        ticker = line.split("|")[0]
                        # Append tickers to file tickers.txt
                        open("tickers.txt","a+").write(ticker + "\n")

Project Euler number 11

Below is my solution to Poject Euler number eleven. I created back ordered array with the number and its positions on a 2D 20×20 array. The 4 corners 4×4 array products only the vertical and horizontal products where calculated since the diagonal products are calculated previously with the 16×16 array.

#!/usr/bin/env python

import time

start = time.time()
f = open("grid.txt", "r")
i = 0
j = 0
newList = []
List = []

# Create and array 20x20 converting members to int
for line in f:
        List[i] = map(int, List[i])
        i = i + 1

# Create an ordered array starting by highest number and writing also position
i = 0
j = 0
for i in range(len(List[i])):
        for j in range(len(List[i])):
sortedList = sorted(newList)
# backorderdList is an array containing an ordered number with its positions in array second entry.
backorderedList = sortedList[::-1]

max = 0
for member in backorderedList:
        if ((member[1][0] == 0) and (member[1][1] == 0)):
                # Multiply upper corner first four lines
                for x in range(4):
                        # Line multiplication
                        newmax = List[x][0]*List[x][1]*List[x][2]*List[x][3]
                        if (newmax > max):
                                max = newmax
                        # Column multiplication
                        newmax = List[0][x]*List[1][x]*List[2][x]*List[3][x]
                        if (newmax > max):
                                max = newmax

        elif ((member[1][0] == 0) and (member[1][1] == 16)):
                # Multiply upper right corner
                for x in range(4):
                        # Line multiplication
                        newmax = List[x][16]*List[x][17]*List[x][18]*List[x][19]
                        if (newmax > max):
                                max = newmax
                        # Column multiplication
                        newmax = List[0][x+16]*List[1][x+16]*List[2][x+16]*List[3][x+16]
                        if (newmax > max):
                                max = newmax

        elif ((member[1][0] == 16) and (member[1][1] == 0)):
                # Multiply lower left corner
                for x in range(4):
                        # Line multiplication
                        newmax = List[x+16][0]*List[x+16][1]*List[x+16][2]*List[x+16][3]
                        if (newmax > max):
                                max = newmax
                        # Column multiplication
                        newmax = List[16][x]*List[17][x]*List[18][x]*List[19][x]
                        if (newmax > max):
                                print max

        elif ((member[1][0] == 16) and (member[1][1] == 16)):
                # Multiply lower right corner
                for x in range(4):
                        # Line multiplication
                        newmax = List[x+16][16]*List[x+16][17]*List[x+16][18]*List[x+16][19]
                        if (newmax > max):
                                max = newmax
                        # Column multiplication
                        newmax = List[16][x+16]*List[17][x+16]*List[18][x+16]*List[19][x+16]
                        if (newmax > max):
                                max = newmax

        elif ((member[1][0] >= 3) and (member[1][0] <= 16) and (member&#91;1&#93;&#91;1&#93; >= 3) and (member[1][1] <= 16)):
                # column numbers from numbers not on edges
                newmax = List&#91;member&#91;1&#93;&#91;0&#93;-3&#93;&#91;member&#91;1&#93;&#91;1&#93;&#93;*List&#91;member&#91;1&#93;&#91;0&#93;-2&#93;&#91;member&#91;1&#93;&#91;1&#93;&#93;*List&#91;member&#91;1&#93;&#91;0&#93;-1&#93;&#91;member&#91;1&#93;&#91;1&#93;&#93;*List&#91;member&#91;1&#93;&#91;0&#93;&#93;&#91;member&#91;1&#93;&#91;1&#93;&#93;
                if (newmax > max):
                        max = newmax
                newmax = List[member[1][0]+3][member[1][1]]*List[member[1][0]+2][member[1][1]]*List[member[1][0]+1][member[1][1]]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                # line numbers
                newmax = List[member[1][0]][member[1][1]-3]*List[member[1][0]][member[1][1]-2]*List[member[1][0]][member[1][1]-1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                newmax = List[member[1][0]][member[1][1]+3]*List[member[1][0]][member[1][1]+2]*List[member[1][0]][member[1][1]+1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                # diagonal numbers
                newmax = List[member[1][0]-3][member[1][1]-3]*List[member[1][0]-2][member[1][1]-2]*List[member[1][0]-1][member[1][1]-1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                newmax = List[member[1][0]+3][member[1][1]+3]*List[member[1][0]+2][member[1][1]+2]*List[member[1][0]+1][member[1][1]+1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                newmax = List[member[1][0]-3][member[1][1]+3]*List[member[1][0]-2][member[1][1]+2]*List[member[1][0]-1][member[1][1]+1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                newmax = List[member[1][0]+3][member[1][1]-3]*List[member[1][0]+2][member[1][1]-2]*List[member[1][0]+1][member[1][1]-1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax

print "Max is: %d." % (max)
elapsed = (time.time() - start)
print "Elapsed time: %s seconds." % (elapsed)


Took the execution time idea from here.


user@server1: ~ $ python euler_11.py ; uname -a
Max is: 70600674.
Elapsed time: 0.0441608428955 seconds.
Linux server1 2.6.32-042stab106.4 #1 SMP Fri Mar 27 15:19:28 MSK 2015 x86_64 GNU/Linux
user@server1: ~ $

Small script to calculate future value

Heres a small script I wrote to calculate the future value.

#!/usr/bin/env python

# This script calculate the future value

iv = float(raw_input("Enter initial value: "));
rate = float(raw_input("Enter interest rate: "));
times = int(raw_input("Enter the amount of years: "));

fv = iv*((1 + (rate/100))**times)

print "Final amount is: %.2f." %fv