Beispiel #1
0
class Watchlist(object):
    """Watchlist Class (** This is subject to change! **)
    ============================================================================
    A simple Class to load/download financial market data and automatically
    apply Technical Analysis indicators with a Pandas TA Strategy. Default
    Strategy: pandas_ta.AllStrategy.

    Requirements:
    - Pandas TA (pip install pandas_ta)
    - AlphaVantage (pip install alphaVantage-api) for the Default Data Source.
        To use another Data Source, update the load() method after AV.

    Required Arguments:
    - tickers: A list of strings containing tickers. Example: ['SPY', 'AAPL']
    ============================================================================
    """
    def __init__(self,
                 tickers: list,
                 tf: str = None,
                 name: str = None,
                 strategy: ta.Strategy = None,
                 ds: object = None,
                 **kwargs):
        self.tickers = tickers
        self.tf = tf
        self.verbose = kwargs.pop("verbose", False)
        self.debug = kwargs.pop("debug", False)
        self.name = name
        self.data = None
        self.kwargs = kwargs
        self.strategy = strategy

        if ds is not None:
            self.ds = ds
        elif isinstance(ds, str) and ds.lower() == "yahoo":
            self.ds = yf
        else:
            AVkwargs = {
                "api_key": "YOUR API KEY",
                "clean": True,
                "export": True,
                "export_path": ".",
                "output_size": "full",
                "premium": False
            }
            av_kwargs = kwargs.pop("av_kwargs", AVkwargs)
            self.ds = AlphaVantage(**av_kwargs)

    def _drop_columns(self,
                      df: pd.DataFrame,
                      cols: list = [
                          "Unnamed: 0", "date", "split_coefficient", "dividend"
                      ]):
        """Helper methods to drop columns silently."""
        df_columns = list(df.columns)
        if any(_ in df_columns for _ in cols):
            if self.debug:
                print(f"[i] Possible columns dropped: {', '.join(cols)}")
            df = df.drop(cols, axis=1, errors="ignore")
        return df

    def _load_all(self, **kwargs) -> dict:
        """Updates the Watchlist's data property with a dictionary of DataFrames
        keyed by ticker."""
        if self.tickers is not None and isinstance(self.tickers, list) and len(
                self.tickers):
            self.data = {
                ticker: self.load(ticker, **kwargs)
                for ticker in self.tickers
            }
            return self.data

    def load(self,
             ticker: str = None,
             tf: str = None,
             index: str = "date",
             drop: list = ["dividend", "split_coefficient"],
             file_path: str = ".",
             **kwargs) -> pd.DataFrame:
        """Loads or Downloads (if a local csv does not exist) the data from the
        Data Source. When successful, it returns a Data Frame for the requested
        ticker. If no tickers are given, it loads all the tickers."""

        tf = self.tf if tf is None else tf.upper()
        if ticker is not None and isinstance(ticker, str):
            ticker = str(ticker).upper()
        else:
            print(f"[!] Loading All: {', '.join(self.tickers)}")
            self._load_all(**kwargs)
            return

        filename_ = f"{ticker}_{tf}.csv"
        current_file = Path(file_path) / filename_

        # Load local or from Data Source
        if current_file.exists():
            df = pd.read_csv(filename_, index_col=index)
            if not df.ta.datetime_ordered:
                df = df.set_index(pd.DatetimeIndex(df.index))
            print(f"[i] Loaded['{tf}']: {filename_}")
        else:
            print(f"[+] Downloading['{tf}']: {ticker}")
            if isinstance(self.ds, AlphaVantage):
                df = self.ds.data(tf, ticker)
                if not df.ta.datetime_ordered:
                    df = df.set_index(pd.DatetimeIndex(df[index]))
            elif isinstance(self.ds, yfinance):
                print("[!] In Development")
                yf_data = self.ds.Ticker(ticker)
                df = yf_data.history(period="max")
                print(yf_data.info)
                print(df)

        # Remove select columns
        df = self._drop_columns(df)

        if kwargs.pop("analyze", True):
            if self.debug:
                print(f"[+] TA[{len(self.strategy.ta)}]: {self.strategy.name}")
            df.ta.strategy(self.strategy, **kwargs)

        df.ticker = ticker  # Attach ticker to the DataFrame
        return df

    @property
    def data(self) -> dict:
        """When not None, it contains a dictionary of DataFrames keyed by ticker. data = {"SPY": pd.DataFrame, ...}"""
        return self._data

    @data.setter
    def data(self, value: dict) -> None:
        # Later check dict has string keys and DataFrame values
        if value is not None and isinstance(value, dict):
            if self.verbose: print(f"[+] New data")
            self._data = value
        else:
            self._data = None

    @property
    def name(self) -> str:
        """The name of the Watchlist. Default: "Watchlist: {Watchlist.tickers}"."""
        return self._name

    @name.setter
    def name(self, value: str) -> None:
        if isinstance(value, str):
            self._name = str(value)
        else:
            self._name = f"Watchlist: {', '.join(self.tickers)}"

    @property
    def strategy(self) -> ta.Strategy:
        """Sets a valid Strategy. Default: pandas_ta.CommonStrategy"""
        return self._strategy

    @strategy.setter
    def strategy(self, value: ta.Strategy) -> None:
        if value is not None and isinstance(value, ta.Strategy):
            self._strategy = value
        else:
            self._strategy = ta.CommonStrategy

    @property
    def tf(self) -> str:
        """Alias for timeframe. Default: 'D'"""
        return self._tf

    @tf.setter
    def tf(self, value: str) -> None:
        if isinstance(value, str):
            value = str(value)
            self._tf = value
        else:
            self._tf = "D"

    @property
    def tickers(self) -> list:
        """tickers

        If a string, it it converted to a list. Example: "AAPL" -> ["AAPL"]
            * Does not accept, comma seperated strings.
        If a list, checks if it is a list of strings.
        """
        return self._tickers

    @tickers.setter
    def tickers(self, value: (list, str)) -> None:
        if value is None:
            print(f"[X] {value} is not a value in Watchlist ticker.")
            return
        elif isinstance(value, list) and [isinstance(_, str) for _ in value]:
            self._tickers = list(map(str.upper, value))
        elif isinstance(value, str):
            self._tickers = [value.upper()]
        self.name = self._tickers

    @property
    def verbose(self) -> bool:
        """Toggle the verbose property. Default: False"""
        return self._verbose

    @verbose.setter
    def verbose(self, value: bool) -> None:
        if isinstance(value, bool):
            self._verbose = bool(value)
        else:
            self._verbose = False

    def indicators(self, *args, **kwargs) -> any:
        """Returns the list of indicators that are available with Pandas Ta."""
        pd.DataFrame().ta.indicators(*args, **kwargs)

    def __repr__(self) -> str:
        s = f"Watch(name='{self.name}', tickers[{len(self.tickers)}]='{', '.join(self.tickers)}', tf='{self.tf}', strategy[{self.strategy.total_ta()}]='{self.strategy.name}'"
        if self.data is not None:
            s += f", data[{len(self.data.keys())}])"
            return s
        return s + ")"
        print('We have a MACD golden cross in weekly time frame. Buy ' +
              cell.value)
        # send an e-mail alert
        ezgmail.send(
            '*****@*****.**',
            cell.value + ' shows a MACD golden cross this week',
            'There is a MACD golden cross for ' + cell.value +
            ' during this week!')

    else:
        print('No signal')


