cvxstoc is a Python package (built on top of cvxpy) that makes it easy to code and solve stochastic optimization problems, i.e., convex optimization problems that include random variables.

Here is a quick example of the kinds of problems you can tackle with cvxstoc (see the gentle walkthrough for more examples).

Suppose we are interested in a stochastic variation on a portfolio optimization problem, i.e., we wish to allocate our wealth across \(n\) assets such that the returns on our investments are (on average) maximized, so long as we keep the probability of a (catastrophic) loss as low as possible; we model our investment choices as a vector \(x \in {\bf R}^n_+\) (we require that the components of \(x\) sum to one), the (uncertain) price change of each asset as a vector \(p \in {\bf R}^n \sim \textrm{Normal}(\mu, \Sigma)\) for simplicity, and our loss threshold and tolerance as \(\alpha\) and \(\beta\), respectively (typically, \(\alpha\) is negative and \(\beta\) is small, e.g., 0.05).

These considerations lead us to the following (convex) optimization problem:

(1)\[\begin{split}\begin{equation}
\begin{array}{ll}
\mbox{maximize} & \mathop{\bf E{}} p^T x \\
\mbox{subject to} & x \succeq 0, \quad {\mathbf 1}^T x = 1, \quad {\mathop{\bf Prob}} ( p^T x \leq \alpha ) \leq \beta
\end{array}
\end{equation}\end{split}\]

with variable \(x\).

We can directly express (1) using cvxstoc as follows:

```
from cvxstoc import NormalRandomVariable, expectation, prob
from cvxpy import Maximize, Problem
from cvxpy.expressions.variables import Variable
import numpy
# Create problem data.
n = 10
mu = numpy.zeros(n)
Sigma = 0.1*numpy.eye(n)
p = NormalRandomVariable(mu, Sigma)
alpha = -1
beta = 0.05
# Create and solve stochastic optimization problem.
x = Variable(n)
p = Problem(Maximize(expectation(x.T*p, num_samples=100)),
[x >= 0, x.T*numpy.ones(n) == 1,
prob(x.T*p <= alpha, num_samples=100) <= beta])
p.solve()
```

On Mac OS X:

- Follow the instructions for installing cvxpy.
- From the terminal, type:
`pip install cvxstoc`(note: doing this will install PyMC, which cvxstoc depends on). - Done!

- See the gentle walkthrough.
- The cvxstoc paper contains much more (mathematical) detail as well as examples.
- The cvxpy and/or cvxstoc email lists are great places to ask questions — please feel free to get in touch!
- Please feel free to grab the source code and contribute!