My First Python Program: pyTrader

+4 Tommy Hillis · September 2, 2014
After watching Buckys last Python tutorial, I made a program that can predict the future stock price for any company (sort of like his PHP analyzer). I haven't actually tested it to see how accurate it is yet, but here it is.

How it Works
1. For each company, it first looks to see how the stock performed today. Variables it looks at include price, volume, and some other ones.
2. After that, it then goes back in history and finds other days that were similar to today. So if the stock went up 3% today, the program will go back and find the other days in the past where it also went up 3%.
3. Once it has gathered a list of similar days, the program makes a prediction based on historical data, calculating how the stock performed the following days.

It can predict the next days stock price for any number of companies. Here is a sample of the final analysis:
Now analyzing: AAPL
Now analyzing: EBAY
Now analyzing: GOOG
Now analyzing: MSFT
Now analyzing: YHOO

***** Prediction based on days with similar Percent Change *****

YHOO -0.35189117152328875
GOOG -0.3229241180048356
AAPL -0.05089056076517642
EBAY -0.033978456511072716
MSFT 0.10128641300886525

***** Prediction based on days with similar RSI *****

MSFT -0.22206129453578888
GOOG -0.14577655735964987
YHOO 0.08582775182764119
EBAY 0.2477418274279587
AAPL 0.5824197058204221

***** Prediction based on days with similar Volume *****

GOOG -0.4442178534707114
AAPL -0.28230842550240626
EBAY 0.0009858754608797482
YHOO 0.05905834012331011
MSFT 0.26713050902447316

***** Final Prediction for next days Price Change *****

GOOG -0.30430617627839895
YHOO -0.06900169319077915
MSFT 0.04878520916584985
EBAY 0.0715830821259219
AAPL 0.08307357318427983


Here are the files:

main.py
import csv
import display
import downloader
import rsi
import stocks
import tickers

end_results = {}
end_results_RSI = {}
end_results_volume = {}
final_results = {}

ticker_list = tickers.tickers_to_list()
i = 0

# Loop through one company at a time
while i < len(ticker_list):
    ticker = ticker_list
    today_month = "11"  # current month - 1
    today_day = "32"  # current day + 1
    today_year = "2014"  # current year
    end_month = "0"  # January is 0
    end_day = "1"
    end_year = "2014"

    csv_url = downloader.create_csv_url(ticker, today_month, today_day, today_year, end_month, end_day, end_year)
    downloader.download_stock_data(ticker, csv_url)
    stock_data_file = r'stocks/' + ticker + '.csv'

    rowID = []
    date = []
    openPrice = []
    high = []
    low = []
    closePrice = []
    volume = []
    volumeDDT = []
    adjClose = []
    pctChange = []
    pctChangeDTT = []
    rsi14 = []
    rsi14DTT = []

    # Create lists from the .csv file
    idNumber = 0
    with open(stock_data_file, newline='') as f:
        stockData = csv.reader(f)
        firstLine = True
        for row in stockData:
            if firstLine:  # skip first line
                firstLine = False
                continue
            if len(row) == 0:
                break
            rowID.append(idNumber)
            date.append(row[0])
            openPrice.append(float(row[1]))
            high.append(float(row[2]))
            low.append(float(row[3]))
            closePrice.append(float(row[4]))
            volume.append(float(row[5]))
            adjClose.append(float(row[6]))
            idNumber += 1

    # Create volumeDDT list (find days that had similar trading volumes)
    x = 0
    while x < len(volume):
        v = abs(volume[0] - volume[x])
        volumeDDT.append(v)
        x += 1

    # Create pctChange list (calculate percent change for each day)
    x = 0
    while x < len(openPrice):
        pc = (closePrice[x] - openPrice[x]) / openPrice[x] * 100
        pctChange.append(pc)
        x += 1

    # Create pctChangeDTT list (find days that had similar changes in price)
    x = 0
    while x < len(pctChange):
        difference = abs(pctChange[0] - pctChange[x])
        pctChangeDTT.append(difference)
        x += 1

    # Create rsi14 list
    rsi14 = rsi.calculate_rsi14(closePrice)

    # Create rsi14DTT list (find the days with similar rsi 14)
    x = 0
    while x < len(rsi14):
        difference = rsi14[0] - rsi14[x]
        difference = abs(difference)
        rsi14DTT.append(difference)
        x += 1

    # Predict future stock price based on percent change similarity
    similar = stocks.get_similar_items(pctChangeDTT, 10)
    next_days_ids = stocks.get_next_days_ids(similar, pctChangeDTT)
    average = stocks.average_pct_change(next_days_ids, pctChange)  # returns predicted change
    end_results[ticker_list] = average

    # Predict future stock price based on RSI similarity
    similar_RSI = stocks.get_similar_items(rsi14DTT, 10)  # returns list of 10 similar items
    next_days_ids_RSI = stocks.get_next_days_ids(similar_RSI, rsi14DTT)
    average_RSI = stocks.average_pct_change(next_days_ids_RSI, pctChange)  # returns predicted change
    end_results_RSI[ticker_list] = average_RSI

    # Predict future stock price based on Volume similarity
    similar_volume = stocks.get_similar_items(volumeDDT, 10)  # returns list of 10 similar items
    next_days_ids_volume = stocks.get_next_days_ids(similar_volume, volumeDDT)
    average_volume = stocks.average_pct_change(next_days_ids_volume, pctChange)  # returns predicted change
    end_results_volume[ticker_list] = average_volume

    # Display the company currently being analyzed
    print('Now analyzing: ' + ticker_list)
    # Predict future stock price based on all 3 indicators combined
    final_results[ticker_list] = (average + average_RSI + average_volume) / 3
    i += 1


