Catch exceptions from yfinance - algorithmic-trading

I have the following code:
try:
yf.Ticker("AALB.NV").history(period = "3mo")
except:
pass
This gives the exception: - AALB.NV: No data found, symbol may be delisted
Is there any way I can catch this exception?

The .history() function doesn't raise an exception if the symbol is invalid, it just prints that statement to your screen. You could raise the exception yourself:
import yfinance as yf
try:
data = yf.Ticker("AALB.NV").history(period="3mo")
if 'Empty DataFrame' in str(data):
raise Exception('Empty DataFrame - might be caused by an invalid symbol')
except Exception as e:
print(e)

Related

How to create and fill structured array with numba?

Python 3.9.7, Numba 0.54.0
I wrote this simple code, that works well:
import numpy as np
import numba
from collections import namedtuple
Deal = namedtuple('Deal' , ['DateTime', 'Price', 'Quantity'])
dtype_deals = [('DateTime', 'datetime64[s]'), ('Price', 'float64'), ('Quantity', 'uint64')]
# #numba.njit
def my_func():
deals = []
deals.append(Deal(np.datetime64('2015-02-27T15:12:12'), 12.48, 10))
deals.append(Deal(np.datetime64('2015-03-17T15:08:36'), 1.15, 100))
deals.append(Deal(np.datetime64('2015-04-02T15:14:32'), 11.01, 20))
return np.array(deals, dtype=dtype_deals)
print(str(my_func()))
But when I remove the comment before #numba.njit, I get a mistake:
numba.core.errors.TypingError: Failed in nopython mode pipeline (step:
nopython frontend) No implementation of function
Function(datetime64[]) found for signature:
(Literalstr) There are 2 candidate implementations:
Of which 1 did not match due to: Overload in function 'make_callable_template..generic': File:
numba/core/typing/templates.py: Line 174. With argument(s):
'(unicode_type)': Rejected as the implementation raised a specific
error:
TypingError: Casting unicode_type to datetime64[] directly is unsupported. raised from
/home/ivan/.local/lib/python3.9/site-packages/numba/core/typing/builtins.py:818
Of which 1 did not match due to: Overload in function 'make_callable_template..generic': File:
numba/core/typing/templates.py: Line 174. With argument(s):
'(Literalstr)': Rejected as the
implementation raised a specific error:
TypingError: Casting Literalstr to datetime64[] directly is unsupported. raised from
/home/ivan/.local/lib/python3.9/site-packages/numba/core/typing/builtins.py:818
During: resolving callee type: class(datetime64[])
During: typing of call at /home/ivan/eclipse-workspace/MarketAnalysis/Experiment.py (11)
File "Experiment.py", line 11: def my_func():
deals = []
deals.append(Deal(np.datetime64('2015-02-27T15:12:12'), 12.48, 10))
^

How to print Graphene-Django / Graphene-Python Exceptions to the Console for Debugging?

When a GraphQL Error occurs, I cannot easily know where it occured. I have to spend unnecessary time trying to track it down. How do I get a Traceback printed in the console of my text editor?
I answered my own question by accessing the GraphQL error(s) with result.errors, iterating through the list, and using python's print_tb function to print the Traceback.
Does anyone have a different or better way of doing it?
Example usage of the print_graphql_errors function:
from django.conf.settings import DEBUG
result = schema.execute(
mutation_str, context_value=request, variable_values=variable_values
)
if result.errors is None:
return self.handle_success(result)
if DEBUG:
print_graphql_errors(result.errors)
return self.handle_failure(result)
The print_graphql_errors function:
from traceback import print_tb
from django.conf.settings import DEBUG
def print_graphql_errors(errors, raise_error=False):
if not DEBUG:
raise Exception(
'DevError: This function should not be called in production'
)
assert errors, 'DevError: The "errors" parameter cannot be None'
print_after = []
current_error = None
print('######################################################################')
print('Manually Generated Traceback (with the print_graphql_errors function):')
print(f'There are {len(errors)} errors:')
for i, error in enumerate(errors):
print(f'{i + 1}) ', error)
print('######################################################################')
for error in errors:
current_error = error
# FYI: This object has these attributes: (example attribute values)
# tb_frame <frame at 0x000002DDB844D548, file 'site-packages\\graphql\\execution\\executor.py', line 455, code resolve_or_error>
# tb_lasti 16
# tb_lineno 447
# tb_next <traceback object at 0x000002DDBAFBA388>
# print('error.locations:', error.locations)
# print('error.positions:', error.positions)
try:
print_tb(error.stack)
except AttributeError as e:
print(e.__traceback__)
print(f'Warning: An error occured while trying to print the traceback: {e}. It has the following attributes instead: {dir(error)}')
print_after.append(error)
if len(print_after):
print('###################################################################')
print(f'Number of errors without the "stack" attribute: {len(print_after)}')
print('###################################################################')
if raise_error:
for error in print_after:
raise error
raise current_error

(Direct) AWS Lambda invocation response status code is 200 despite unhandled function error

