File size: 2,206 Bytes
1f5a1dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

import datetime as dt
import logging
import os

import pandas as pd
import yfinance as yf


class FetchData:
    def __init__(self, ticker: str, fetchperiodinweeks: int = 12, debug=False):
        # set up logging
        if debug:
            self.logger_level = logging.DEBUG
        else:
            self.logger_level = logging.INFO
        self.logger = logging.getLogger(__name__)
        logging.basicConfig(level=self.logger_level)  # filename='TechnicalAnalysis.log',

        self.ticker = ticker
        self.fetchperiodinweeks = fetchperiodinweeks
    
    def run(
        self
        ) -> pd.DataFrame:
        """
        Fetches historical stock price data from Yahoo Finance.
        This method downloads historical stock price data for the specified
        ticker over a given period of weeks. The data is fetched on a daily
        interval and stored in a pandas DataFrame. If the download is successful,
        redundant ticker columns are removed, and logging information is
        recorded. In case of failure, an empty DataFrame is returned and an
        exception is raised.
        Returns:
        pd.DataFrame
            A DataFrame containing the historical stock price data with columns
            for open, high, low, close, volume, and adjusted close prices.
        Raises:
        Exception
            If the data fetching fails, an exception is raised with an error
            message.
        """

        period_start = dt.datetime.now() - dt.timedelta(weeks=self.fetchperiodinweeks)
        self.logger.info(f'Fetching price data for {self.ticker}')
        try:
            df = yf.download(
                self.ticker,
                start=period_start,
                end=dt.datetime.now(),
                interval='1d'
            )
        except Exception as e:
            self.logger.error(f'{e}')
            # create empty df
            df = pd.DataFrame()

        if df.shape[0] > 0:
            # get rid of the redundant ticker column
            df.columns = df.columns.droplevel('Ticker')
            self.logger.debug(df.head(10))
            self.logger.info(f'Fetched {df.shape[0]} rows for {self.ticker}')
        
        return df