# Print out the final results
print('\n***** Prediction based on days with similar Percent Change *****\n')
display.print_sorted_dictionary(end_results)
print('\n***** Prediction based on days with similar RSI *****\n')
display.print_sorted_dictionary(end_results_RSI)
print('\n***** Prediction based on days with similar Volume *****\n')
display.print_sorted_dictionary(end_results_volume)
print('\n***** Final Prediction for next days Price Change *****\n')
display.print_sorted_dictionary(final_results)


tickers.py
# Get the list of companies to analyze from tickers/tickers.txt
def tickers_to_list():
   tickers = []
   with open(r'tickers/tickers.txt') as f:
       for row in f:
           row = str(row).strip()
           tickers.append(row)
   return tickers


downloader.py
from urllib import request


# Create the URL to download each companies data from Yahoo!
def create_csv_url(ticker, today_month, today_day, today_year, end_month, end_day, end_year):
   csv_url = 'http://real-chart.finance.yahoo.com/table.csv?s=' +\
             ticker +\
             '&d=' +\
             today_month +\
             '&e=' +\
             today_day +\
             '&f=' +\
             today_year +\
             '&g=d&a=' +\
             end_month +\
             '&b=' +\
             end_day +\
             '&c=' +\
             end_year +\
             '&ignore=.csv'
   return csv_url


# Download company data and save it to .csv file in 'stocks' folder
def download_stock_data(ticker, csv_url):
   response = request.urlopen(csv_url)
   csv = response.read()
   csv_str = str(csv).strip("b'")  # Save the string to a file
   lines = csv_str.split("\\n")
   dest_url = r'stocks/' + ticker + '.csv'
   fx = open(dest_url, "w")
   for line in lines:
       fx.write(line + "\n")
   fx.close()


rsi.py
def calculate_rsi14(closePrice):
    closePrice.reverse()
    rsi14 = []
    change = calculate_change(closePrice)
    gain = calculate_gain(change)
    loss = calculate_loss(change)
    avg_gain = calculate_avg_gain(gain)
    avg_loss = calculate_avg_loss(loss)
    rs = calculate_rs(avg_gain, avg_loss)
    x = 0
    while x < len(rs):
        y = 100 - 100 / (1+rs[x])
        rsi14.append(y)
        x += 1
    rsi14.reverse()
    return rsi14


def calculate_change(close_price):
    change = []
    x = 0
    while x < len(close_price):
        if x == 0:
            change.append(0)
            x += 1
            continue
        else:
            c = close_price[x] - close_price[x-1]
            change.append(c)
            x += 1
    return change


def calculate_gain(change):
    gain = []
    x = 0
    while x < len(change):
        if change[x] > 0:
            gain.append(change[x])
            x += 1
            continue
        else:
            gain.append(0)
            x += 1
    return gain


def calculate_loss(change):
    loss = []
    x = 0
    while x < len(change):
        if change[x] < 0:
            loss.append(abs(change[x]))
            x += 1
            continue
        else:
            loss.append(0)
            x += 1
    return loss


def calculate_avg_gain(gain):
    avg_gain = []
    x = 0
    while x < len(gain):
        if x < 14:
            avg_gain.append(0)
            x += 1
            continue
        elif x == 14:
            y = sum(gain[:15]) / 14
            avg_gain.append(y)
            x += 1
        else:
            y = (avg_gain[x-1] * 13 + gain[x]) / 14
            avg_gain.append(y)
            x += 1
    return avg_gain


def calculate_avg_loss(loss):
    avg_loss = []
    x = 0
    while x < len(loss):
        if x < 14:
            avg_loss.append(0)
            x += 1
            continue
        elif x == 14:
            y = sum(loss[:15]) / 14
            avg_loss.append(y)
            x += 1
        else:
            y = (avg_loss[x-1] * 13 + loss[x]) / 14
            avg_loss.append(y)
            x += 1
    return avg_loss


def calculate_rs(avg_gain, avg_loss):
    rs = []
    x = 0
    while x < len(avg_gain):
        if x < 14:
            rs.append(0)
            x += 1
        else:
            y = avg_gain[x] / avg_loss[x]
            rs.append(y)
            x += 1
    return rs


stocks.py
def get_similar_items(items, how_many=0):
    similar = []
    for i in items:
        if i == 0:
            continue
        if len(similar) < how_many:
            similar.append(i)
        else:
            if i < max(similar):
                similar.append(i)
                similar.remove(max(similar))
    return similar


def get_next_days_ids(items, original):
    ids_list = []
    for i in items:
        x = 0
        while x < len(original):
            if i == original[x]:
                ids_list.append(x-1)  # get tomorrows id
            x += 1
    return ids_list


def average_pct_change(ids, pctChange):
    x = []
    for i in ids:
        if i == 0:
            continue
        else:
            x.append(pctChange)
    predicted_change = sum(x) / len(x)
    return predicted_change


def print_list(items):
    for i in items:
        print(i)



display.py
def print_sorted_dictionary(end_results):
   sorted_list = [(k, v) for v, k in sorted([(v, k) for k, v in end_results.items()])]
   for key, value in sorted_list:
       print(key, value)

Post a Reply

Replies

Oldest  Newest  Rating
0 Abhijeet G · February 11, 2015
Great work :). i am having some problem executing it, is there any order of listing companies name in text file? and csv file is not generating>
  • 1

Python

106,960 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator