Skip to content

Commit

Permalink
Merge pull request #63 from xrgarcia/61-add-classes-for-time-series
Browse files Browse the repository at this point in the history
61 add classes for time series
  • Loading branch information
xrgarcia authored Jun 27, 2023
2 parents e09fcd5 + b95422a commit 3940cc2
Show file tree
Hide file tree
Showing 8 changed files with 304 additions and 191 deletions.
2 changes: 1 addition & 1 deletion alphavantage_api_client/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from alphavantage_api_client.client import AlphavantageClient
from alphavantage_api_client.models import GlobalQuote, Quote, AccountingReport, CompanyOverview, RealGDP, \
CsvNotSupported
CsvNotSupported, TickerSearch, MarketStatus
from alphavantage_api_client.ticker import Ticker
130 changes: 128 additions & 2 deletions alphavantage_api_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from .response_validation_rules import ValidationRuleChecks
import json
from alphavantage_api_client.models import GlobalQuote, Quote, AccountingReport, CompanyOverview, RealGDP, \
CsvNotSupported
CsvNotSupported, TickerSearch, MarketStatus
import copy
import logging
import hashlib
Expand Down Expand Up @@ -188,8 +188,100 @@ def get_daily_quote(self, event: dict) -> Quote:

return Quote.parse_obj(json_response)

def get_daily_adjusted_quote(self, event: dict) -> Quote:
"""
This API returns raw (as-traded) daily open/high/low/close/volume values,
daily adjusted close values, and historical split/dividend events of the global
equity specified, covering 20+ years of historical data.
Args:
event: dict, required
Returns: Quote
"""
# default params
defaults = {"datatype": "json", "function": "TIME_SERIES_DAILY_ADJUSTED",
"outputsize": "compact"}
json_request = self.__create_api_request_from__(defaults, event)
json_response = self.get_data_from_alpha_vantage(json_request, self.__retry__)

return Quote.parse_obj(json_response)

def get_weekly_quote(self, event: dict) -> Quote:
"""
This API returns weekly time series (last trading day of each week, weekly open,
weekly high, weekly low, weekly close, weekly volume) of the global equity
specified, covering 20+ years of historical data.
Args:
event: dict, required
Returns: Quote
"""
# default params
defaults = {"datatype": "json", "function": "TIME_SERIES_WEEKLY",
"outputsize": "compact"}
json_request = self.__create_api_request_from__(defaults, event)
json_response = self.get_data_from_alpha_vantage(json_request, self.__retry__)

return Quote.parse_obj(json_response)

def get_weekly_adjusted_quote(self, event: dict) -> Quote:
"""
This API returns weekly adjusted time series (last trading day of each week, weekly open,
weekly high, weekly low, weekly close, weekly adjusted close, weekly volume, weekly dividend)
of the global equity specified, covering 20+ years of historical data.
Args:
event: dict, required
Returns: Quote
"""
# default params
defaults = {"datatype": "json", "function": "TIME_SERIES_WEEKLY_ADJUSTED"}
json_request = self.__create_api_request_from__(defaults, event)
json_response = self.get_data_from_alpha_vantage(json_request, self.__retry__)

return Quote.parse_obj(json_response)

def get_monthly_quote(self, event: dict) -> Quote:
"""
This API returns monthly time series (last trading day of each month, monthly open,
monthly high, monthly low, monthly close, monthly volume) of the global equity specified,
covering 20+ years of historical data.
Args:
event: dict, required
Returns: Quote
"""
# default params
defaults = {"datatype": "json", "function": "TIME_SERIES_MONTHLY"}
json_request = self.__create_api_request_from__(defaults, event)
json_response = self.get_data_from_alpha_vantage(json_request, self.__retry__)

return Quote.parse_obj(json_response)

def get_monthly_adjusted_quote(self, event: dict) -> Quote:
"""
This API returns monthly time series (last trading day of each month, monthly open,
monthly high, monthly low, monthly close, monthly volume) of the global equity specified,
covering 20+ years of historical data.
Args:
event: dict, required
Returns: Quote
"""
# default params
defaults = {"datatype": "json", "function": "TIME_SERIES_MONTHLY_ADJUSTED"}
json_request = self.__create_api_request_from__(defaults, event)
json_response = self.get_data_from_alpha_vantage(json_request, self.__retry__)

return Quote.parse_obj(json_response)