# alphavantage API key
ts = AlphaVantage(api_key='##############', datatype='pandas')

for x in range(2, 103):
    try:
        cell = sheet['A' + str(x)]
        Macd = ts.data(function='MACD',
                       symbol=cell.value,
                       interval='weekly',
                       series_type='close',
                       fastperiod=12,
                       slowperiod=26,
                       signalperiod=9)

        Checking_MACD_cross()
    except:
        print("An error ocurred while trying to connect to Alphavantage API")
import pandas_ta as ta
from alphaVantageAPI.alphavantage import AlphaVantage 

ticker='CW'
AV = AlphaVantage(
        api_key='PUT YOUR API KEY HERE',
        premium=False,       
        datatype='json',
        export=False,
        export_path= 'C:/Users/Andy/Downloads',
        output='csv',
        output_size='full',
        clean=True,
        proxy={})

df = AV.data(symbol=ticker, function='DA') # daily adjusted
predper = 60 #number of days to predict ahead
print(f"Shape: {df.shape}")
df.set_index(['date'], inplace=True)
df.fillna(0.0, inplace=True)

df.to_csv (r'C:/Users/Andy/Downloads/pricedataCW.csv', index = 'date', header=True)
df = pd.read_csv('C:/Users/Andy/Downloads/pricedataCW.csv',
                usecols=['date','close'])
