Roy Chang
Roy Chang

Reputation: 1

How to solve an inequality that contains standard deviation in python?

I have the past 19 days of stock price stored in the pd.dataframe and I am trying to find out the price P that is smaller than (mean - 2.5*standard deviation), where mean and standard deviation are calculated based on P and the past 19 days prices.

The inequality will be something like below:

P < mean - 2.5*standard deviation

I am assuming using solve in SymPy, but I got the error 'loop of ufunc does not support argument 0 of type Add which has no callable sqrt method' when calling np.std().

This is the demo code:

from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
solve(x-np.mean([1,2,3,x])-np.std([1,2,3,x]), x)

Error message:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
AttributeError: 'Add' object has no attribute 'sqrt'

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
Input In [71], in <cell line: 4>()
      2 from sympy import Symbol
      3 x = Symbol('x')
----> 4 solve(x-np.mean([1,2,3,x])-np.std([1,2,3,x]), x)

File ~/opt/anaconda3/lib/python3.9/site-packages/numpy/core/fromnumeric.py:3645, in std(a, axis, dtype, out, ddof, keepdims, where)
   3642     else:
   3643         return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
-> 3645 return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
   3646                      **kwargs)

File ~/opt/anaconda3/lib/python3.9/site-packages/numpy/core/_methods.py:214, in _std(a, axis, dtype, out, ddof, keepdims, where)
    212     ret = ret.dtype.type(um.sqrt(ret))
    213 else:
--> 214     ret = um.sqrt(ret)
    216 return ret

TypeError: loop of ufunc does not support argument 0 of type Add which has no callable sqrt method

Or maybe are there any other better methods?

Upvotes: 0

Views: 67

Answers (1)

smichr
smichr

Reputation: 19135

There are pure-python routines for mean and stddev here. With them (and using sqrt(x) instead of x**.5) you can generate your equation to solve:

>>> v=[1,2,3,x]; solve(x-mean(v)-stddev(v))
[2*sqrt(3)/3 + 2]
>>> _[0].n()
3.15470053837925

Upvotes: 0

Related Questions