def get_intraday_quote(self, event: dict) -> Quote:
""" Intraday time series data covering extened trading hours.
""" Intraday time series data covering extended trading hours.
This API returns intraday time series of the equity specified, covering extended trading hours where applicable
(e.g., 4:00am to 8:00pm Eastern Time for the US market). The intraday data is derived from the Securities
Expand Down Expand Up @@ -541,3 +633,37 @@ def clear_cache(self):
self.__cache__.clear()

return self

def search_ticker(self, event) -> TickerSearch:
"""
We've got you covered! The Search Endpoint returns the best-matching symbols and market information based
on keywords of your choice. The search results also contain match scores that provide you with the full
flexibility to develop your own search and filtering logic.
Args:
event: dict
Returns: TickerSearch
"""
defaults = {
"function": "SYMBOL_SEARCH",
"datatype": "json"
}
json_request = self.__create_api_request_from__(defaults, event)
json_response = self.get_data_from_alpha_vantage(json_request, self.__retry__)

return TickerSearch.parse_obj(json_response)

def get_market_status(self) -> MarketStatus:
"""
This endpoint returns the current market status (open vs. closed) of major trading venues for equities,
forex, and cryptocurrencies around the world.
Returns:
"""
json_request = {
"function": "MARKET_STATUS"
}
json_response = self.get_data_from_alpha_vantage(json_request, self.__retry__)

return MarketStatus.parse_obj(json_response)
16 changes: 14 additions & 2 deletions alphavantage_api_client/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ class BaseQuote(BaseResponse):
symbol: str


class TickerSearch(BaseResponse):
bestMatches: list[dict]

class MarketStatus(BaseResponse):
endpoint: str
markets: list[dict]

class Quote(BaseQuote):
"""
data is this clients abstraction of the response from alpha vantage. Time Series, Technical Indicator
Expand All @@ -33,7 +40,12 @@ class Quote(BaseQuote):
@pydantic.root_validator(pre=True)
def normalize_fields(cls, values):
return {
"data" if k.startswith("Technical Analysis: ") or k.startswith("Time Series (")
"data" if k.startswith("Weekly Adjusted Time Series")
or k.startswith("Monthly Adjusted Time Series")
or k.startswith("Monthly Time Series")
or k.startswith("Weekly Time Series")
or k.startswith("Technical Analysis: ")
or k.startswith("Time Series (")
or k.startswith("Time Series Crypto (") else k: v for k, v in values.items()
}

Expand All @@ -49,7 +61,7 @@ def get_most_recent_value(self) -> Optional[dict]:
def get_oldest_value(self) -> Optional[dict]:
if len(self.data) > 0:
quote_dates = list(self.data.keys())
last_quote_date = quote_dates[len(quote_dates)-1]
last_quote_date = quote_dates[len(quote_dates) - 1]
quote = self.data[last_quote_date]
quote["query_date"] = last_quote_date

Expand Down
17 changes: 14 additions & 3 deletions examples/getting_started.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from alphavantage_api_client import AlphavantageClient, GlobalQuote, Quote, AccountingReport, CompanyOverview, Ticker

import logging

def sample_global_quote():
client = AlphavantageClient()
Expand Down Expand Up @@ -104,8 +104,9 @@ def sample_cash_flow():


def sample_retry_when_limit_reached():
logging.basicConfig(level=logging.INFO)
client = AlphavantageClient().use_simple_cache().should_retry_once()
symbols = ["TSLA", "F", "C", "WFC", "ZIM", "PXD", "PXD", "POOL", "INTC", "INTU"] # more than 5 calls so should fail
symbols = ["TSLA", "F", "C", "WFC", "ZIM", "PXD", "PXD", "POOL", "INTC", "INTU", "AAPL"] # more than 5 calls so should fail
for symbol in symbols:
event = {
"symbol": symbol
Expand Down Expand Up @@ -150,6 +151,16 @@ def sample_ticker_usage():
combined_financial_statements = correlated_financial_statements[fiscal_date_ending]
print(f"{fiscal_date_ending} = {combined_financial_statements}")

def sample_direct_access():
client = AlphavantageClient()
event = {
"symbol" : "AAPL",
"function" : "GLOBAL_QUOTE"
} # EACH ATTRIBUTE IS EXACTLY SUPPORTED BY END POINTS

response = client.get_data_from_alpha_vantage(event)
print(response) # a dictionary with exact response from Alpha Vantage End point you requested


if __name__ == "__main__":
sample_ticker_usage()
sample_direct_access()
Loading

0 comments on commit 3940cc2

Please sign in to comment.