Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create SP500.csv #1

Merged
merged 5 commits into from
May 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,6 @@ ENV/

# mypy
.mypy_cache/

# VS Code settings
.vscode
56 changes: 56 additions & 0 deletions itertools-in-python3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Itertools in Python 3, By Example

> Supplemental materials for the [Itertools in Python 3, By Example](https://realpython.com/itertools-in-python3) article on [Real Python](https://realpython.com).

This folder contains content for two example from the article: [Analyzing the S&P500](https://realpython.com/python3-itertools/#analyzing-the-sp500) and [Building Relay Teams from Swimmer Data](https://realpython.com/python3-itertools/#building-relay-teams-from-swimmer-data).

## Downloading the Files

### With `git`

If you have `git` installed, the easiest way to access these files is to clone the repository to the directory of your choice:

```console
git clone https://github.com/realpython/materials.git
```

Then `cd` into the `itertools-in-python3` directory:

```console
cd itertools-in-python3
```

### Without `git`

Alternatively, you can download the entire repository as a `.zip` file from the repository's [homepage](https://github.com/realpython/materials) using the green "Clone or download" button in the top right hand corner.

![Download repo as zip](download-zip.gif)

## Running the Code Examples

To run the code examples, first make sure you have Python 3 installed on your machine. **The code examples WILL NOT work with Python 2.** If you need help installing Python 3, check out Real Python's [Python 3 Installation & Setup Guide](https://realpython.com/installing-python/).

To run the `sp500.py` file, type `python3 sp500.py` into your terminal. Here's how that looks, with output:

```console
$ python3 sp500.py
Max gain: 11.58% on 2008-10-13
Max loss: -20.47% on 1987-10-19
Longest growth streak: 14 days (1971-03-26 to 1971-04-15)
```

Similarly, for `swimmers.py`:

```console
$ python3 swimmers.py
Backstroke A: Sophia, Grace, Penelope, Addison
Backstroke B: Elizabeth, Audrey, Emily, Aria
Breaststroke A: Samantha, Avery, Layla, Zoe
Breaststroke B: Lillian, Aria, Ava, Alexa
Butterfly A: Audrey, Leah, Layla, Samantha
Butterfly B: Alexa, Zoey, Emma, Madison
Freestyle A: Aubrey, Emma, Olivia, Evelyn
Freestyle B: Elizabeth, Zoe, Addison, Madison
```

> **Note:** Depending on your installation, you may need to type `python3.6` or `python36` to run the examples. If you follow the [Python 3 Installation & Setup Guide](https://realpython.com/installing-python/), you should have no problem.
17,192 changes: 17,192 additions & 0 deletions itertools-in-python3/SP500.csv

Large diffs are not rendered by default.

Binary file added itertools-in-python3/download-zip.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
61 changes: 61 additions & 0 deletions itertools-in-python3/sp500.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
from collections import namedtuple
import csv
from datetime import datetime
import itertools as it
import functools as ft


class DataPoint(namedtuple('DataPoint', ['date', 'value'])):
__slots__ = ()

def __le__(self, other):
return self.value <= other.value

def __lt__(self, other):
return self.value < other.value

def __gt__(self, other):
return self.value > other.value


def consecutive_positives(sequence, zero=0):
def _consecutives():
for itr in it.repeat(iter(sequence)):
yield tuple(it.takewhile(lambda p: p > zero,
it.dropwhile(lambda p: p <= zero, itr)))
return it.takewhile(lambda t: len(t), _consecutives())


def read_prices(csvfile, _strptime=datetime.strptime):
with open(csvfile) as infile:
reader = csv.DictReader(infile)
for row in reader:
yield DataPoint(date=_strptime(row['Date'], '%Y-%m-%d').date(),
value=float(row['Adj Close']))


# Read prices and calculate daily percent change.
prices = tuple(read_prices('SP500.csv'))
gains = tuple(DataPoint(day.date, 100*(day.value/prev_day.value - 1.))
for day, prev_day in zip(prices[1:], prices))

# Find maximum daily gain/loss.
zdp = DataPoint(None, 0) # zero DataPoint
max_gain = ft.reduce(max, it.filterfalse(lambda p: p <= zdp, gains))
max_loss = ft.reduce(min, it.filterfalse(lambda p: p > zdp, gains), zdp)


# Find longest growth streak.
growth_streaks = consecutive_positives(gains, zero=DataPoint(None, 0))
longest_streak = ft.reduce(lambda x, y: x if len(x) > len(y) else y,
growth_streaks)

# Display results.
print('Max gain: {1:.2f}% on {0}'.format(*max_gain))
print('Max loss: {1:.2f}% on {0}'.format(*max_loss))

print('Longest growth streak: {num_days} days ({first} to {last})'.format(
num_days=len(longest_streak),
first=longest_streak[0].date,
last=longest_streak[-1].date
))
Loading