I have an AWS Lambda which is designed for direct invocation from multiple applications within my team's service landscape. I'm writing a wrapper class which will perform this invocation, and associated validation and error detection / handling in the Lambda's response.
By design, the Lambda terminates with an unhandled exception if runtime validation of the invocation parameters fails. But I didn't expect to find that in spite of an unhandled function error, the status_code of the invocation response is 200:
[1] pry(main)> lambda_client = Aws::Lambda::Client.new(region: 'us-east-1')
=> #<Aws::Lambda::Client>
[2] pry(main)> invocation_response = lambda_client.invoke(function_name: 'jwt-tokens-dev-AccessTokenCreator')
=> #<struct Aws::Lambda::Types::InvocationResponse
status_code=200,
function_error="Unhandled",
log_result=nil,
payload=#<StringIO:0x007f91c1749028>,
executed_version="$LATEST">
[3] pry(main)> invocation_response.payload.string
=> "{\"errorMessage\": \"Required parameters are missing: role, sub, sub_type\", \"errorType\": \"ParamMissingError\", \"stackTrace\": [[\"/var/task/handler.py\", 15, \"access_token_creator\", \"return access_token_creator_handler(event, context)\"], [\"/var/task/access_token_creator.py\", 32, \"handler\", \"params = _validate_event_params(event)\"], [\"/var/task/access_token_creator.py\", 97, \"_validate_event_params\", \"raise ParamMissingError('Required parameters are missing: %s' % ', '.join(missing_params))\"]]}"
[4] pry(main)> ActiveSupport::JSON.decode(invocation_response.payload.string)
=> {"errorMessage"=>"Required parameters are missing: role, sub, sub_type",
"errorType"=>"ParamMissingError",
"stackTrace"=>
[["/var/task/handler.py", 15, "access_token_creator", "return access_token_creator_handler(event, context)"],
["/var/task/access_token_creator.py", 32, "handler", "params = _validate_event_params(event)"],
["/var/task/access_token_creator.py",
97,
"_validate_event_params",
"raise ParamMissingError('Required parameters are missing: %s' % ', '.join(missing_params))"]]}
Is it expected that the status code of the response of a direct Lambda invocation would be 200, despite an unhandled function error? I want to implement proper error response detection in my wrapper class, and searching for the key "errorType" in the top-level of the JSON response doesn't really seem so robust.
The solution -- too obvious, but not enough to distract from the "200" status_code -- is to check if function_error is nil.
The value is nil in the event of successful invocation:
[8] pry(main)> invocation_response = lambda_client.invoke(function_name: 'jwt-tokens-dev-AccessTokenCreator', payload: ActiveSupport::JSON::encode(sub:3285397, sub_type:'user', role:'admin'))
=> #<struct Aws::Lambda::Types::InvocationResponse
status_code=200,
function_error=nil,
log_result=nil,
payload=#<StringIO:0x007f91c2a2eeb8>,
executed_version="$LATEST">
Otherwise it has the value 'Unhandled' or 'Handled':
function_error ⇒ String
Indicates whether an error occurred while executing the Lambda function. If an error occurred this field will
have one of two values; Handled or Unhandled. Handled errors are
errors that are reported by the function while the Unhandled errors
are those detected and reported by AWS Lambda. Unhandled errors
include out of memory errors and function timeouts. For information
about how to report an Handled error, see Programming Model.
https://docs.aws.amazon.com/sdkforruby/api/Aws/Lambda/Types/InvocationResponse.html#function_error-instance_method

Wordcount Nonetype error pyspark-

I am trying to do some text analysis:
def cleaning_text(sentence):
sentence=sentence.lower()
sentence=re.sub('\'','',sentence.strip())
sentence=re.sub('^\d+\/\d+|\s\d+\/\d+|\d+\-\d+\-\d+|\d+\-\w+\-\d+\s\d+\:\d+|\d+\-\w+\-\d+|\d+\/\d+\/\d+\s\d+\:\d+',' ',sentence.strip())# dates removed
sentence=re.sub(r'(.)(\/)(.)',r'\1\3',sentence.strip())
sentence=re.sub("(.*?\//)|(.*?\\\\)|(.*?\\\)|(.*?\/)",' ',sentence.strip())
sentence=re.sub('^\d+','',sentence.strip())
sentence = re.sub('[%s]' % re.escape(string.punctuation),'',sentence.strip())
cleaned=' '.join([w for w in sentence.split() if not len(w)<2 and w not in ('no', 'sc','ln') ])
cleaned=cleaned.strip()
if(len(cleaned)<=1):
return "NA"
else:
return cleaned
org_val=udf(cleaning_text,StringType())
df_new =df.withColumn("cleaned_short_desc", org_val(df["symptom_short_description_"]))
df_new =df_new.withColumn("cleaned_long_desc", org_val(df_new["long_description"]))
longWordsDF = (df_new.select(explode(split('cleaned_long_desc',' ')).alias('word'))
longWordsDF.count()
I get the following error.
File "<stdin>", line 2, in cleaning_text
AttributeError: 'NoneType' object has no attribute 'lower'
I want to perform word counts but any kind of aggregation function is giving me an error.
I tried following things:
sentence=sentence.encode("ascii", "ignore")
Added this statement in the cleaning_text function
df.dropna()
Its still giving the same issue, I do not know how to resolve this issue.
It looks like you have null values in some columns. Add an if at the beginning of cleaning_text function and the error will disappear:
if sentence is None:
return "NA"

how to interpret the error codes of boost::mpi?

How to make sense of the boost::mpi error code? For instance, what does error code 834983239 mean?
...
mpi::communicator world;
mpi::request req = world.isend(1, 1, std::string("hello"));
while(!req.test()) {
boost::this_thread::sleep(boost::posix_time::seconds(1));
}
int errorCode = req.test()->error();
...
The error code is unlikely to be filled in if there was not an error (and the default behavior for Boost.MPI is to throw an exception on error, not return a code). You should not need to check error codes manually unless you have changed Boost.MPI's default error handling settings.

Resources