df.columns = ['ds', 'y']
m = Prophet(
    growth="linear",
    #holidays=holidays,
    #seasonality_mode="multiplicative",
    changepoint_prior_scale=30,
    seasonality_prior_scale=35,
Beispiel #4
0
def Checking_cross():
    #calculation for today's difference
    TEMA_50 = EMA_50.iloc[-1].loc['EMA']
    TEMA_200 = EMA_200.iloc[-1].loc['EMA']
    TDiff = TEMA_50-TEMA_200
    #calculation for yesterday's difference
    YEMA_50 = EMA_50.iloc[-2].loc['EMA']
    YEMA_200 = EMA_200.iloc[-2].loc['EMA']
    YDiff = YEMA_50-YEMA_200

    if ( YDiff<0 and TDiff>0 ):
        print('We have a golden cross of 50 EMA and 200 EMA! Buy '+cell.value)

        # Send an email alert
        ezgmail.send('*****@*****.**',cell.value+' shows a golden cross today ', 'There was a golden cross of 50 and 200 EMAs for '+cell.value+' It is good time for buying it!')

    else:
        print('No signal')

for x in range (2, 103):
    try:
        cell = sheet['A'+str(x)]
        EMA_50 = ts.data(symbol = cell.value, function = 'EMA', interval = 'daily', time_period = 50, series_type = 'close')
        EMA_200 = ts.data(symbol = cell.value, function = 'EMA', interval = 'daily', time_period = 200, series_type = 'close')

        print('Checking '+cell.value)
        Checking_cross()
    except:
        print("A problem occurred while connecting to Alpha Vantage API")
Beispiel #5
0
# The symbol='CW' is how you pick which ticker you are trying to analyze, 'DA' stands for daily adjusted data.
# predper is how many days ahead (periods ahead) to give a predicted value for.

# %%
ticker = 'CW'
AV = AlphaVantage(api_key='PUT YOUR API KEY HERE',
                  premium=False,
                  datatype='json',
                  export=False,
                  export_path='C:/Users/Andy/Downloads',
                  output='csv',
                  output_size='full',
                  clean=True,
                  proxy={})

df = AV.data(symbol=ticker, function='DA')
predper = 60  #number of days to predict ahead
print(f"Shape: {df.shape}")
df.set_index(['date'], inplace=True)
df.head()

# %% [markdown]
# The table above shows the very beginning cells in the dataframe, similar to an excel table.  Columns are labeled across the top.
#
# As a matter of good housekeeping, we're going to fill any N/A fields with a 0, which helps avoid computational errors that are hidden deep inside a csv file sometimes.

# %%
df.fillna(0.0, inplace=True)

# %% [markdown]
# Next export the dataframe to a csv and store it in the folder you've been using.
Beispiel #6
0
class TestAlphaVantageAPI(TestCase):
    @classmethod
    def setUpClass(cls):
        cls.test_data_path = C.TEST_DATA_PATH
        # Set premium to True to avoid API throttling for testing
        av = AlphaVantage(api_key=C.API_KEY_TEST, premium=True)

        # Minimum parameters
        cls.batch_parameters = {
            'function': 'BATCH_STOCK_QUOTES',
            'symbols': C.API_BATCH_TEST
        }
        cls.fx_parameters = {
            'function': 'CURRENCY_EXCHANGE_RATE',
            'from_currency': 'USD',
            'to_currency': 'JPY'
        }
        cls.sector_parameters = {'function': 'SECTOR'}
        cls.data_parameters = {
            'function': 'TIME_SERIES_DAILY_ADJUSTED',
            'symbol': C.API_DATA_TEST
        }
        cls.intraday_parameters = {
            'function': 'TIME_SERIES_INTRADAY',
            'symbol': C.API_DATA_TEST
        }
        cls.indicator_parameters = {
            'function': 'RSI',
            'symbol': C.API_DATA_TEST,
            'interval': 'weekly',
            'series_type': 'open',
            'time_period': 10
        }
        cls.digital_parameters = {
            'function': 'DIGITAL_CURRENCY_DAILY',
            'symbol': C.API_DIGITAL_TEST,
            'market': 'CNY'
        }

        # json files of sample data
        cls.json_batch = load_json(cls.test_data_path / 'mock_batch.json')
        cls.json_fx = load_json(cls.test_data_path / 'mock_fx.json')
        cls.json_sectors = load_json(cls.test_data_path / 'mock_sectors.json')
        cls.json_data = load_json(cls.test_data_path / 'mock_data.json')
        cls.json_indicator = load_json(cls.test_data_path /
                                       'mock_indicator.json')
        cls.json_digital = load_json(cls.test_data_path / 'mock_digital.json')

        # Pandas DataFrames of sample data
        cls.df_batch = av._to_dataframe('BATCH_STOCK_QUOTES', cls.json_batch)
        cls.df_fx = av._to_dataframe('CURRENCY_EXCHANGE_RATE', cls.json_fx)
        cls.df_sectors = av._to_dataframe('SECTOR', cls.json_sectors)
        cls.df_data = av._to_dataframe('TIME_SERIES_DAILY_ADJUSTED',
                                       cls.json_data)
        cls.df_indicator = av._to_dataframe('RSI', cls.json_indicator)
        cls.df_digital = av._to_dataframe('DIGITAL_CURRENCY_DAILY',
                                          cls.json_digital)

    @classmethod
    def tearDownClass(cls):
        del cls.test_data_path

        del cls.batch_parameters
        del cls.fx_parameters
        del cls.sector_parameters
        del cls.data_parameters
        del cls.intraday_parameters
        del cls.indicator_parameters
        del cls.digital_parameters

        del cls.json_batch
        del cls.json_fx
        del cls.json_sectors
        del cls.json_data
        del cls.json_indicator
        del cls.json_digital

        del cls.df_batch
        del cls.df_fx
        del cls.df_sectors
        del cls.df_data
        del cls.df_indicator
        del cls.df_digital

    def setUp(self):
        self.av = AlphaVantage(api_key=C.API_KEY_TEST)

    def tearDown(self):
        del self.av

    # tests of: batch, fx, sectors, data, intraday, and digital
    @patch('alphaVantageAPI.alphavantage.AlphaVantage._av_api_call')
    def test_batch(self, mock_av_api_call):
        mock_av_api_call.side_effect = [None, self.df_batch, self.json_batch]
        self.assertIsNone(self.av.batch(C.API_BATCH_TEST))
        self.assertIsInstance(self.av.batch(C.API_BATCH_TEST), DataFrame)
        self.assertIsInstance(self.av.batch(C.API_BATCH_TEST), dict)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._av_api_call')
    def test_fx(self, mock_av_api_call):
        mock_av_api_call.side_effect = [None, self.df_fx, self.json_fx]
        self.assertIsNone(self.av.fx(C.API_FX_TEST))
        # 4/7/2019 Stopped passing!?
        # self.assertIsInstance(self.av.fx(C.API_FX_TEST), DataFrame)
        # self.assertIsInstance(self.av.fx(C.API_FX_TEST), dict)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._av_api_call')
    def test_sectors(self, mock_av_api_call):
        mock_av_api_call.side_effect = [
            None, self.df_sectors, self.json_sectors
        ]
        self.assertIsNone(self.av.sectors())
        self.assertIsInstance(self.av.sectors(), DataFrame)
        self.assertIsInstance(self.av.sectors(), dict)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._av_api_call')
    def test_digital(self, mock_av_api_call):
        mock_av_api_call.side_effect = [
            None, self.df_digital, self.json_digital
        ]
        self.assertIsNone(self.av.digital(C.API_DIGITAL_TEST))
        self.assertIsInstance(self.av.digital(C.API_DIGITAL_TEST), DataFrame)
        self.assertIsInstance(self.av.digital(C.API_DIGITAL_TEST), dict)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._av_api_call')
    def test_intraday(self, mock_av_api_call):
        mock_av_api_call.side_effect = [
            None, self.df_sectors, self.json_sectors
        ]
        self.assertIsNone(self.av.intraday(C.API_DATA_TEST))
        self.assertIsInstance(self.av.intraday(C.API_DATA_TEST), DataFrame)
        self.assertIsInstance(self.av.intraday(C.API_DATA_TEST), dict)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._av_api_call')
    def test_data(self, mock_av_api_call):
        mock_av_api_call.side_effect = [None, self.df_data, self.json_data]
        self.assertIsNone(self.av.data('D', C.API_DATA_TEST))
        self.assertIsInstance(self.av.data('D', C.API_DATA_TEST), DataFrame)
        self.assertIsInstance(self.av.data('D', C.API_DATA_TEST), dict)

    # av_api_call tests
    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_batch(self, mock_requests_get, mock_to_dataframe):
        mock_requests_get.return_value = _mock_response(
            json_data=self.json_batch)
        mock_to_dataframe.return_value = self.df_batch

        av_api_call = self.av._av_api_call(self.batch_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 1)
        self.assertIsInstance(mock_to_dataframe(), DataFrame)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_batch_csv(self, mock_requests_get, mock_to_dataframe):
        self.av.datatype = 'csv'

        mock_requests_get.return_value = _mock_response(
            text_data=self.json_batch)

        av_api_call = self.av._av_api_call(self.batch_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 0)
        self.assertIsInstance(av_api_call(), dict)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_fx(self, mock_requests_get, mock_to_dataframe):
        mock_requests_get.return_value = _mock_response(json_data=self.json_fx)
        mock_to_dataframe.return_value = self.df_fx

        av_api_call = self.av._av_api_call(self.fx_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 1)
        self.assertIsInstance(mock_to_dataframe(), DataFrame)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_fx_csv(self, mock_requests_get, mock_to_dataframe):
        self.av.datatype = 'csv'

        mock_requests_get.return_value = _mock_response(text_data=self.json_fx)

        av_api_call = self.av._av_api_call(self.fx_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 0)
        self.assertIsInstance(av_api_call(), dict)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_sectors(self, mock_requests_get, mock_to_dataframe):
        mock_requests_get.return_value = _mock_response(
            json_data=self.json_sectors)
        mock_to_dataframe.return_value = self.df_sectors

        av_api_call = self.av._av_api_call(self.sector_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 1)
        self.assertIsInstance(mock_to_dataframe(), DataFrame)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_sectors_csv(self, mock_requests_get,
                                     mock_to_dataframe):
        self.av.datatype = 'csv'

        mock_requests_get.return_value = _mock_response(
            text_data=self.json_sectors)

        av_api_call = self.av._av_api_call(self.sector_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 0)
        self.assertIsInstance(av_api_call(), dict)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_data(self, mock_requests_get, mock_to_dataframe):
        mock_requests_get.return_value = _mock_response(
            json_data=self.json_data)
        mock_to_dataframe.return_value = self.df_data

        av_api_call = self.av._av_api_call(self.data_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 1)
        self.assertIsInstance(mock_to_dataframe(), DataFrame)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_data_csv(self, mock_requests_get, mock_to_dataframe):
        self.av.datatype = 'csv'
        mock_requests_get.return_value = _mock_response(
            text_data=self.json_data)

        av_api_call = self.av._av_api_call(self.data_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 0)
        self.assertIsInstance(av_api_call(), dict)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_intraday(self, mock_requests_get, mock_to_dataframe):
        mock_requests_get.return_value = _mock_response(
            json_data=self.json_data)
        mock_to_dataframe.return_value = self.df_data

        av_api_call = self.av._av_api_call(self.intraday_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 1)
        self.assertIsInstance(mock_to_dataframe(), DataFrame)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_intraday_csv(self, mock_requests_get,
                                      mock_to_dataframe):
        self.av.datatype = 'csv'

        mock_requests_get.return_value = _mock_response(
            text_data=self.json_data)

        av_api_call = self.av._av_api_call(self.intraday_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 0)
        self.assertIsInstance(av_api_call(), dict)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_indicator(self, mock_requests_get, mock_to_dataframe):
        mock_requests_get.return_value = _mock_response(
            json_data=self.json_indicator)
        mock_to_dataframe.return_value = self.df_indicator

        av_api_call = self.av._av_api_call(self.indicator_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 1)
        self.assertIsInstance(mock_to_dataframe(), DataFrame)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_indicator_csv(self, mock_requests_get,
                                       mock_to_dataframe):
        self.av.datatype = 'csv'

        mock_requests_get.return_value = _mock_response(
            text_data=self.json_indicator)

        av_api_call = self.av._av_api_call(self.indicator_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 0)
        self.assertIsInstance(av_api_call(), dict)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_digital(self, mock_requests_get, mock_to_dataframe):
        mock_requests_get.return_value = _mock_response(
            json_data=self.json_digital)
        mock_to_dataframe.return_value = self.df_digital

        av_api_call = self.av._av_api_call(self.digital_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 1)
        self.assertIsInstance(mock_to_dataframe(), DataFrame)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage._to_dataframe')
    @patch('alphaVantageAPI.alphavantage.requests.get')
    def test_av_api_call_digital_csv(self, mock_requests_get,
                                     mock_to_dataframe):
        self.av.datatype = 'csv'

        mock_requests_get.return_value = _mock_response(
            text_data=self.json_digital)

        av_api_call = self.av._av_api_call(self.digital_parameters)

        self.assertEqual(mock_requests_get.call_count, 1)
        self.assertEqual(mock_to_dataframe.call_count, 0)
        self.assertIsInstance(av_api_call(), dict)

    # save_df tests
    @patch('alphaVantageAPI.alphavantage.AlphaVantage.last')
    @patch('alphaVantageAPI.alphavantage.DataFrame.to_csv')
    def test_save_df_to_csv(self, mock_to_csv, mock_last):
        self.av.output = 'csv'
        mock_last.return_value = self.sector_parameters
        mock_to_csv.return_result = True

        self.av._save_df(self.sector_parameters['function'], self.df_sectors)

        self.assertEqual(mock_last.call_count, 1)
        self.assertEqual(mock_to_csv.call_count, 1)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage.last')
    @patch('alphaVantageAPI.alphavantage.DataFrame.to_json')
    def test_save_df_to_json(self, mock_to_json, mock_last):
        self.av.output = 'json'
        mock_last.return_value = self.sector_parameters
        mock_to_json.return_result = True

        self.av._save_df(self.sector_parameters['function'], self.df_sectors)

        self.assertEqual(mock_last.call_count, 1)
        self.assertEqual(mock_to_json.call_count, 1)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage.last')
    @patch('alphaVantageAPI.alphavantage.DataFrame.to_pickle')
    def test_save_df_to_pickle(self, mock_to_pickle, mock_last):
        self.av.output = 'pkl'
        mock_last.return_value = self.sector_parameters
        mock_to_pickle.return_result = True

        self.av._save_df(self.sector_parameters['function'], self.df_sectors)

        self.assertEqual(mock_last.call_count, 1)
        self.assertEqual(mock_to_pickle.call_count, 1)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage.last')
    @patch('alphaVantageAPI.alphavantage.DataFrame.to_html')
    def test_save_df_to_html(self, mock_to_html, mock_last):
        self.av.output = 'html'
        mock_last.return_value = self.sector_parameters
        mock_to_html.return_result = True

        self.av._save_df(self.sector_parameters['function'], self.df_sectors)

        self.assertEqual(mock_last.call_count, 1)
        self.assertEqual(mock_to_html.call_count, 1)

    @patch('alphaVantageAPI.alphavantage.AlphaVantage.last')
    @patch('alphaVantageAPI.alphavantage.Path.write_text')
    def test_save_df_to_txt(self, mock_write_text, mock_last):
        self.av.output = 'txt'
        mock_last.return_value = self.sector_parameters
        mock_write_text.return_result = True

        self.av._save_df(self.sector_parameters['function'], self.df_sectors)

        self.assertEqual(mock_last.call_count, 1)
        self.assertEqual(mock_write_text.call_count, 1)
import pandas_ta as ta
from alphaVantageAPI.alphavantage import AlphaVantage  ##pip install alphaVantage-api##

ticker = 'CW'
AV = AlphaVantage(api_key='PUT YOUR API KEY HERE',
                  premium=False,
                  datatype='json',
                  export=False,
                  export_path='C:/Users/Andy/Downloads',
                  output='csv',
                  output_size='full',
                  clean=True,
                  proxy={})

df = AV.data(symbol=ticker, function='DA')
predper = 60  #number of days to predict ahead
print(f"Shape: {df.shape}")
df.set_index(['date'], inplace=True)
df.head()

df.fillna(0.0, inplace=True)
df.to_csv(r'C:/Users/Andy/Downloads/pricedataCW.csv',
          index='date',
          header=True)
df = pd.read_csv('C:/Users/Andy/Downloads/pricedataCW.csv',
                 usecols=['date', 'close'])
df.head()
df.tail()
df.columns = ['ds', 'y']
Beispiel #8
0
import os.path
import sys
from skimage import draw

# Initialize the AlphaVantage Class with default values
AV = AlphaVantage(api_key="S45HPVH3ZGG9U18Z",
                  premium=False,
                  output_size='compact',
                  datatype='json',
                  export=False,
                  export_path='~/av_data',
                  output='csv',
                  clean=False,
                  proxy={})

df_AAPL = AV.data(symbol='AAPL', function='D')  # Daily

#df_AAPL = AV.intraday(symbol='AAPL', interval='15min') # Intraday as str

df_AAPL.drop("1. open", axis=1, inplace=True)
df_AAPL.drop("2. high", axis=1, inplace=True)
df_AAPL.drop("3. low", axis=1, inplace=True)
df_AAPL.drop("5. volume", axis=1, inplace=True)

df_AAPL["Date"] = df_AAPL["date"]
df_AAPL["Close"] = df_AAPL["4. close"]

df_AAPL.drop("date", axis=1, inplace=True)
df_AAPL.drop("4. close", axis=1, inplace=True)

if 1 == 1: