Home > other >  Basic python - calculating %change between close and open price
Basic python - calculating %change between close and open price

Time:12-14

I've got the following question and the challenging part of for me is to calculate the wanted value without using panda.

Question :

  1. Please download a CSV file containing the stock history of some companies, for example from:
    http://finance.yahoo.com/q/hp?s=GOOG
    http://finance.yahoo.com/q/hp?s=IBM
    http://finance.yahoo.com/q/hp?s=MSFT

(Download Data)
Save files giving them different names to a local folder on your drive

  1. Write a program that searches for CSV files with stock rates in a given folder and for every one of them:

  2. Calculates the percentage change between Close and Open price and adds these values as another column to this CSV file.
    You can replace the old file or create a new one.

Change = (Close-Open)/Open

  1. The output files can be stored in another folder
  2. You can use Python to download files. An example is given here:
    https://raw.githubusercontent.com/prubach/Python_Winter_2022_1/master/download_file.py
  3. Please do not use pandas, or only use it as an alternative way of implementing it along a more "manual" way using just python without any libraries.
from urllib import request
# Define the remote file to retrieve
url = 'https://query1.finance.yahoo.com/v7/finance/download/IBM?period1=1639213520&period2=1670749520&interval=1d&events=history&includeAdjustedClose=true'
# Define the local filename to save data
file_IBM = 'IBM.csv'
# Download remote and save locally
request.urlretrieve(url, file_IBM)

class Change:
    def __init__(self,o,c):
        self.open = o
        self.close = c
    def calc_percentage(self):
        return (self.c - self.o)/self.o

    r = Change(IMB.csv)

print(r.calc_percentage)

I tried to make a new column using an object-oriented format but it's not working. And how I am writing my code is I have my data file on a separate python page and I am writing the code on another page and faced some issues connecting these 2 pages

CodePudding user response:

with open('IBM.csv', 'r') as file: reader = csv.reader(file) for column in reader: print(column)

Okay, so far what I did was to use this code to read the data file I have. now I should use this formula (close - open)/open Now my question is how should I implement this formula into this code?!

CodePudding user response:

I know you are asking to not use libraries if possible, but have you considered using the following the built-in pandas function that calculates percentage changes:

pandas-pct_change

  • Related