index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
47,056 | alka653/PrediosEjido | refs/heads/master | /PrediosEjido/apps/principal/admin.py | from django.contrib import admin
from .models import *
admin.site.register(Propieta)
admin.site.register(Predio) | {"/PrediosEjido/apps/principal/views.py": ["/PrediosEjido/apps/principal/models.py", "/PrediosEjido/apps/principal/forms.py"], "/PrediosEjido/apps/principal/admin.py": ["/PrediosEjido/apps/principal/models.py"], "/PrediosEjido/apps/principal/urls.py": ["/PrediosEjido/apps/principal/views.py"], "/PrediosEjido/apps/principal/forms.py": ["/PrediosEjido/apps/principal/models.py"]} |
47,057 | alka653/PrediosEjido | refs/heads/master | /PrediosEjido/apps/principal/migrations/0003_auto_20151222_1505.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('principal', '0002_auto_20151222_1504'),
]
operations = [
migrations.AlterField(
model_name='predio',
name='c_recaja',
field=models.IntegerField(blank=True),
),
migrations.AlterField(
model_name='predio',
name='f_recaja',
field=models.DateField(blank=True),
),
migrations.AlterField(
model_name='predio',
name='v_recaja',
field=models.DecimalField(max_digits=9, decimal_places=2, blank=True),
),
]
| {"/PrediosEjido/apps/principal/views.py": ["/PrediosEjido/apps/principal/models.py", "/PrediosEjido/apps/principal/forms.py"], "/PrediosEjido/apps/principal/admin.py": ["/PrediosEjido/apps/principal/models.py"], "/PrediosEjido/apps/principal/urls.py": ["/PrediosEjido/apps/principal/views.py"], "/PrediosEjido/apps/principal/forms.py": ["/PrediosEjido/apps/principal/models.py"]} |
47,058 | alka653/PrediosEjido | refs/heads/master | /PrediosEjido/apps/principal/urls.py | from django.conf.urls import patterns, url
from .views import *
urlpatterns = patterns('PrediosEjido.apps.principal.views',
url(r'^$', 'home', name = 'home'),
url(r'^Importar/$', 'upload_data_predio', name = 'upload_data_predio'),
url(r'^Predios/$', 'list_predio', name = 'list_predio'),
url(r'^Predios/Ver/(?P<predio_pk>\d+)/$', 'view_predio', name = 'view_predio'),
url(r'^Predios/Nuevo/(?:/(?P<predio_pk>\d+))?', 'predio', name = 'predio'),
url(r'^Predios/Propietario/(?P<predio_pk>\d+)/$', 'sold_predio', name = 'sold_predio'),
url(r'^Predios/Eliminar/(?P<predio_pk>\d+)/$', 'delete_predio', name = 'delete_predio'),
url(r'^Predios/Reportes/all-predio/(?:/(?P<option>\d+))?', PredioAllPDFView.as_view(), name = 'pdf_all_predio'),
url(r'^Propietarios/$', 'list_propieta', name = 'list_propieta'),
url(r'^Propietarios/Nuevo/(?:/(?P<propieta_pk>\d+))?', 'propietario', name = 'propietario'),
url(r'^Propietarios/Eliminar/(?P<propieta_pk>\d+)/$', 'delete_propieta', name = 'delete_propieta'),
url(r'^Logout/$', 'logout_user', name = 'logout_user'),
url(r'^Usuarios/$', 'list_user', name = 'list_user'),
url(r'^Usuarios/Nuevo/$', 'user', name = 'user'),
)
| {"/PrediosEjido/apps/principal/views.py": ["/PrediosEjido/apps/principal/models.py", "/PrediosEjido/apps/principal/forms.py"], "/PrediosEjido/apps/principal/admin.py": ["/PrediosEjido/apps/principal/models.py"], "/PrediosEjido/apps/principal/urls.py": ["/PrediosEjido/apps/principal/views.py"], "/PrediosEjido/apps/principal/forms.py": ["/PrediosEjido/apps/principal/models.py"]} |
47,059 | alka653/PrediosEjido | refs/heads/master | /PrediosEjido/apps/principal/forms.py | # -*- encoding: utf-8 -*-
from django.contrib.auth.models import User
from django.forms import *
from django import forms
from .models import *
class PredioForm(forms.ModelForm):
class Meta:
model = Predio
fields = '__all__'
exclude = ('c_recaja', 'f_recaja', 'v_recaja', 'id_propieta_fin')
widgets = {
'c_catastral': TextInput(attrs = {'class': 'form-control number-val', 'maxlength': '15', 'required': True}),
't_ord': TextInput(attrs = {'class': 'form-control number-val', 'maxlength': '3', 'required': True}),
't_tot': TextInput(attrs = {'class': 'form-control number-val', 'maxlength': '3', 'required': True}),
'propieta': TextInput(attrs = {'class': 'form-control', 'maxlength': '9', 'required': True}),
'e': TextInput(attrs = {'class': 'form-control', 'maxlength': '1'}),
'd': TextInput(attrs = {'class': 'form-control', 'maxlength': '1'}),
'id_propietario': TextInput(attrs = {'class': 'form-control', 'maxlength': '15', 'required': True}),
'dir_predio': TextInput(attrs = {'class': 'form-control', 'maxlength': '30', 'required': True}),
'hectarea': TextInput(attrs = {'class': 'form-control number-val'}),
'met2': TextInput(attrs = {'class': 'form-control number-val', 'required': True}),
'area_con': TextInput(attrs = {'class': 'form-control number-val'}),
'avaluo_catastral': TextInput(attrs = {'class': 'form-control number-val', 'maxlength': '9', 'required': True})
}
labels = {
'c_catastral': 'Código Catastral',
't_ord': 'ORD',
't_tot': 'TOT',
'propieta': 'Nombre del Propietario',
'e': 'E',
'd': 'D',
'id_propietario': 'Identificación del Propietario',
'dir_predio': 'Dirección del Predio',
'hectarea': 'Tamaño en Hectárea',
'met2': 'Tamaño en Metros',
'area_con': 'Tamaño de Área Construida',
'avaluo_catastral': 'Valor Avaluo Catastral'
}
class PropietarioVentaForm(forms.Form):
c_recaja = forms.CharField(label = 'Código Recibo de Caja', widget = forms.TextInput(attrs = {'required': True, 'class': 'form-control number-val'}))
f_recaja = forms.CharField(label = 'Fecha del Recibo de Caja', widget = forms.TextInput(attrs = {'required': True, 'class': 'form-control datepicker'}))
v_recaja = forms.CharField(label = 'Valor Recibo de Caja', widget = forms.TextInput(attrs = {'required': True, 'class': 'form-control number-val', 'maxlength': '9'}))
id_propieta_fin = forms.ModelChoiceField(label = 'Propietario', queryset = Propieta.objects.all(), widget = forms.Select(attrs = {'class': 'form-control', 'required': True}))
id_propieta = forms.CharField(label = 'Identificación del propietario', widget = forms.TextInput(attrs = {'class': 'form-control', 'maxlength': '15'}))
name = forms.CharField(label = 'Nombre Completo del propietario', widget = forms.TextInput(attrs = {'class': 'form-control', 'maxlength': '30'}))
class UploadForm(forms.Form):
file_input = forms.FileField()
def upload(self):
val = 0
text = self.cleaned_data.get('file_input')
for txt in text.readlines():
predio_array = []
val = txt.replace('\n', '').replace(',', '')
for v in val.split(" "):
predio_array.append(v)
predio = Predio(c_catastral = predio_array[0], t_ord = predio_array[1], t_tot = predio_array[2], propieta = predio_array[3].replace('-', ' '), e = predio_array[4], d = predio_array[5], id_propietario = predio_array[6], dir_predio = predio_array[7].replace('-', ' '), hectarea = int(predio_array[8]), met2 = int(predio_array[9]), area_con = int(predio_array[10]), avaluo_catastral = int(predio_array[11]))
predio.save()
return "Importación Exitoso"
class PropietaForm(forms.ModelForm):
class Meta:
model = Propieta
fields = '__all__'
widgets = {
'id_propieta': TextInput(attrs = {'class': 'form-control', 'maxlength': '15', 'required': True}),
'name': TextInput(attrs = {'class': 'form-control', 'maxlength': '30', 'required': True}),
}
labels = {
'id_propieta': 'Identificación del propietario',
'name': 'Nombre Completo del propietario',
}
class UserForm(ModelForm):
class Meta:
model = User
fields = '__all__'
widgets = {
'password': TextInput(attrs = {'class': 'form-control', 'type': 'password', 'required': True}),
'username': TextInput(attrs = {'class': 'form-control', 'required': True}),
'first_name': TextInput(attrs = {'class': 'form-control', 'required': True}),
}
labels = {
'password': 'Contraseña',
'username': 'Username',
'first_name': 'Nombre del Usuario',
}
exclude = ('last_login', 'groups', 'user_permissions', 'last_name', 'email', 'date_joined', 'is_staff', 'is_active', 'is_superuser') | {"/PrediosEjido/apps/principal/views.py": ["/PrediosEjido/apps/principal/models.py", "/PrediosEjido/apps/principal/forms.py"], "/PrediosEjido/apps/principal/admin.py": ["/PrediosEjido/apps/principal/models.py"], "/PrediosEjido/apps/principal/urls.py": ["/PrediosEjido/apps/principal/views.py"], "/PrediosEjido/apps/principal/forms.py": ["/PrediosEjido/apps/principal/models.py"]} |
47,060 | DarshanRedij1/SIVRAJ- | refs/heads/main | /Functions.py | import random
import time
from Utilities import *
from playsound import playsound
def music(no_of_notes, raag,patti=pandhari_1):
i = 0
notations = []
x= [0,0,0,0.1,0.2,0.3]
while True:
if i<no_of_notes:
notations.append(Raag[raag.lower()][random.randrange(len(Raag[raag.lower()]))])
i+=1
else:
break
for j in notations:
if j in patti:
playsound(patti[j])
time.sleep(x[random.randrange(len(x))])
return print(notations) | {"/Functions.py": ["/Utilities.py"], "/main.py": ["/Functions.py"]} |
47,061 | DarshanRedij1/SIVRAJ- | refs/heads/main | /Utilities.py | #"Sa", "Re", "Ga", "Ma", "Pa", "Dha", "Ni", "Sa'"
from urllib.request import urlopen
#import soundfile as sf
Raag={
"bhoop": [".Sa", ".Re", ".Ga", ".Pa", ".Dha", "Sa",
"Re", "Ga", "Pa", "Dha", "Sa'",
"Sa'", "Re'", "Ga'", "Pa'", "Dha'"],
"bheempalasi": [".Sa", ".Re", ".ga", ".Ma", ".Pa", ".Dha", ".ni", "Sa",
"Re", "ga", "Ma", "Pa", "Dha", "ni", "Sa'",
"Re'", "ga'", "Ma'", "Pa'", "Dha'", "ni'"],
"bageshree": [".Sa", ".Re", ".ga", ".Ma", ".Pa", ".Dha", ".ni", "Sa",
"Re", "ga", "Ma", "Pa", "Dha", "ni", "Sa'",
"Re'", "ga'", "Ma'", "Pa'", "Dha'", "ni'"],
"khamaj": [".Sa", ".Re", ".Ga", ".Ma", ".Pa", ".Dha", ".Ni", ".ni", "Sa",
"Re", "Ga", "Ma", "Pa", "Dha", "Ni", "ni", "Sa'",
"Re'", "Ga'", "Ma'", "Pa'", "Dha'", "Ni'", "ni'"],
"des": [".Sa", ".Re", ".Ga", ".Ma", ".Pa", ".Dha", ".Ni", ".ni", "Sa",
"Re", "Ga", "Ma", "Pa", "Dha", "Ni", "ni", "Sa'",
"Re'", "Ga'", "Ma'", "Pa'", "Dha'", "Ni'", "ni'"],
"kafi": [".Sa", ".Re", ".ga", ".Ma", ".Pa", ".Dha", ".ni", "Sa",
"Re", "ga", "Ma", "Pa", "Dha", "ni", "Sa'",
"Re'", "ga'", "Ma'", "Pa'", "Dha'", "ni'"],
"durga": [".Sa", ".Re", ".Ma", ".Pa", ".Dha", "Sa",
"Re", "Ma", "Pa", "Dha", "Sa'",
"Re'", "Ma'", "Pa'", "Dha'"],
"yaman": [".Sa", ".Re", ".Ga", ".ma", ".Pa", ".Dha", ".Ni", "Sa",
"Re", "Ga", "ma", "Pa", "Dha", "Ni", "Sa'",
"Re'", "Ga'", "ma'", "Pa'", "Dha'", "Ni'"]
}
pandhari_1 = {
".Sa":"c3.wav", ".Re":"d3.wav", ".Ga":"e3.wav", ".Ma":"f3.wav", ".Pa":"g3.wav", ".Dha":"a3.wav", ".Ni":"b3.wav",
".re":"c-3.wav", ".ga":"d-3.wav", ".ma":"f-3.wav", ".dha":"g-3.wav", ".ni":"a-3.wav",
"Sa":"c4.wav", "Re":"d4.wav", "Ga":"e4.wav", "Ma":"f4.wav", "Pa":"g4.wav", "Dha":"a4.wav", "Ni":"b4.wav",
"re":"c-4.wav", "ga":"d-4.wav", "ma":"f-4.wav", "dha":"g-4.wav", "ni":"a-4.wav",
"Sa'": "c5.wav", "Re'": "d5.wav", "Ga'": "e5.wav", "Ma'": "f5.wav", "Pa'": "g5.wav", "Dha'": "a5.wav", "Ni'": "b5.wav",
"re'": "c-5.wav", "ga'": "d-5.wav", "ma'": "f-5.wav", "dha'": "g-5.wav", "ni'": "a-5.wav"
}
kali_1 = {
".Sa":"c-3.wav", ".Re":"d-3.wav", ".Ga":"f3.wav", ".Ma":"f-3.wav", ".Pa":"g-3.wav", ".Dha":"a-3.wav", ".Ni":"c4.wav",
".re":"d3.wav", ".ga":"e3.wav", ".ma":"g3.wav", ".dha":"a3.wav", ".ni":"b3.wav",
"Sa":"c-4.wav", "Re":"d-4.wav", "Ga":"f4.wav", "Ma":"f-4.wav", "Pa":"g-4.wav", "Dha":"a-4.wav", "Ni":"c4.wav",
"re":"d4.wav", "ga":"e4.wav", "ma":"g4.wav", "dha":"a4.wav", "ni":"b4.wav",
"Sa'": "c-5.wav", "Re'": "d-5.wav", "Ga'": "f5.wav", "Ma'": "f-5.wav", "Pa'": "g-5.wav", "Dha'": "a-5.wav",
"re'": "d5.wav", "ga'": "e5.wav", "ma'": "g5.wav", "dha'": "a5.wav", "ni'": "b5.wav"
}
pandhari_2 = {
".Sa":"d3.wav", ".Re":"e3.wav", ".Ga":"f-3.wav", ".Ma":"g3.wav", ".Pa":"a3.wav", ".Dha":"b3.wav", ".Ni":"c-4.wav",
".re":"d-3.wav", ".ga":"f3.wav", ".ma":"g-3.wav", ".dha":"a-3.wav", ".ni":"c4.wav",
"Sa":"d4.wav", "Re":"e4.wav", "Ga":"f-4.wav", "Ma":"g4.wav", "Pa":"a4.wav", "Dha":"b4.wav", "Ni":"c-5.wav",
"re":"d-4.wav", "ga":"f4.wav", "ma":"g-4.wav", "dha":"a-4.wav", "ni":"c5.wav",
"Sa'": "d5.wav", "Re'": "e5.wav", "Ga'": "f-5.wav", "Ma'": "g5.wav", "Pa'": "a5.wav", "Dha'": "b5.wav",
"re'": "d-5.wav", "ga'": "f5.wav", "ma'": "g-5.wav", "dha'": "a-5.wav"
}
kali_2 = {
".Sa":"d-3.wav", ".Re":"f3.wav", ".Ga":"g3.wav", ".Ma":"g-3.wav", ".Pa":"a-3.wav", ".Dha":"c4.wav", ".Ni":"d4.wav",
".re":"e3.wav", ".ga":"f-3.wav", ".ma":"a3.wav", ".dha":"b3.wav", ".ni":"c-4.wav",
"Sa":"d-4.wav", "Re":"f4.wav", "Ga":"g4.wav", "Ma":"g-4.wav", "Pa":"a-4.wav", "Dha":"c5.wav", "Ni":"d5.wav",
"re":"e4.wav", "ga":"f-4.wav", "ma":"a4.wav", "dha":"b4.wav", "ni":"c-5.wav",
"Sa'": "d-5.wav", "Re'": "f5.wav", "Ga'": "g5.wav", "Ma'": "g-5.wav", "Pa'": "a-5.wav",
"re'": "e5.wav", "ga'": "f-5.wav", "ma'": "a5.wav", "dha'": "b5.wav"
} | {"/Functions.py": ["/Utilities.py"], "/main.py": ["/Functions.py"]} |
47,062 | DarshanRedij1/SIVRAJ- | refs/heads/main | /main.py |
from Functions import *
from SIVRAJ import *
#Notations = music(200, "Yaman")
if __name__ == "__main__":
wishMe()
while True:
# if 1:
query = takeCommand().lower()
if 'wikipedia' in query:
speak("Searching Wikipedia...")
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=2)
speak("According to Wikipedia")
print(results)
speak(results)
elif 'open youtube' in query:
speak("what do you want to search?")
print("F.R.I.D.A.Y.:What do you want to search?")
searchYoutube = takeCommand()
webbrowser.open('https://www.youtube.com/results?search_query=' + searchYoutube)
elif 'open google' in query:
speak("what do you want to search?")
print("F.R.I.D.A.Y.:What do you want to search?")
searchGoogle = takeCommand()
webbrowser.open('https://www.google.com/?#q=' + searchGoogle)
elif 'open stackoverflow' in query:
webbrowser.open("stackoverflow.com")
elif 'the time' in query:
strTime = datetime.datetime.now().strftime("%H:%M:%S")
speak(f"Sir, the time is {strTime}")
elif 'play music'in query:
speak("How many notes do you want to play?")
notes = int(input("No. of notes :"))
speak("Which raag do you want to play?")
rg = input("Raag :")
music(notes, rg)
elif 'exit' in query:
print("See you later!")
speak("See you later!")
break
| {"/Functions.py": ["/Utilities.py"], "/main.py": ["/Functions.py"]} |
47,063 | ambroisie/kata | refs/heads/master | /fizzbuzz/fizzbuzz.py | #! /usr/bin/env python
from typing import Callable, Dict
def fizzbuzzer(words: Dict[int, str]) -> Callable[[int], None]:
def _fun(max: int) -> None:
for i in range(1, max + 1):
out = []
for div, word in sorted(words.items()):
if i % div == 0:
out.append(word)
if len(out) > 0:
print("".join(out))
else:
print(i)
return _fun
def fizzbuzz(max: int = 100) -> None:
words = {
3: "fizz",
5: "buzz",
}
f = fizzbuzzer(words)
f(max)
if __name__ == "__main__":
fizzbuzz()
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,064 | ambroisie/kata | refs/heads/master | /rover/rover.py | import enum
from copy import deepcopy
from typing import List
from pydantic import BaseModel, root_validator, validator
class Vector(BaseModel):
x: int = 0
y: int = 0
@validator("x")
def _x_must_be_positive(x):
if x < 0:
raise ValueError("x must be positive")
return x
@validator("y")
def _y_must_be_positive(y):
if y < 0:
raise ValueError("y must be positive")
return y
class Direction(enum.Enum):
NORTH = "N"
SOUTH = "S"
EAST = "E"
WEST = "W"
class ObstacleError(RuntimeError):
pass
DIRECTIONS = [Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST]
class Rover(BaseModel):
pos: Vector = Vector(x=0, y=0)
planet_size: Vector = Vector(x=100, y=100)
dir: Direction = Direction.NORTH
@root_validator()
def _validate_pos(cls, values) -> None:
pos, planet_size = values.get("pos"), values.get("planet_size")
if pos.x > planet_size.x:
raise ValueError(
f"pos.x (= {pos.x}) should be under planet_size.x (= {planet_size.x})"
)
if pos.y > planet_size.y:
raise ValueError(
f"pos.y (= {pos.y}) should be under planet_size.y (= {planet_size.y})"
)
return values
def _translate(self, value) -> None:
if self.dir == Direction.NORTH:
self.pos.y += value
elif self.dir == Direction.SOUTH:
self.pos.y -= value
elif self.dir == Direction.EAST:
self.pos.x += value
elif self.dir == Direction.WEST:
self.pos.x -= value
if self.pos.x < 0:
self.pos.x += self.planet_size.x
if self.pos.y < 0:
self.pos.y += self.planet_size.y
self.pos.x %= self.planet_size.x
self.pos.y %= self.planet_size.y
def forward(self) -> None:
self._translate(1)
def backward(self) -> None:
self._translate(-1)
def _turn(self, value) -> None:
index: int = DIRECTIONS.index(self.dir)
self.dir = DIRECTIONS[(index + value) % len(DIRECTIONS)]
def turn_left(self) -> None:
self._turn(-1)
def turn_right(self) -> None:
self._turn(1)
class Commander(BaseModel):
rover: Rover = Rover()
obstacles: List[Vector] = []
@root_validator()
def _rover_should_not_start_on_obstacle(cls, values):
rover, obstacles = values.get("rover"), values.get("obstacles")
if rover.pos in obstacles:
raise ValueError(f"Rover should not start on obstacle ({rover.pos})")
return values
def parse_execute(self, commands: str) -> None:
for i, command in enumerate(commands):
save: Vector = deepcopy(self.rover.pos)
if command == "F":
self.rover.forward()
elif command == "B":
self.rover.backward()
elif command == "L":
self.rover.turn_left()
elif command == "R":
self.rover.turn_right()
else:
raise ValueError(f"Unknown command: '{command}' (index {i})")
if self.rover.pos in self.obstacles:
self.rover.pos = save
raise ObstacleError
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,065 | ambroisie/kata | refs/heads/master | /calculator/calculator/parse/parsed_string.py | from typing import List, Union
from calculator.ast import BinOp, Constant, Node, UnaryOp
from pydantic.dataclasses import dataclass
def begins_with_digit(d: str) -> bool:
return "0" <= d[0] <= "9"
@dataclass
class ParsedString:
input: str
def _is_done(self) -> bool:
return len(self.input) == 0
def _get_token(self) -> Union[int, str]:
ans = ""
self.input = self.input.strip() # Remove whitespace
while begins_with_digit(self.input):
ans += self.input[0]
self.input = self.input[1:]
if len(self.input) == 0 or not begins_with_digit(self.input):
break
if len(ans) != 0: # Was a number, return the converted int
return int(ans)
# Was not a number, return the (presumed) symbol
ans = self.input[0]
self.input = self.input[1:]
return ans
def tokenize(self) -> List[Union[int, str]]:
ans: List[str] = []
while not self._is_done():
ans.append(self._get_token())
return ans
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,066 | ambroisie/kata | refs/heads/master | /calculator/calculator/ast/node.py | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from calculator.ast.visit import Visitor
class Node(ABC):
"""
Abstract Node class for calculator AST.
"""
@abstractmethod
def accept(self, v: Visitor) -> None:
pass
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,067 | ambroisie/kata | refs/heads/master | /calculator/calculator/__init__.py | import calculator.core # isort:skip
import calculator.ast
import calculator.eval
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,068 | ambroisie/kata | refs/heads/master | /calculator/calculator/print/__init__.py | from .printer import Printer
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,069 | ambroisie/kata | refs/heads/master | /calculator/calculator/eval/test_evaluator.py | import pytest
from calculator.ast import BinOp, Constant, UnaryOp
from calculator.core import operations
from .evaluator import Evaluator
@pytest.fixture
def vis():
return Evaluator()
def test_evaluate_constant(vis):
c = Constant(42)
assert vis.visit_and_get_value(c) == 42
def test_evaluate_unaryop_identity(vis):
op = UnaryOp(operations.identity, Constant(42))
assert vis.visit_and_get_value(op) == 42
def test_evaluate_unaryop_negate(vis):
op = UnaryOp(operations.negate, Constant(-42))
assert vis.visit_and_get_value(op) == 42
def test_evaluate_binop_plus(vis):
op = BinOp(operations.plus, Constant(12), Constant(27))
assert vis.visit_and_get_value(op) == 39
def test_evaluate_binop_minus(vis):
op = BinOp(operations.minus, Constant(42), Constant(51))
assert vis.visit_and_get_value(op) == -9
def test_evaluate_binop_times(vis):
op = BinOp(operations.times, Constant(6), Constant(9))
assert vis.visit_and_get_value(op) == 54
def test_evaluate_binop_int_div(vis):
op = BinOp(operations.int_div, Constant(5), Constant(2))
assert vis.visit_and_get_value(op) == 2
def test_evaluate_binop_pow(vis):
op = BinOp(operations.pow, Constant(3), Constant(4))
assert vis.visit_and_get_value(op) == 81
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,070 | ambroisie/kata | refs/heads/master | /calculator/calculator/parse/test_postfix.py | from calculator.ast import BinOp, Constant, UnaryOp
from calculator.core import operations
from .postfix import parse_postfix
def test_parse_constant():
assert parse_postfix("42") == Constant(42)
def test_parse_negated_constant():
assert parse_postfix("42 @") == UnaryOp(operations.negate, Constant(42))
def test_parse_doubly_negated_constant():
assert parse_postfix("42@@") == UnaryOp(
operations.negate, UnaryOp(operations.negate, Constant(42))
)
def test_parse_binary_operation():
assert parse_postfix("12 27 +") == BinOp(
operations.plus, Constant(12), Constant(27)
)
def test_parse_complete_expression_tree():
assert parse_postfix("12 27 + 42 51 - *") == BinOp(
operations.times,
BinOp(operations.plus, Constant(12), Constant(27)),
BinOp(operations.minus, Constant(42), Constant(51)),
)
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,071 | ambroisie/kata | refs/heads/master | /calculator/calculator/print/printer.py | from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING
from calculator.ast.visit import Visitor
from calculator.core.operations import (
identity,
int_div,
minus,
negate,
plus,
pow,
times,
)
from pydantic.dataclasses import dataclass
if TYPE_CHECKING:
from calculator.ast import BinOp, Constant, Node, UnaryOp
OP_TO_STR = {
plus: "+",
minus: "-",
times: "*",
int_div: "/",
pow: "^",
identity: "+",
negate: "-",
}
@dataclass
class Printer(Visitor):
"""
Print a Tree
"""
indent: int = dataclasses.field(default=0, init=False)
def print(self, n: Node) -> None:
n.accept(self)
def visit_constant(self, c: Constant) -> None:
print(" " * self.indent + str(c.value))
def visit_binop(self, b: BinOp) -> None:
print(" " * self.indent + OP_TO_STR[b.op])
self.indent += 2
self.print(b.lhs)
self.print(b.rhs)
self.indent -= 2
def visit_unaryop(self, b: UnaryOp) -> None:
print(" " * self.indent + OP_TO_STR[b.op])
self.indent += 2
self.print(b.rhs)
self.indent -= 2
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,072 | ambroisie/kata | refs/heads/master | /calculator/calculator/ast/unaryop.py | from __future__ import annotations
from typing import TYPE_CHECKING, Callable
from pydantic.dataclasses import dataclass
from .node import Node
if TYPE_CHECKING:
from calculator.ast.visit import Visitor
class Config:
arbitrary_types_allowed = True
@dataclass(config=Config)
class UnaryOp(Node):
"""
Node to represent a unary operation
"""
op: Callable[[int], int]
rhs: Node
def accept(self, v: Visitor) -> None:
v.visit_unaryop(self)
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,073 | ambroisie/kata | refs/heads/master | /calculator/calculator/parse/postfix.py | from __future__ import annotations
from typing import TYPE_CHECKING, List, Union, cast
from calculator.ast import BinOp, Constant, UnaryOp
from calculator.core import operations
from .parsed_string import ParsedString
if TYPE_CHECKING:
from calculator.ast import Node
def stack_to_tree(s: List[Union[int, str]]) -> Node:
top = s.pop()
if type(top) is int:
return Constant(top)
top = cast(str, top)
if top == "@":
rhs = stack_to_tree(s)
return UnaryOp(operations.negate, rhs)
rhs = stack_to_tree(s)
lhs = stack_to_tree(s)
return BinOp(operations.STR_TO_BIN[top], lhs, rhs)
def parse_postfix(input: str) -> Node:
"""
Parses the given string in postfix notation.
Negation is represented by the '@' sign.
"""
parsed = ParsedString(input).tokenize()
ans = stack_to_tree(parsed)
return ans
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,074 | ambroisie/kata | refs/heads/master | /calculator/calculator/print/test_printer.py | import pytest
from calculator.parse import parse_infix
from .printer import Printer
def print_test_helper(input: str, expected: str, capsys):
Printer().print(parse_infix(input))
out, __ = capsys.readouterr()
assert out == expected
def test_printer_constant(capsys):
print_test_helper("42", "42\n", capsys)
def test_printer_negated_constant(capsys):
print_test_helper("-42", "-\n 42\n", capsys)
def test_printer_binaryop(capsys):
print_test_helper("12 + 27", "+\n 12\n 27\n", capsys)
def test_print_complex_expression(capsys):
print_test_helper(
"12 + 27 * 42 ^51", "+\n 12\n *\n 27\n ^\n 42\n 51\n", capsys
)
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,075 | ambroisie/kata | refs/heads/master | /calculator/calculator/ast/visit/visitor.py | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from calculator.ast import BinOp, Constant, Node, UnaryOp
class Visitor(ABC):
"""
Abstract Visitor class for the AST class hierarchy.
"""
def visit(self, n: Node) -> None:
n.accept(self)
@abstractmethod
def visit_constant(self, c: Constant) -> None:
pass
@abstractmethod
def visit_binop(self, b: BinOp) -> None:
pass
@abstractmethod
def visit_unaryop(self, b: UnaryOp) -> None:
pass
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,076 | ambroisie/kata | refs/heads/master | /calculator/calculator/ast/__init__.py | from .node import Node # isort:skip
from .binop import BinOp
from .constant import Constant
from .unaryop import UnaryOp
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,077 | ambroisie/kata | refs/heads/master | /rover/test_rover.py | import pytest
from pydantic import ValidationError
from rover import Commander, Direction, ObstacleError, Rover, Vector
def test_rover_constructor():
rov = Rover(pos={"x": 0, "y": 0}, planet_size={"x": 100, "y": 100})
assert rov.pos == Vector(x=0, y=0) and rov.planet_size == Vector(x=100, y=100)
def test_rover_default_values():
rov = Rover()
assert rov.pos == Vector(x=0, y=0) and rov.planet_size == Vector(x=100, y=100)
def test_rover_has_direction():
rov = Rover(dir=Direction.NORTH)
assert rov.dir == Direction.NORTH
def test_rover_default_direction_is_north():
rov = Rover()
assert rov.dir == Direction.NORTH
def test_rover_can_go_forward_once_going_north():
rov = Rover(
pos=Vector(x=0, y=0), planet_size=Vector(x=10, y=10), dir=Direction.NORTH
)
rov.forward()
assert rov.pos == Vector(x=0, y=1)
def test_rover_can_go_forward_twice_going_north():
rov = Rover(
pos=Vector(x=0, y=0), planet_size=Vector(x=10, y=10), dir=Direction.NORTH
)
rov.forward()
rov.forward()
assert rov.pos == Vector(x=0, y=2)
def test_rover_can_go_forward_going_east():
rov = Rover(
pos=Vector(x=0, y=0), planet_size=Vector(x=10, y=10), dir=Direction.EAST
)
rov.forward()
assert rov.pos == Vector(x=1, y=0)
def test_rover_can_go_forward_going_south():
rov = Rover(
pos=Vector(x=0, y=1), planet_size=Vector(x=10, y=10), dir=Direction.SOUTH
)
rov.forward()
assert rov.pos == Vector(x=0, y=0)
def test_rover_can_go_forward_going_west():
rov = Rover(
pos=Vector(x=1, y=0), planet_size=Vector(x=10, y=10), dir=Direction.WEST
)
rov.forward()
assert rov.pos == Vector(x=0, y=0)
def test_rover_can_wrap_under_north_south():
rov = Rover(
pos=Vector(x=0, y=0), planet_size=Vector(x=10, y=10), dir=Direction.SOUTH
)
rov.forward()
assert rov.pos == Vector(x=0, y=9)
def test_rover_can_wrap_under_east_west():
rov = Rover(
pos=Vector(x=0, y=0), planet_size=Vector(x=10, y=10), dir=Direction.WEST
)
rov.forward()
assert rov.pos == Vector(x=9, y=0)
def test_rover_can_wrap_over_north_south():
rov = Rover(
pos=Vector(x=0, y=9), planet_size=Vector(x=10, y=10), dir=Direction.NORTH
)
rov.forward()
assert rov.pos == Vector(x=0, y=0)
def test_rover_can_wrap_over_east_west():
rov = Rover(
pos=Vector(x=9, y=0), planet_size=Vector(x=10, y=10), dir=Direction.EAST
)
rov.forward()
assert rov.pos == Vector(x=0, y=0)
def test_rover_can_go_backward_north():
rov = Rover(
pos=Vector(x=0, y=1), planet_size=Vector(x=10, y=10), dir=Direction.NORTH
)
rov.backward()
assert rov.pos == Vector(x=0, y=0)
def test_rover_can_go_backward_south():
rov = Rover(
pos=Vector(x=0, y=0), planet_size=Vector(x=10, y=10), dir=Direction.SOUTH
)
rov.backward()
assert rov.pos == Vector(x=0, y=1)
def test_rover_can_go_backward_west():
rov = Rover(
pos=Vector(x=0, y=0), planet_size=Vector(x=10, y=10), dir=Direction.WEST
)
rov.backward()
assert rov.pos == Vector(x=1, y=0)
def test_rover_can_go_backward_east():
rov = Rover(
pos=Vector(x=1, y=0), planet_size=Vector(x=10, y=10), dir=Direction.EAST
)
rov.backward()
assert rov.pos == Vector(x=0, y=0)
def test_rover_can_go_backward_wrapping_under_north_south():
rov = Rover(
pos=Vector(x=0, y=0), planet_size=Vector(x=10, y=10), dir=Direction.NORTH
)
rov.backward()
assert rov.pos == Vector(x=0, y=9)
def test_rover_can_go_backward_wrapping_over_north_south():
rov = Rover(
pos=Vector(x=0, y=9), planet_size=Vector(x=10, y=10), dir=Direction.SOUTH
)
rov.backward()
assert rov.pos == Vector(x=0, y=0)
def test_rover_can_go_backward_wrapping_under_east_west():
rov = Rover(
pos=Vector(x=0, y=0), planet_size=Vector(x=10, y=10), dir=Direction.EAST
)
rov.backward()
assert rov.pos == Vector(x=9, y=0)
def test_rover_can_go_backward_wrapping_over_east_west():
rov = Rover(
pos=Vector(x=9, y=0), planet_size=Vector(x=10, y=10), dir=Direction.WEST
)
rov.backward()
assert rov.pos == Vector(x=0, y=0)
def test_rover_can_turn_left():
rov = Rover(dir=Direction.NORTH)
rov.turn_left()
assert rov.dir == Direction.WEST
def test_rover_can_turn_right():
rov = Rover(dir=Direction.NORTH)
rov.turn_right()
assert rov.dir == Direction.EAST
def test_commander_constructor():
com = Commander(
rover=Rover(
pos=Vector(x=12, y=27), planet_size=Vector(x=100, y=100), dir=Direction.WEST
)
)
assert (
com.rover.pos == Vector(x=12, y=27)
and com.rover.planet_size == Vector(x=100, y=100)
and com.rover.dir == Direction.WEST
)
def test_commander_default_values():
com = Commander()
assert com.rover == Rover()
def test_commander_can_parse_left():
com = Commander()
com.parse_execute("L")
assert com.rover == Rover(dir=Direction.WEST)
def test_commander_can_parse_right():
com = Commander()
com.parse_execute("R")
assert com.rover == Rover(dir=Direction.EAST)
def test_commmander_can_parse_forward():
com = Commander()
com.parse_execute("F")
assert com.rover == Rover(pos=Vector(x=0, y=1))
def test_commmander_can_parse_backward():
com = Commander(rover=Rover(pos=Vector(x=0, y=1)))
com.parse_execute("B")
assert com.rover == Rover()
def test_commander_complex_command():
com = Commander()
com.parse_execute("FRFRFLB")
assert com.rover == Rover(dir=Direction.EAST)
def test_commander_unknown_command():
com = Commander()
with pytest.raises(ValueError):
com.parse_execute("A")
def test_commander_command_with_obstacles():
com = Commander(obstacles=[Vector(x=1, y=0), Vector(x=1, y=2)])
with pytest.raises(ObstacleError):
com.parse_execute("FFRF")
assert com.rover == Rover(pos=Vector(x=0, y=2), dir=Direction.EAST)
def test_rover_negative_x_construction():
with pytest.raises(ValidationError):
_ = Rover(pos=Vector(x=-1, y=0))
def test_rover_negative_y_construction():
with pytest.raises(ValidationError):
_ = Rover(pos=Vector(x=0, y=-1))
def test_rover_oversize_x_construction():
with pytest.raises(ValidationError):
_ = Rover(pos=Vector(x=11, y=0), planet_size=Vector(x=10, y=10))
def test_rover_oversize_y_construction():
with pytest.raises(ValidationError):
_ = Rover(pos=Vector(x=0, y=11), planet_size=Vector(x=10, y=10))
def test_commander_have_rover_start_on_obstacle():
with pytest.raises(ValidationError):
_ = Commander(obstacles=[Vector()])
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,078 | ambroisie/kata | refs/heads/master | /calculator/calculator/parse/__init__.py | from .infix import parse_infix
from .postfix import parse_postfix
from .prefix import parse_prefix
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,079 | ambroisie/kata | refs/heads/master | /calculator/calculator/ast/constant.py | from __future__ import annotations
from typing import TYPE_CHECKING
from pydantic.dataclasses import dataclass
from .node import Node
if TYPE_CHECKING:
from calculator.ast.visit import Visitor
class Config:
arbitrary_types_allowed = True
@dataclass(config=Config)
class Constant(Node):
"""
Node to represent a constant value.
"""
value: int
def accept(self, v: Visitor) -> None:
v.visit_constant(self)
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,080 | ambroisie/kata | refs/heads/master | /calculator/run.py | #! /usr/bin/env python
import click
from calculator.eval import Evaluator
from calculator.parse import parse_infix, parse_postfix, parse_prefix
from calculator.print import Printer
STR_TO_PARSER = {
"infix": parse_infix,
"prefix": parse_prefix,
"postfix": parse_postfix,
}
@click.group(invoke_without_command=True, chain=True)
@click.option(
"--expr-type",
default="infix",
type=click.Choice(["infix", "prefix", "postfix"], case_sensitive=False),
)
@click.pass_context
def cli(ctx, expr_type):
ctx.ensure_object(dict)
ctx.obj["input"] = STR_TO_PARSER[expr_type](
input(f"Input your {expr_type} expression: ")
)
if ctx.invoked_subcommand is None:
ctx.invoke(eval_tree)
@cli.command(name="print")
@click.pass_context
def print_tree(ctx):
"""
Print the parsed AST.
"""
Printer().print(ctx.obj["input"])
@cli.command(name="eval")
@click.pass_context
def eval_tree(ctx):
"""
Evaluate the parsed expression.
"""
print(Evaluator().visit_and_get_value(ctx.obj["input"]))
if __name__ == "__main__":
cli(obj={})
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,081 | ambroisie/kata | refs/heads/master | /calculator/calculator/parse/test_infix.py | from calculator.ast import BinOp, Constant, UnaryOp
from calculator.core import operations
from .infix import parse_infix
def test_parse_constant():
assert parse_infix("42") == Constant(42)
def test_parse_negated_constant():
assert parse_infix("-42") == UnaryOp(operations.negate, Constant(42))
def test_parse_doubly_negated_constant():
assert parse_infix("--42") == UnaryOp(
operations.negate, UnaryOp(operations.negate, Constant(42))
)
def test_parse_binary_operation():
assert parse_infix("12 + 27") == BinOp(operations.plus, Constant(12), Constant(27))
def test_parse_complete_expression_tree():
assert parse_infix("(12 + 27 )* (42 - 51)") == BinOp(
operations.times,
BinOp(operations.plus, Constant(12), Constant(27)),
BinOp(operations.minus, Constant(42), Constant(51)),
)
def test_power_binds_to_the_right():
assert parse_infix("12 ^ 27 ^ 42") == BinOp(
operations.pow, Constant(12), BinOp(operations.pow, Constant(27), Constant(42))
)
def test_negate_and_pow_dont_mix():
assert parse_infix("-12 ^ 27") == UnaryOp(
operations.negate, BinOp(operations.pow, Constant(12), Constant(27))
)
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,082 | ambroisie/kata | refs/heads/master | /calculator/calculator/ast/visit/__init__.py | from .visitor import Visitor # isort:skip
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,083 | ambroisie/kata | refs/heads/master | /calculator/calculator/core/__init__.py | import calculator.core.operations
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,084 | ambroisie/kata | refs/heads/master | /fizzbuzz/test_fizzbuzz.py | from fizzbuzz import fizzbuzz, fizzbuzzer
def list_output(max, capsys, expected_list, function):
function(max)
out, __ = capsys.readouterr()
assert out == "\n".join(map(lambda x: str(x), expected_list)) + "\n"
def list_fizzbuzz_output(max, capsys, expected_list):
list_output(max, capsys, expected_list, fizzbuzz)
def test_fizzbuzz_counts_to_two(capsys):
list_fizzbuzz_output(2, capsys, [1, 2])
def test_fizzbuzz_shows_fizz_on_three(capsys):
list_fizzbuzz_output(3, capsys, [1, 2, "fizz"])
def test_fizzbuzz_shows_buzz_on_five(capsys):
list_fizzbuzz_output(5, capsys, [1, 2, "fizz", 4, "buzz"])
def test_fizzbuzz_shows_fizzbuzz_on_fifteen(capsys):
list_fizzbuzz_output(
15,
capsys,
[
1,
2,
"fizz",
4,
"buzz",
"fizz",
7,
8,
"fizz",
"buzz",
11,
"fizz",
13,
14,
"fizzbuzz",
],
)
def test_can_foobarbazz_customization(capsys):
foobarbazz = fizzbuzzer({2: "foo", 3: "bar", 4: "bazz"})
list_output(
function=foobarbazz,
max=12,
capsys=capsys,
expected_list=[
1,
"foo",
"bar",
"foobazz",
5,
"foobar",
7,
"foobazz",
"bar",
"foo",
11,
"foobarbazz",
],
)
def test_can_foobarbazz_customization_regardless_of_dict_order(capsys):
foobarbazz = fizzbuzzer({4: "bazz", 3: "bar", 2: "foo"})
list_output(
function=foobarbazz,
max=12,
capsys=capsys,
expected_list=[
1,
"foo",
"bar",
"foobazz",
5,
"foobar",
7,
"foobazz",
"bar",
"foo",
11,
"foobarbazz",
],
)
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,085 | ambroisie/kata | refs/heads/master | /calculator/calculator/core/operations.py | def plus(x: int, y: int) -> int:
return x + y
def minus(x: int, y: int) -> int:
return x - y
def times(x: int, y: int) -> int:
return x * y
def int_div(x: int, y: int) -> int:
return x // y
def pow(x: int, y: int) -> int:
return x ** y
def identity(x: int) -> int:
return x
def negate(x: int) -> int:
return -x
STR_TO_BIN = {
"+": plus,
"-": minus,
"*": times,
"/": int_div,
"^": pow,
}
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,086 | ambroisie/kata | refs/heads/master | /calculator/calculator/eval/evaluator.py | from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING
from calculator.ast.visit import Visitor
from pydantic.dataclasses import dataclass
if TYPE_CHECKING:
from calculator.ast import BinOp, Constant, Node, UnaryOp
@dataclass
class Evaluator(Visitor):
"""
Evaluate a Tree and retrieve the calculated value.
"""
value: int = dataclasses.field(default=0, init=False)
def visit_and_get_value(self, n: Node) -> int:
n.accept(self)
return self.value
def visit_constant(self, c: Constant) -> None:
self.value = c.value
def visit_binop(self, b: BinOp) -> None:
lhs_val = self.visit_and_get_value(b.lhs)
rhs_val = self.visit_and_get_value(b.rhs)
self.value = b.op(lhs_val, rhs_val)
def visit_unaryop(self, b: UnaryOp) -> None:
rhs_val = self.visit_and_get_value(b.rhs)
self.value = b.op(rhs_val)
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,087 | ambroisie/kata | refs/heads/master | /calculator/calculator/parse/infix.py | from __future__ import annotations
from typing import TYPE_CHECKING, List, Union, cast
from calculator.ast import BinOp, Constant, UnaryOp
from calculator.core import operations
from .parsed_string import ParsedString
if TYPE_CHECKING:
from calculator.ast import Node
"""
E : T [ (+|-) T ]*
T : F [ (*|/) F ]*
F : [ (-|+) ]* P
P : G [ (^) F ]*
G : '(' E ')' | CONSTANT
"""
def parse_g(l: List[Union[int, str]]) -> Node:
top = l.pop(0)
if top == "(":
ans = parse_e(l)
assert l.pop(0) == ")"
return ans
return Constant(top)
def parse_p(l: List[Union[int, str]]) -> Node:
lhs = parse_g(l)
while len(l) and l[0] == "^":
op = l.pop(0)
rhs = parse_f(l)
lhs = BinOp(operations.STR_TO_BIN[op], lhs, rhs)
return lhs
def parse_f(l: List[Union[int, str]]) -> Node:
str_to_unop = {
"+": operations.identity,
"-": operations.negate,
}
if l[0] in str_to_unop:
op = l.pop(0)
return UnaryOp(str_to_unop[op], parse_f(l))
return parse_p(l)
def parse_t(l: List[Union[int, str]]) -> Node:
lhs = parse_f(l)
while len(l) and l[0] in ["*", "/"]:
op = cast(str, l.pop(0))
rhs = parse_t(l)
lhs = BinOp(operations.STR_TO_BIN[op], lhs, rhs)
return lhs
def parse_e(l: List[Union[int, str]]) -> Node:
lhs = parse_t(l)
while len(l) and l[0] in ["+", "-"]:
op = cast(str, l.pop(0))
rhs = parse_t(l)
lhs = BinOp(operations.STR_TO_BIN[op], lhs, rhs)
return lhs
def parse_infix(input: str) -> Node:
"""
Parses the given string in infix notation.
"""
parsed = ParsedString(input).tokenize()
ans = parse_e(parsed)
return ans
| {"/calculator/calculator/print/__init__.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/eval/test_evaluator.py": ["/calculator/calculator/eval/evaluator.py"], "/calculator/calculator/parse/test_postfix.py": ["/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/unaryop.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/postfix.py": ["/calculator/calculator/parse/parsed_string.py"], "/calculator/calculator/print/test_printer.py": ["/calculator/calculator/print/printer.py"], "/calculator/calculator/ast/__init__.py": ["/calculator/calculator/ast/node.py", "/calculator/calculator/ast/constant.py", "/calculator/calculator/ast/unaryop.py"], "/calculator/calculator/parse/__init__.py": ["/calculator/calculator/parse/infix.py", "/calculator/calculator/parse/postfix.py"], "/calculator/calculator/ast/constant.py": ["/calculator/calculator/ast/node.py"], "/calculator/calculator/parse/test_infix.py": ["/calculator/calculator/parse/infix.py"], "/calculator/calculator/ast/visit/__init__.py": ["/calculator/calculator/ast/visit/visitor.py"], "/calculator/calculator/parse/infix.py": ["/calculator/calculator/parse/parsed_string.py"]} |
47,117 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/data_types/__init__.py |
from pandas import DataFrame
from datetime import datetime
class Collection:
'''
The Collection class provides an interface for managing collections of
specific items (e.g. trades, or events).
It holds a list of 'items' and provides an interface for interacting with
them.
'''
def __getitem__(self, key):
if isinstance(key, datetime):
return self.find(lambda e: e.date == key)
elif isinstance(key, str):
return self.find(lambda e: e.ticker == key)
elif isinstance(key, int):
return self.items[key]
else:
raise ValueError("key must be a date, ticker (string), or integer")
def __iter__(self):
return self.items.__iter__()
def __len__(self):
return len(self.items)
@property
def count(self):
return len(self.items)
def as_list(self):
return self.items
def as_dataframe(self):
data = [item.as_tuple() for item in self.items]
return DataFrame(data, columns = self.items[0].tuple_fields)
def index(self, item):
return self.items.index(item)
def find(self, condition):
'''
Accepts a callable condition object (e.g. lambda expression), which
must accept a CollectionItem. Returns a new Collection which meet the condition.
'''
new_items = [item for item in self.items if condition(item)]
return self.copy_with(new_items)
def apply(self, modifier):
modified_trades = []
for trade in self.items:
new_trade = modifier(trade)
if new_trade is not None:
modified_trades.append(new_trade)
return self.copy_with(modified_trades)
def subset(self, selection):
'''
Returns a new collection containing only items in the selection.
selection is typically a list of integers representing the index
of the item to select, although a list of tickers will also work.
'''
new_items = [self[s] for s in selection]
return self.copy_with(new_items)
def copy_with(self, items):
'''
Collection classes need to implement copy_with to create new
instances with revised items.
'''
raise NotImplementedError
class CollectionItem:
def as_tuple(self):
return tuple(getattr(self, name) for name in self.tuple_fields)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,118 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/measures/moving_averages.py |
from pandas import DataFrame
import numpy as np
from . import SignalElement
from .volatility import EfficiencyRatio
class EMA(SignalElement):
def __init__(self, period):
self.period = period
def __call__(self, prices):
return prices.ewm(span = self.period).mean()
def update_param(self, new_params):
self.period = new_params
class KAMA(SignalElement):
'''
Calculates the Kaufman adaptive moving average. The smooth parameter varies between the
square of the fast and slow parameters based on the efficiency ratio calculated from
the period number of previous days.
'''
def __init__(self, period, fast = 2, slow = 30):
self.fast = fast
self.slow = slow
self.period = period
self.eff_ratio = EfficiencyRatio(period)
@property
def name(self):
return 'KAMA.{}.{}.{}'.format(self.period, self.fast, self.slow)
def __call__(self, prices):
fastest = 2 / (self.fast + 1.0)
slowest = 2 / (self.slow + 1.0)
ER = self.eff_ratio(prices)
sc = (ER * (fastest - slowest) + slowest) ** 2
kama = DataFrame(None, index = prices.index, columns = prices.tickers, dtype = float)
kama.iloc[self.period] = prices.iloc[self.period]
for i in range((self.period + 1), len(kama)):
prev_kama = kama.iloc[(i - 1)]
curr_prices = prices.iloc[i]
curr_kama = prev_kama + sc.iloc[i] * (curr_prices - prev_kama)
missing_prev_kama = prev_kama.isnull()
if any(missing_prev_kama):
prev_kama[missing_prev_kama] = curr_prices[missing_prev_kama]
missing_curr_kama = curr_kama.isnull()
if any(missing_curr_kama):
curr_kama[missing_curr_kama] = prev_kama[missing_curr_kama]
kama.iloc[i] = curr_kama
return kama
def update_params(self, new_params):
self.period = new_params[0]
self.fast = new_params[1]
self.slow = new_params[2]
class LinearTrend(SignalElement):
'''
Linear trend produces a rolling linear regression output for the given span.
'''
def __init__(self, span):
self.period = span
self.name = "LinTrend.{}".format(span)
X = np.asarray(range(1, self.period + 1))
self.X_bar = X.mean()
self.X_diff = X - self.X_bar
self.SSE_X = (self.X_diff ** 2).sum()
def __call__(self, prices):
return prices.ffill().rolling(self.period).apply(self.trend)
def trend(self, Y):
'''
This gets called by rolling apply, and gets passed a numpy.ndarray.
This will return the linear trend at the end of the supplied window.
'''
Y_bar = Y.mean()
Y_diff = Y - Y_bar
slope = (self.X_diff * Y_diff).sum() / self.SSE_X
intercept = Y_bar - slope * self.X_bar
return slope * self.period + intercept
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,119 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/data_types/positions.py |
from copy import deepcopy
from pandas import DataFrame
from numpy import sign
from system.interfaces import DataElement
from data_types.returns import AggregateReturns
from data_types.trades import Trade, TradeCollection
from data_types.events import EventCollection
class Position(DataElement):
'''
Position objects hold the dual role of keeping the position data for the strategy, as well as
calculating the returns from holding those positions.
'''
def __init__(self, data):
if not isinstance(data, DataFrame):
raise TypeError
self.data = data
self.events = self.create_events()
def create_events(self):
return EventCollection.from_position_data(self.data)
def create_trades(self, strategy):
prices = strategy.trade_prices
trades = []
for ticker in self.events.tickers:
# Note we loop through by ticker and subset the events here so
# we don't have to search the full set of tickers every time.
# The EventCollection caches the subset for each ticker behind the
# scenes.
# Although less elegant, this approach reduced the calculation time
# significantly.
ticker_entries = self.events.related_entries(ticker)
ticker_exits = self.events.related_exits(ticker)
for entry in ticker_entries:
trade_exit = self.events.next_exit(entry, ticker_exits)
# If an entry is generated on the last day, the the entry
# and exit date will be the same which will cause issues.
if entry.date < trade_exit.date:
trades.append(Trade(entry.ticker, entry.date, trade_exit.date,
prices[entry.ticker], self.data[entry.ticker]))
return TradeCollection(trades)
def update_from_trades(self, trades):
new_pos_data = deepcopy(self.data)
new_pos_data[:] = 0
for trade in trades.as_list():
new_pos_data.loc[trade.entry:trade.exit, trade.ticker] = self.data.loc[trade.entry:trade.exit, trade.ticker]
self.data = new_pos_data
self.events = self.create_events()
self.trades = trades
def subset(self, subset_tickers):
new_data = self.data[subset_tickers]
new_positions = Position(new_data)
new_positions.trades = self.trades.find(lambda T: T.ticker in subset_tickers)
return new_positions
def applied_to(self, market_returns):
data = self.data * market_returns.data
#data = data.div(self.num_concurrent(), axis = 'rows')
return AggregateReturns(data)
@property
def start(self):
num = self.num_concurrent()
return num[num != 0].index[0]
def long_only(self):
data = deepcopy(self.data)
data[data < 0] = 0
return Position(data)
def short_only(self):
data = deepcopy(self.data)
data[data > 0] = 0
return Position(data)
def remove(self, excluded):
for trade in excluded:
self.data.loc[trade.entry:trade.exit, trade.ticker] = 0
def num_concurrent(self):
'''
Returns a series of the number of concurrent positions held over time.
'''
data = sign(self.data)
return data.sum(axis = 1)
def normalised(self):
"""
Returns a new Position object with sizes normalised by dividing by the current
total number of positions held on that day.
"""
data = self.data.copy()
data = data.div(self.num_concurrent(), axis = 0)
return Position(data)
def unitised(self):
"""
Returns a new positions object with sizes set to unity (1 long, -1 long).
"""
position_sign = (self.data > 0) * 1
position_sign[self.data < 0] = -1
return Position(position_sign)
# TODO discretise only works for long positions at the moment
def discretise(self, min_size, max_size, step):
"""
Returns a new Position object of discrete position signals.
discretise takes the continuous positions and turns it into a stepped series,
attempting to keep the average area under the curve approximately equivalent.
Refer: https://qoppac.blogspot.com.au/2016/03/diversification-and-small-account-size.html
"""
i = 0
pos = self.data.copy()
pos[pos < min_size] = 0
while min_size + i * step < max_size:
lower = min_size + i * step
upper = min_size + (i + 1) * step
size = min_size + (i + 0.5) * step
pos[(pos >= lower) & (pos < upper)] = size
i += 1
pos[pos > max_size] = max_size
return Position(pos)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,120 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/signals/mean_sd_forecasters.py |
import pandas as pd
import numpy as np
from numpy import NaN, empty, isinf
from copy import deepcopy
from pandas import Panel
from pandas.stats.moments import rolling_mean, rolling_std
from data_types.forecasts import Forecast
class NullForecaster:
'''
The NullForecaster returns 1 for mean where the signal is equal to any of the
provided levels in 'in_trade_levels'.
'''
def __init__(self, in_trade_levels):
if not isinstance(in_trade_levels, list):
in_trade_levels = list(in_trade_levels)
self.in_trade_levels = in_trade_levels
self.name = 'Null Forecaster (lvls: {})'.format(','.join(in_trade_levels))
def __call__(self, strategy):
signal = strategy.lagged_signal
mean = deepcopy(signal.data)
mean[:] = 0
mean = mean.astype(float)
sd = deepcopy(mean)
sd[:] = 1
for lvl in self.in_trade_levels:
mean[signal.data == lvl] = 1
return Forecast(pd.Panel({"Forecast":mean}), pd.Panel({"Forecast":sd}))
class BlockForecaster:
def __init__(self, window, pooled = False, average = "mean"):
self.window = window
self.name = 'Block Forecast (window: {})'.format(window)
self.pooled = pooled
self.average = average
def update_param(self, window):
self.window = window
def __call__(self, strategy):
returns = strategy.market_returns.at("decision")
signal = strategy.signal.at("decision")
if self.pooled:
mean_fcst, sd_fcst = self.pooled_forecast_mean_sd(signal, returns, self.average)
else:
mean_fcst, sd_fcst = self.forecast_mean_sd(signal, returns, self.average)
return Forecast(mean_fcst, sd_fcst)
def forecast_mean_sd(self, signal, returns, average):
tickers = returns.columns
levels = signal.levels
headings = ["Forecast"] + levels
mean_fcst = pd.Panel(NaN, items = headings, major_axis = signal.index, minor_axis = tickers)
sd_fcst = pd.Panel(NaN, items = headings, major_axis = signal.index, minor_axis = tickers)
aligned_signal = signal.alignWith(returns)
for ticker in tickers:
# TODO check lag logic is correct for calculation of BlockForecaster
# signal for decision is available at the same time of forecasting, no lag
decision_inds = signal[ticker]
# signal aligned with returns needs to be return lag + 1 (2 total)
# however, when indexing into dataframe the current day is not returned so
# is in effect one day lag built in already. Therefore only shift 1.
aligned_inds = aligned_signal[ticker]
# returns need to be lagged one day for "CC", "O" timings
# As above, indexing into dataframe effectively already includes lag of 1.
rtns = returns[ticker]
for i, lvl in enumerate(decision_inds):
if i < self.window:
continue
ind = aligned_inds[(i - self.window):i]
rtn = rtns[(i - self.window):i]
for level in levels:
level_returns = rtn[ind == level]
if average == "mean":
mean_fcst[level][ticker][i] = level_returns.mean()
else:
mean_fcst[level][ticker][i] = level_returns.median()
sd_fcst[level][ticker][i] = level_returns.std()
mean_fcst["Forecast"][ticker][i] = mean_fcst[lvl][ticker][i]
sd_fcst["Forecast"][ticker][i] = sd_fcst[lvl][ticker][i]
return (mean_fcst, sd_fcst)
def pooled_forecast_mean_sd(self, signal, returns, average):
tickers = returns.columns
levels = signal.levels
headings = ["Forecast"] + levels
mean_fcst = pd.Panel(NaN, items = headings, major_axis = signal.index, minor_axis = tickers)
sd_fcst = pd.Panel(NaN, items = headings, major_axis = signal.index, minor_axis = tickers)
decision_inds = signal.data
aligned_inds = signal.data.shift(1)
rtns = returns.data
i = self.window
while i < len(decision_inds):
if i < self.window:
continue
ind = aligned_inds[(i - self.window):i]
rtn = rtns[(i - self.window):i]
for level in levels:
level_returns = rtn[ind == level].unstack()
if average == "mean":
mean_fcst[level].iloc[i, :] = level_returns.mean()
else:
mean_fcst[level].iloc[i, :] = level_returns.median()
sd_fcst[level].iloc[i, :] = level_returns.std()
i += 1
mean_fcst = mean_fcst.fillna(method = 'ffill')
sd_fcst = sd_fcst.fillna(method = 'ffill')
for ticker in tickers:
decision_ind = decision_inds[ticker]
for i, lvl in enumerate(decision_ind):
mean_fcst["Forecast"][ticker][i] = mean_fcst[lvl][ticker][i]
sd_fcst["Forecast"][ticker][i] = sd_fcst[lvl][ticker][i]
return (mean_fcst, sd_fcst)
class BlockMeanReturnsForecaster:
def __init__(self, window):
self.window = window
self.name = 'Block Mean Rtn Fcst (window: {})'.format(window)
def update_param(self, window):
self.window = window
def __call__(self, strategy):
returns = strategy.market_returns
mean_fcst, sd_fcst = self.forecast_mean_sd(returns)
return Forecast(mean_fcst, sd_fcst)
def forecast_mean_sd(self, returns):
mean_fcst = pd.Panel({"Forecast":rolling_mean(returns.data, self.window)})
sd_fcst = pd.Panel({"Forecast":rolling_std(returns.data, self.window)})
return (mean_fcst, sd_fcst)
class SmoothDetrendedForecaster:
def __init__(self, span):
self.span = span
self.name = 'Smooth Detrended Fcst (span: {})'.format(span)
def update_param(self, span):
self.smooth = EMA(span)
def __call__(self, strategy):
returns = strategy.market_returns.at("decision")
signal = strategy.signal.at("decision")
mean_fcst, sd_fcst = self.forecast_mean_sd(signal, returns)
return Forecast(mean_fcst, sd_fcst)
def forecast_mean_sd(self, signal, returns):
tickers = returns.columns
levels = signal.levels
headings = ["Forecast"] + levels + ['trend'] + [L + "_detrend" for L in levels]
measures = {}
for level in levels:
measures[level] = pd.DataFrame(NaN, index = signal.index, columns = tickers)
mean_fcst = pd.Panel(NaN, items = headings, major_axis = signal.index, minor_axis = tickers)
sd_fcst = pd.Panel(NaN, items = headings, major_axis = signal.index, minor_axis = tickers)
# TODO check logic of lagged data for SmoothDetrendedForecaster
# signal for decision is available at the same time of forecasting, no lag
decision_inds = signal.data
# signal aligned with returns needs to be return lag + 1 (2 total)
# however, when indexing into dataframe the current day is not returned so
# is in effect one day lag built in already.
aligned_inds = signal.alignWith(returns).data
returns = returns.data
for day in decision_inds.index:
for level in levels:
level_index = aligned_inds.ix[day] == level
measures[level].loc[day, level_index] = returns.loc[day, level_index]
mean_fcst["trend"] = returns.ewm(span = self.span).mean()
sd_fcst["trend"] = returns.ewm(span = self.span).std()
for level in levels:
measures[level] = measures[level].fillna(method = 'ffill')
mean_fcst[level] = measures[level].ewm(span = self.span).mean()
mean_fcst[level + "_detrend"] = mean_fcst[level] - mean_fcst["trend"]
sd_fcst[level] = measures[level].ewm(span = self.span).std()
sd_fcst[level + "_detrend"] = sd_fcst[level] - sd_fcst["trend"]
for day in decision_inds.index:
for level in levels:
level_index = decision_inds.ix[day] == level
mean_fcst["Forecast"].loc[day, level_index] = mean_fcst[level + "_detrend"].loc[day, level_index]
sd_fcst["Forecast"].loc[day, level_index] = sd_fcst[level + "_detrend"].loc[day, level_index]
mean_fcst["Forecast"] = mean_fcst["Forecast"].fillna(method = 'ffill')
sd_fcst["Forecast"] = sd_fcst["Forecast"].fillna(method = 'ffill')
return (mean_fcst, sd_fcst)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,121 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/measures/cross_section.py |
from . import SignalElement
class RelativeReturns(SignalElement):
def __init__(self, period):
self.period = period
def __call__(self, prices):
returns = (prices / prices.shift(1)) - 1
relative = returns.subtract(returns.mean(axis = 'columns'), axis = 'rows')
return relative.ewm(span = self.period).mean()
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,122 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/data_types/market.py | '''
Created on 6 Dec 2014
@author: Mark
'''
from pandas import DateOffset, Panel, DataFrame
import pandas as pd
from mpl_finance import candlestick_ohlc
from matplotlib.dates import date2num
import matplotlib.pyplot as plt
import datetime
# Import from related packages
import os
import sys
sys.path.append(os.path.join("C:\\Users", os.getlogin(), "Source\\Repos\\FinancialDataHandling\\financial_data_handling"))
from system.interfaces import DataElement
from data_types.returns import AverageReturns, Returns
class Market:
'''
Market holds several data frames containing market information for each stock
it comprises.
'''
def __init__(self, store, excluded_tickers = None):
'''
Constructor
'''
instruments = store.get_instruments(excluded_tickers)
self.store = store
self.start = instruments.start
self.end = instruments.end
self.exchange = instruments.exchange
self.instruments = instruments.data
self.indices = []
@property
def tickers(self):
return list(self.instruments.items)
@property
def index(self):
return self.instruments[self.instruments.items[0]].index
def __setitem__(self, key, val):
instruments = dict(self.instruments)
instruments[key] = val
self.instruments = Panel.from_dict(instruments)
def __getitem__(self, key):
return self.instruments[key]
def get_empty_dataframe(self, fill_data = None):
if isinstance(fill_data, str):
data_type = object
else:
data_type = float
return DataFrame(fill_data, index = self.index, columns = self.tickers, dtype = data_type)
def subset(self, subset_tickers):
excluded_tickers = [t for t in self.tickers if t not in subset_tickers]
return Market(self.store, excluded_tickers)
@property
def open(self):
return Prices(self._get_series("Open"), ["open"])
@property
def high(self):
return Prices(self._get_series("High"), ["close"])
@property
def low(self):
return Prices(self._get_series("Low"), ["close"])
@property
def close(self):
return Prices(self._get_series("Close"), ["close"])
@property
def volume(self):
return Prices(self._get_series("Volume"), ["close"])
def at(self, timing):
"""
This method is an implementation of the DataElement.at method, however in this case
it is used to select the right time series, rather than lag period.
"""
if timing.target == "O":
return self.open
elif timing.target == "C":
return self.close
def _get_series(self, name):
return self.instruments.minor_xs(name)
def returns(self, timing = "close"):
trade_days = getattr(self, timing)
return trade_days.returns()
def candlestick(self, ticker, start = None, end = None):
data = self[ticker][start:end]
quotes = zip(date2num(data.index.astype(datetime.date)), data.Open, data.High, data.Low, data.Close)
fig, ax = plt.subplots()
candlestick_ohlc(ax, quotes)
ax.xaxis_date()
fig.autofmt_xdate()
return (fig, ax)
def add_indice(self, ticker):
indice = self.store.get_indice(ticker)
self.indices[indice.ticker] = indice.data
def plot_indice(self, ticker, timing, start, **kwargs):
indice = self.indices[ticker]
if timing.target == "O":
prices = indice.open
elif timing.target == "C":
prices = indice.close
returns = Returns(prices / prices.shift(1) - 1)
returns.plot(label = ticker, start = start, **kwargs)
def get_valuations(self, type, sub_type, date = None):
values = self.store.get_valuations(type, date)
try:
fundamentals_data = values.as_wide_values(sub_type, index = self.index)
except TypeError as E:
print(E)
else:
return Fundamentals(fundamentals_data, sub_type)
class Prices(DataElement):
"""
A Prices object holds a particular series of prices, e.g. Open.
"""
def __init__(self, data, calculation_timing, lag = 0):
self.data = data
self.calculation_timing = calculation_timing
self.lag = lag
def returns(self):
return AverageReturns((self.data / self.data.shift(1)) - 1)
class Fundamentals(DataElement):
"""
Provides an interface for different fundamentals data; valuations,
earnings, etc.
"""
def __init__(self, data, name):
self.name = name
self.data = data
self.calculation_timing = ['close']
self.lag = 0
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,123 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/measures/breakout.py | import pandas as pd
from . import SignalElement
class TrailingHighLow(SignalElement):
def __init__(self, lookback):
self.period = lookback
def update_param(self, new_params):
self.period = new_params[0]
def __call__(self, prices):
'''
Returns a panel with the last high, and last low.
'''
high = prices.rolling(self.period).max()
low = prices.rolling(self.period).min()
return pd.Panel.from_dict({"high" : high, "low" : low}) | {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,124 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/system/models.py | '''
The models package provides some methods for predicting which
trades to select given some metrics and filtering values.
'''
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
from measures.valuations import ValueRatio
def build_data_table(strat,
epv = ['Adjusted', 'Cyclic', 'Base'],
metrics = ['ROIC (%)', 'Growth mult.', 'Dilution (%)']):
filter_names = epv[:]
filter_names.extend(metrics)
print('Loading filter data', end='')
filters = []
for filt in filter_names:
if filt in epv:
filters.append(ValueRatio('EPV', filt)(strat))
elif filt in metrics:
filters.append(strat.market.get_valuations('Metrics', filt))
print('.', end = '')
print('\nBuilding data table', end = '')
trade_df = strat.trades.as_dataframe(); print('.', end='')
filter_names = []
for filter in filters:
trade_df = strat.trades.add_to_df(trade_df, filter)
filter_names.append(filter.name)
print('.', end='')
print('')
print('\nCleaning data')
# Drop any rows with NA values.
len_before = len(trade_df)
print('- starting rows: {}'.format(len_before))
trade_df = trade_df.dropna()
print('- dropped {} NA rows'.format(len_before - len(trade_df)))
# Drop rows where filter values are > 2 std devs from mean.
len_before = len(trade_df)
for filter_col in filter_names:
filter_col = trade_df[filter_col]
filt_mean = filter_col.mean()
filt_sd = filter_col.std()
lower_bnd = (filt_mean - 2 * filt_sd)
upper_bnd = (filt_mean + 2 * filt_sd)
trade_df = trade_df[(filter_col > lower_bnd) & (filter_col < upper_bnd)]
print('- dropped {} Outlier rows'.format(len_before - len(trade_df)))
trade_df.filter_names = filter_names
return trade_df
def prepare_x_y_data(trade_df, filter_names, model_metric, metric_threshold):
x_table = trade_df[filter_names]
y_data = trade_df[model_metric].copy()
y_data.loc[y_data > metric_threshold] = 1
y_data.loc[y_data <= metric_threshold] = 0
return (x_table.values, y_data.values)
def build_model_data(strat,
epv = ['Adjusted', 'Cyclic', 'Base'],
metrics = ['ROIC (%)', 'Growth mult.', 'Dilution (%)'],
model_metric = 'normalised_return',
metric_threshold = 0.15):
trade_df = build_data_table(strat, epv, metrics)
print('Preparing model data')
x_data, y_data = prepare_x_y_data(trade_df, trade_df.filter_names, model_metric, metric_threshold)
return (trade_df, x_data, y_data)
def assess_classifier(model, x, y, split_test = 0.3):
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = split_test)
model.fit(x_train, y_train)
train_pred = model.predict(x_train)
test_pred = model.predict(x_test)
print('Confusion matrix train\n')
print(confusion_matrix(y_train, train_pred))
print('\nConfusion matrix test\n')
print(confusion_matrix(y_test, test_pred))
print('\nClassification report train\n')
print(classification_report(y_train, train_pred))
print('\nClassification report test\n')
print(classification_report(y_test, test_pred))
return model
def assess_regressor(model, x, y, split_test = 0.3, threshold = 0):
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = split_test)
if isinstance(model, list):
first_model = model[0]
first_model.fit(x_train, y_train)
train_pred = first_model.predict(x_train)
test_pred = first_model.predict(x_test)
for m in model[1:]:
m.fit(x_train, y_train)
train_pred += m.predict(x_train)
test_pred += m.predict(x_test)
train_pred /= len(model)
test_pred /= len(model)
else:
model.fit(x_train, y_train)
train_pred = model.predict(x_train)
test_pred = model.predict(x_test)
train_pred_id = train_pred[:]
train_pred_id[train_pred_id <= threshold] = -1
train_pred_id[train_pred_id > threshold] = 1
test_pred_id = test_pred[:]
test_pred_id[test_pred_id <= threshold] = -1
test_pred_id[test_pred_id > threshold] = 1
train_id = y_train[:]
train_id[train_id <= threshold] = -1
train_id[train_id > threshold] = 1
test_id = y_test[:]
test_id[test_id <= threshold] = -1
test_id[test_id > threshold] = 1
print('Confusion matrix train\n')
print(confusion_matrix(train_id, train_pred_id))
print('\nConfusion matrix test\n')
print(confusion_matrix(test_id, test_pred_id))
print('\nClassification report train\n')
print(classification_report(train_id, train_pred_id))
print('\nClassification report test\n')
print(classification_report(test_id, test_pred_id))
return model
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,125 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/data_types/returns.py | '''
The returns module contains classes for dealing with different
types of returns data.
'''
from pandas import DataFrame, Series, Categorical
from pandas.core.common import isnull
from numpy import NaN, arange, log, exp
import matplotlib.pyplot as plt
from system.interfaces import DataElement
from system.metrics import Drawdowns, OptF
from data_types.constants import TRADING_DAYS_PER_YEAR
class Returns(DataElement):
"""
Returns represents a returns Series, and provides methods for summarising
and plotting.
"""
def __init__(self, data):
self.data = data.fillna(0)
self.lag = 1
self.calculation_timing = ["entry", "exit"]
self.indexer = None
def __getitem__(self, key):
return self.data[key]
def __len__(self):
return len(self.data)
def __sub__(self, other):
return Returns(self.data - other.data)
def append(self, other):
self.data[other.data.columns] = other.data
def int_indexed(self):
'''
Converts to integer based index.
'''
return Returns(Series(self.data.values))
def final(self):
'''
Returns the final cumulative return of the series
'''
return exp(self.log().sum()) - 1
def cumulative(self):
returns = self.log()
return exp(returns.cumsum()) - 1
def log(self):
returns = self.data
returns[returns <= -1.0] = -0.9999999999
return log(returns + 1)
def plot(self, start = None, **kwargs):
returns = self.cumulative()
if start is not None:
start_value = returns[start]
if isinstance(start_value, Series):
start_value = start_value[0]
returns = returns - start_value
returns[start:].plot(**kwargs)
def annualised(self):
return (1 + self.final()) ** (TRADING_DAYS_PER_YEAR / len(self)) - 1
def drawdowns(self):
return Drawdowns(self.cumulative())
def sharpe(self):
mean = self.data.mean()
std = self.data.std()
if isinstance(std, Series):
std[std == 0] = NaN
else:
std = NaN
return (mean / std) * (TRADING_DAYS_PER_YEAR ** 0.5)
def optf(self):
return OptF(self.data)
def annual_mean(self):
return self.data.mean() * TRADING_DAYS_PER_YEAR
def volatility(self):
return self.data.std() * (TRADING_DAYS_PER_YEAR ** 0.5)
def normalised(self):
volatility = self.volatility()
if volatility == 0:
return NaN
else:
return self.annualised() / volatility
def monthly(self, start = None):
'''
monthly returns a dict with a number of dataframes of returns summarised
by month (columns) and year (rows).
monthly accepts a start parameter as a date to crop the data from.
'''
data = self.data[start:]
returns = DataFrame(data.values, index = data.index, columns = ["Returns"])
returns['Month'] = returns.index.strftime("%b")
returns['Month'] = Categorical(returns['Month'], ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])
returns['Year'] = returns.index.strftime("%Y")
grouped = returns.groupby(["Year", "Month"])
result = {}
result["mean"] = grouped.mean().unstack() * 12
result['std'] = grouped.std().unstack() * (12 ** 0.5)
result['sharpe'] = result['mean'] / result['std']
return result
def plot_monthly(self, start = None, values = 'sharpe'):
if isinstance(values, list):
fig, axes = plt.subplots(nrows = 1, ncols = len(values))
else:
fig, ax = plt.subplots()
axes = (ax, )
results = self.monthly(start = start)
for i, value in enumerate(values):
data = results[value.lower()].transpose()
title = value.upper()[0] + value.lower()[1:]
x_labels = data.columns
y_labels = data.index.levels[1]
ax = axes[i]
self.plot_heatmap(data.values, x_labels, y_labels, title, ax)
fig.tight_layout()
def plot_heatmap(self, values, x_labs, y_labs, title, ax):
im = ax.imshow(values, cmap = "RdYlGn")
ax.set_xticks(arange(len(x_labs)))
ax.set_yticks(arange(len(y_labs)))
ax.set_xticklabels(x_labs)
ax.set_yticklabels(y_labs)
plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
for i in range(len(y_labs)):
for j in range(len(x_labs)):
ax.text(j, i, round(values[i, j], 2), ha="center", va="center", fontsize=8)
ax.set_title(title)
plt.colorbar(im, ax = ax)
class AggregateReturns(Returns):
"""
AggregateReturns represents a dataframe of returns which are summed for the overall
result (e.g. the result of position weighted returns).
"""
def __init__(self, data):
super().__init__(data)
self.columns = data.columns
def combined(self):
return Returns(self.data.sum(axis = 1))
def log(self):
return self.combined().log()
def annualised(self):
return self.combined().annualised()
class AverageReturns(Returns):
"""
AverageReturns represents a dataframe of returns which are averaged for the overal
result (e.g. market returns).
"""
def __init__(self, data):
super().__init__(data)
self.columns = data.columns
def combined(self):
return Returns(self.data.mean(axis = 1))
def log(self):
return self.combined().log()
def annualised(self):
return self.combined().annualised()
class StrategyReturns(AggregateReturns):
"""
StrategyReturns is a hypothetical result of the strategy assuming that rebalancing
can happen daily at no cost, to ensure that the strategy is fully invested. Positions
are divided by the number of concurrent positions for the day to normalise.
"""
def __init__(self, data, positions):
data = data.div(positions.num_concurrent(), axis = 'rows')
super().__init__(data)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,126 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/trade_modifiers/filters.py |
from system.interfaces import FilterInterface
class HighPassFilter(FilterInterface):
'''
HighPassFilter allows trades where the filter values are above the specified threshold.
'''
def __init__(self, values, threshold):
'''
Filters assume that the supplied values are a DataElement object.
threshold specifies the value above which the filter passes.
'''
self.values = values
self.threshold = threshold
self.filter_name = values.name
self.name = '{}:{}'.format(values.name, threshold)
def accepted_trade(self, trade):
'''
Returns True if the value is above the threshold at the trade entry, else False.
'''
value = self.get(trade.entry, trade.ticker)
if value is None:
return False
else:
return value > self.threshold
def plot(self, ticker, start, end, ax):
self.values.plot(ticker, start, end, ax)
class LowPassFilter(FilterInterface):
'''
LowPassFilter allows trades where the filter values are below the specified threshold.
'''
def __init__(self, values, threshold):
'''
Filters assume that the supplied values are a DataElement object.
threshold specifies the value below which the filter passes.
'''
self.values = values
self.threshold = threshold
self.filter_name = values.name
self.name = '{}:{}'.format(values.name, threshold)
def accepted_trade(self, trade):
'''
Returns True if the value is above the threshold at the trade entry, else False.
'''
value = self.get(trade.entry, trade.ticker)
if value is None:
return False
else:
return value < self.threshold
def plot(self, ticker, start, end, ax):
self.values.plot(ticker, start, end, ax)
class BandPassFilter(FilterInterface):
'''
BandPassFilter allows trades according to where the filter values lie with respect to the
specified range. if 'within_bounds' is True (default), values falling within the range result in
acceptance of the trade, and vice-versa.
'''
def __init__(self, values, bounds, within_bounds = True):
'''
Assumes that values is a DataElement object.'
bounds is an iterable (e.g. tuple) which specifies the upper and lower range.
When within_bounds is True (the default), the filter will pass values between
the min and max values of bounds, else it will pass when outside the min or max.
'''
self.values = values
self.bounds = bounds
self.within_bounds = within_bounds
self.filter_name = values.name
self.name = '{}:{}-{}'.format(values.name, min(bounds), max(bounds))
def accepted_trade(self, trade):
'''
Returns True if the value is within the threshold at the trade entry, else False.
'''
value = self.get(trade.entry, trade.ticker)
if value is None:
return False
else:
return (not self.within_bounds) ^ (min(self.bounds) < value < max(self.bounds))
def plot(self, ticker, start, end, ax):
self.values.plot(ticker, start, end, ax)
# TODO EntryLagFilter is an Entry Condition, not a Filter
class EntryLagFilter(FilterInterface):
def __init__(self, lag):
self.lag = lag
def __call__(self, strategy):
prices = strategy.get_trade_prices()
new_trades = []
for trade in strategy.trades.as_list():
if trade.duration <= self.lag:
continue
new_possible_entries = trade.normalised.index[trade.normalised > 0]
new_possible_entries = new_possible_entries[new_possible_entries > self.lag]
if len(new_possible_entries) == 0:
continue
new_entry_lag = min(new_possible_entries) + 1
if new_entry_lag >= trade.duration:
continue
new_entry = prices[trade.entry:].index[new_entry_lag]
new_trades.append(Trade(trade.ticker, new_entry, trade.exit, prices[trade.ticker]))
return TradeCollection(new_trades)
def plot(self, ticker, start, end, ax):
pass
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,127 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/data_types/constants.py | """
Global constants for the project, e.g. tickers for a given market.
And enums.
"""
from enum import Enum
class TradeSelected(Enum):
UNDECIDED = 0
YES = 1
NO = -1
TRADING_DAYS_PER_YEAR = 260
ASX20 = ["AMP", "ANZ", "BHP", "BXB", "CBA", "CSL", "IAG", "MQG", "NAB", "ORG", "QBE",
"RIO", "SCG", "SUN", "TLS", "WBC", "WES", "WFD", "WOW", "WPL"]
valued_tickers = [u'ONT', u'TGP', u'TIX', u'TOF', u'3PL', u'ABP', u'ALR', u'ACR',
u'ADA', u'AAU', u'ASW', u'AGL', u'AGJ', u'APW', u'AGI', u'AIZ',
u'AQG', u'LEP', u'ALU', u'AMA', u'AMB', u'AMH', u'AMC', u'AGF',
u'ANN', u'ANO', u'APE', u'APA', u'APN', u'APD', u'ARB', u'AAD',
u'ARF', u'ARG', u'ALL', u'AIK', u'ASZ', u'ASH', u'AJJ', u'AUF',
u'AJA', u'ATR', u'ASX', u'AUB', u'AIA', u'AZJ', u'AUP', u'AST',
u'AGD', u'AAC', u'AAP', u'AEF', u'AFI', u'AKY', u'API', u'ARW',
u'AUI', u'AVG', u'AHG', u'AOG', u'AVJ', u'AXI', u'AZV', u'BLX',
u'BCN', u'BFG', u'BHP', u'BGL', u'BXN', u'BIS', u'BKI', u'BGG',
u'BWF', u'BWR', u'BLA', u'BSL', u'BLD', u'BXB', u'BRG', u'BKW',
u'BYL', u'BBL', u'BPA', u'BSA', u'BTT', u'BUG', u'BAP', u'BWP',
u'BPG', u'CAB', u'CDM', u'CTX', u'CZZ', u'CAJ', u'CAA', u'CDP',
u'CIN', u'CAR', u'CWP', u'CLT', u'CAF', u'CNI', u'CYA', u'CHC',
u'CQR', u'CII', u'CSS', u'CVW', u'CIW', u'CLV', u'CMI', u'CCL',
u'CDA', u'CLH', u'CKF', u'CMP', u'CPU', u'CTD', u'COO', u'CUP',
u'CCP', u'CMW', u'CWN', u'CTE', u'CSV', u'CSL', u'CSR', u'CLX',
u'CUE', u'CYC', u'DTL', u'DCG', u'DSB', u'DGH', u'DVN', u'DXS',
u'DUI', u'DJW', u'DMP', u'DRM', u'DOW', u'DRA', u'DWS', u'ELX',
u'EMB', u'EGO', u'EPD', u'EOL', u'EWC', u'ETE', u'EGL', u'EQT',
u'EPW', u'EBG', u'EGH', u'FAN', u'FRM', u'FFI', u'FID', u'FRI',
u'FPH', u'FSI', u'FWD', u'FBU', u'FXL', u'FLT', u'FET', u'FLK',
u'FSF', u'FMG', u'FNP', u'FSA', u'FGX', u'GUD', u'GEM', u'GAP',
u'GJT', u'GZL', u'GBT', u'GHC', u'GLE', u'GCS', u'GLH', u'GFL',
u'GLB', u'GMG', u'GOW', u'GPT', u'GNG', u'GNC', u'GXL', u'GOZ',
u'HSN', u'HVN', u'HGG', u'HNG', u'HIT', u'HOM', u'HZN', u'HPI',
u'HHV', u'HHL', u'ICS', u'IMF', u'IPL', u'IGO', u'IFN', u'IFM',
u'INA', u'ITQ', u'IRI', u'IOF', u'IVC', u'IFL', u'IPE', u'IRE',
u'IBC', u'ISD', u'ITD', u'JYC', u'JIN', u'KSC', u'KAM', u'KBC',
u'KRM', u'KME', u'KKT', u'KOV', u'LMW', u'LBL', u'LGD', u'LLC',
u'LHC', u'LIC', u'LAU', u'LCM', u'LCE', u'MLD', u'MQA', u'MRN',
u'MFG', u'MFF', u'MTR', u'MCE', u'MXI', u'MSP', u'MYX', u'MMS',
u'MCP', u'MVP', u'MLB', u'MLX', u'MWR', u'MLT', u'MRC', u'MIR',
u'MGR', u'MNF', u'MBE', u'MND', u'MVF', u'MNY', u'MOC', u'MYR',
u'NMS', u'NTC', u'NCM', u'NHH', u'NCK', u'NST', u'NUF', u'OCL',
u'OGC', u'OCP', u'OSH', u'OEC', u'ORL', u'OFX', u'PEA', u'PFM',
u'PGC', u'PFL', u'PAY', u'PPC', u'PTL', u'PPT', u'PRU', u'PXS',
u'PHI', u'PTM', u'PMC', u'PRT', u'PME', u'PPG', u'PRO', u'PSZ',
u'PTB', u'PHA', u'QAN', u'QTM', u'RMS', u'RHC', u'RND', u'RCG',
u'REA', u'RKN', u'RFT', u'RDH', u'REH', u'RCT', u'REX', u'RRL',
u'RHT', u'RDG', u'RFG', u'REF', u'RIS', u'RIC', u'RIO', u'RWH',
u'RFF', u'RXP', u'SAI', u'SFR', u'SAR', u'SND', u'SFC', u'SDI',
u'SLK', u'SEK', u'SHV', u'SEN', u'SRV', u'SSM', u'SWL', u'SGF',
u'SHU', u'SHJ', u'SIP', u'SIV', u'SRX', u'SIT', u'SKT', u'SKC',
u'SGH', u'SMX', u'SOM', u'SHL', u'SKI', u'SPK', u'SPO', u'SDF',
u'SST', u'SGP', u'SDG', u'SUL', u'SNL', u'TAH', u'TWD', u'TMM',
u'TGR', u'TTS', u'TCN', u'TNE', u'TLS', u'TGG', u'TFC', u'TRS',
u'SGR', u'TSM', u'TGA', u'TOP', u'TOX', u'TPM', u'TME', u'TTI',
u'TCO', u'TWE', u'TBR', u'UOS', u'UPG', u'UNV', u'VII', u'VLW',
u'VRT', u'VTG', u'VSC', u'VMT', u'VOC', u'WAA', u'WAM', u'WAX',
u'SOL', u'WAT', u'WEB', u'WBA', u'WLL', u'WES', u'WSA', u'WHF',
u'WIG', u'WPL', u'WOW', u'WRR', u'XRF', u'XTE', u'ZGL']
dodgy_tickers = [u'MWR', u'FGX', u'NMS', u'ARW', u'SOM', u'GJT',
u'ICS', u'XTE', u'EGO', u'BXN', u'DRA', u'VMT',
u'PGC']
ASX_VALUED = list(set(valued_tickers) - set(dodgy_tickers))
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,128 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/data_types/forecasts.py | '''
Created on 20 Dec 2014
@author: Mark
'''
class Forecast:
'''
A Forecast element supports position calculations for certain position rules.
Given the mean and standard deviation forecasts over time, it calculates the optimal F.
'''
def __init__(self, mean, sd):
self.mean = mean
self.sd = sd
@property
def mean(self):
return self._mean["Forecast"]
@mean.setter
def mean(self, data):
self._mean = data
@property
def sd(self):
return self._sd["Forecast"]
@sd.setter
def sd(self, data):
self._sd = data
def optF(self):
optimal_fraction = self.mean / self.sd ** 2
optimal_fraction[isinf(optimal_fraction)] = 0
return optimal_fraction
class MeanForecastWeighting:
def __call__(self, forecasts):
items = list(bounds(len(forecasts)))
means = [forecast.mean for forecast in forecasts]
means = zip(items, means)
stds = [forecast.sd for forecast in forecasts]
stds = zip(items, stds)
means = Panel({item:frame for item, frame in means})
stds = Panel({item:frame for item, frame in stds})
return MeanForecast(means.mean(axis = "items"), stds.mean(axis = "items"))
class MeanForecast(Forecast):
@property
def mean(self):
return self._mean
@mean.setter
def mean(self, data):
self._mean = data
@property
def sd(self):
return self._sd
@sd.setter
def sd(self, data):
self._sd = data
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,129 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/trade_modifiers/weighting.py |
class TradeWeighting:
def __init__(self, weights):
self.values = weights
def __call__(self, trade):
weight = self.get(trade.entry, trade.ticker)
if weight is not None:
trade.position_size = weight
return trade
def get(self, date, ticker):
try:
value = self.values.loc[date, ticker]
except KeyError:
value = None
return value | {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,130 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/signals/level_signals.py |
from pandas import Panel, DataFrame
from system.interfaces import SignalElement
from data_types.signals import Signal
class Crossover(SignalElement):
'''
The Crossover signal compares two indicators (fast and slow) to determine whether
the prevailing trend is 'Up' (fast > slow) or 'Down' (fast <= slow).
'''
def __init__(self, slow, fast):
self.fast = fast
self.slow = slow
@property
def name(self):
return "x".join([self.fast.name, self.slow.name])
@property
def measures(self):
return [self.fast, self.slow]
def execute(self, strategy):
prices = strategy.indicator_prices
fast_ema = self.fast(prices)
slow_ema = self.slow(prices)
ind_data = strategy.get_empty_dataframe(fill_data = 'Down')
ind_data[fast_ema > slow_ema] = 'Up'
return Signal(ind_data, ['Up', 'Down'], {'Fast':fast_ema, 'Slow':slow_ema})
def update_param(self, new_params):
self.slow.update_param(max(new_params))
self.fast.update_param(min(new_params))
class TripleCrossover(SignalElement):
'''
The Triple Crossover signal is similar to the Crossover except it uses three indicators (fast, mid and slow).
The prevailing trend is 'Up' when (fast > mid) and (mid > slow), and 'Down' otherwise.
'''
def __init__(self, slow, mid, fast):
self.fast = fast
self.mid = mid
self.slow = slow
@property
def name(self):
return "x".join([self.fast.name, self.mid.name, self.slow.name])
@property
def measures(self):
return [self.fast, self.mid, self.slow]
def execute(self, strategy):
prices = strategy.indicator_prices
fast_ema = self.fast(prices)
mid_ema = self.mid(prices)
slow_ema = self.slow(prices)
levels = (fast_ema > mid_ema) & (mid_ema > slow_ema)
ind_data = strategy.get_empty_dataframe(fill_data = 'Down')
ind_data[levels] = 'Up'
return Signal(ind_data, ['Up', 'Down'], {'Fast':fast_ema, 'Mid':mid_ema, 'Slow':slow_ema})
def update_param(self, new_params):
pars = list(new_params)
pars.sort()
self.fast = pars[0]
self.mid = pars[1]
self.slow = pars[2]
class Breakout(SignalElement):
def __init__(self, breakout_measure):
self.breakout = breakout_measure
@property
def name(self):
return "Breakout." + self.breakout.name
@property
def measures(self):
return [self.breakout]
def execute(self, strategy):
prices = strategy.indicator_prices
breakout = self.breakout(prices)
high = breakout["high"]
low = breakout["low"]
ind_data = strategy.get_empty_dataframe()
# Note: dataframe.where returns the existing values where the
# mask is True, and replaces them with other where False.
# So we need to invert the mask.
# Counterintuitive I think...
ind_data = ind_data.where(~(prices.data == high), 'Up')
ind_data = ind_data.where(~(prices.data == low), 'Down')
ind_data = ind_data.ffill()
# We need to remove any remaining Nans (at the start of the df),
# otherwise later string comparisons will throw an error because
# it thinks it is a mixed datatype.
ind_data = ind_data.fillna('-')
return Signal(ind_data, ['Up', 'Down'], breakout)
def update_param(self, new_params):
self.breakout.update_param(new_params)
class MultiLevelMACD(SignalElement):
"""
The MultiLevelMACD creates a defined set of levels above and below zero
based on the MACD level.
"""
def __init__(self, fast, slow, levels):
"""
ema_pars is a tuple of (fast, slow) parameters for the EMA calc.
levels is an integer which determines how many segments the
signal is broken up into above and below zero.
"""
self.fast = fast
self.slow = slow
self.levels = levels
@property
def name(self):
return "{}.lvl-MACD_".format(self.levels) + ".".join([self.fast.name, self.slow.name])
def update_params(self, new_params):
self.fast.update_param(min(new_params))
self.slow.update_param(max(new_params))
def execute(self, strategy):
prices = strategy.indicator_prices
fast = self.fast(prices)
slow = self.slow(prices)
return Signal(fast - slow, ['forecast'], {'fast':fast, 'slow':slow})
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,131 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/system/analysis.py | # System analysis
import matplotlib.pyplot as plt
from pandas import qcut, cut, concat, DataFrame, Series
from numpy import log, random, arange, NaN
from multiprocessing import Pool, cpu_count
import time
from data_types.returns import Returns, AverageReturns
from data_types.constants import TRADING_DAYS_PER_YEAR
from system.core import Strategy, Portfolio
from system.metrics import *
from trade_modifiers.exit_conditions import StopLoss, TrailingStop
# Profiling
class Timer:
'''
Usage:
with Timer() as t:
[run method to be timed]
print("some words: %ss" % t.secs)
or the following will output as milliseconds "elapsed time: [time] ms":
with Timer(verbose = True) as t:
[run method to be timed]
'''
def __init__(self, verbose=False):
self.verbose = verbose
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.secs = self.end - self.start
self.msecs = self.secs * 1000 # millisecs
if self.verbose:
print("elapsed time: %f ms" % self.msecs)
# Signal analysis
def signal_summary(returns, levels):
'''
Takes a dataframe of returns, and dataframe of levels (typically
['Flat', 'Long', 'Short'], but could be anything), and returns a
summary of performance for each of the levels and base returns.
Used to compare whether the segregation from a signal is improving
the return profile.
'''
metrics = ['mean', 'median', 'std', 'skew', OptF, GeometricGrowth]
grouped = returns.stack().groupby(levels.stack())
summary = grouped.agg(metrics).T # Transpose to have metrics as index for adding base
summary.insert(0, 'Base', returns.stack().agg(metrics))
summary.loc['mean'] *= TRADING_DAYS_PER_YEAR
summary.loc['std'] *= (TRADING_DAYS_PER_YEAR ** 0.5)
summary.loc['Sharpe'] = summary.loc['mean'] / summary.loc['std']
return summary
# Path dependent trade results
# Attempts to characterise trade outcomes based on path taken.
# Mean and std deviation
# Winners vs losers
def win_loss_trace(trades):
tf = trades.trade_frame(compacted = False, cumulative = True)
rets = trades.returns
winners = tf[rets > 0]
losers = tf[rets <= 0]
win_N = winners.count()
win_cutoff = max(win_N[win_N > max(round(win_N[0] * 0.3), 20)].index)
los_N = losers.count()
los_cutoff = max(los_N[los_N > max(round(los_N[0] * 0.3), 20)].index)
cutoff = min(win_cutoff, los_cutoff)
win_mean = winners.mean()[:cutoff]
win_std = winners.std()[:cutoff]
los_mean = losers.mean()[:cutoff]
los_std = losers.std()[:cutoff]
for trace in [('blue', win_mean, win_std), ('red', los_mean, los_std)]:
trace[1].plot(color = trace[0])
(trace[1] + trace[2]).plot(style = '--', color = trace[0])
(trace[1] - trace[2]).plot(style = '--', color = trace[0])
def std_dev_trace(trades):
tf = trades.trade_frame(compacted = False, cumulative = True)
rets = trades.returns
tf_N = tf.count()
cutoff = max(tf_N[tf_N > max(round(tf_N[0] * 0.3), 20)].index)
tf_normalised = tf.loc[:, :cutoff]
tf_normalised = (tf_normalised - tf_normalised.mean()) / tf_normalised.std()
winners = tf_normalised[rets > 0]
losers = tf_normalised[rets <= 0]
win_mean = winners.mean()
los_mean = losers.mean()
for trace in [('blue', win_mean), ('red', los_mean)]:
trace[1].plot(color = trace[0])
def result_after_delay(trades, N):
# Calculate the remaining returns if entry is lagged.
# This will establish if short duration losers are impacting the results.
tf = trades.trade_frame(compacted = False, cumulative = False)
cutoff = min(tf.shape[1], N)
tf_log = log(tf + 1)
result = DataFrame(columns = list(range(cutoff)), dtype = float)
for i in range(cutoff):
result[i] = tf_log.loc[:, i:].sum(axis = 1)
return result
# Boxplot by return outcomes
def box_colour(bp, box_num, edge_color):
for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
plt.setp(bp[element], color = edge_color)
def boxplot_path_by_outcome(trades, day):
tf = trades.trade_frame(compacted = False, cumulative = False)
# Get the daily returns from the day after the requested day onwards.
# Remove any trades which are empty moving forward, as we know these would have been closed.
forward = tf.loc[:, (day + 1):].dropna(how = 'all')
forward = log(forward + 1)
backward = tf.loc[forward.index, :day]
backward = log(backward + 1)
df = DataFrame(dtype = float)
df['Final Return'] = qcut(forward.sum(axis = 1).round(2), 5)
df['Current Return'] = backward.sum(axis = 1)
bp = df.boxplot('Current Return', by = 'Final Return', return_type = 'dict')
whisker_points = []
[whisker_points.extend(list(whisker.get_ydata())) for whisker in bp[0]['whiskers']]
y_min = min(whisker_points) * 1.1
y_max = max(whisker_points) * 1.1
plt.ylim((y_min, y_max))
plt.xticks(fontsize = 'small', rotation = 30)
plt.ylabel('Current Return')
plt.title('Day {}'.format(day))
# TODO implement boxplot_outcome_by_path
def boxplot_outcome_by_path(trades, day):
pass
# Plot trends of trade collection
def prep_for_lm(x, y):
nulls = (x * y).isnull()
x = x[~nulls]
x = x.reshape(x.count(), 1)
y = y[~nulls]
return (x, y)
def tf_sum(tf, start, end):
tf_log = log(tf + 1)
X = tf_log.iloc[:, start:end].sum(axis = 1)
return X
def tf_sharpe(tf, start, end):
X_mean = tf.iloc[:, start:end].mean(axis = 1)
X_std = tf.iloc[:, start:end].std(axis = 1)
return X_mean / X_std
def calc_trends(trades, dep_time, dep_method, indep_method):
allowable_timing = ['end', 'interim']
allowable_dep_methods = {
'sum' : tf_sum,
'sharpe' : tf_sharpe
}
allowable_indep_methods = {
'sum' : tf_sum
}
if dep_time not in allowable_timing:
raise ValueError('dep_timing must be one of: {}'.format(', '.join(allowable_timing)))
try:
dep_method = allowable_dep_methods[dep_method]
except KeyError:
raise ValueError('dep_method must be one of: {}'.format(', '.join(allowable_dep_methods.keys())))
try:
indep_method = allowable_indep_methods[indep_method]
except KeyError:
raise ValueError('indep_method must be one of: {}'.format(', '.join(allowable_indep_methods.keys())))
lm = LinearRegression()
tf = trades.trade_frame(compacted = False, cumulative = False)
trends = DataFrame([-0.1, -0.01, 0, 0.01, 0.1])
result = DataFrame(None, None, trends[0], dtype = float)
if dep_time == 'end':
R = dep_method(tf, None, None)
i = j = 1
while j < tf.shape[1] and tf[tf.columns[j]].count() >= 20:
X = indep_method(tf, None, (j + 1))
if dep_time == 'interim':
R = dep_method(tf, (j + 1), None)
X, R_i = prep_for_lm(X, R)
lm.fit(X, R_i)
result.loc[j, :] = lm.predict(trends)
k = j
j += i
i = k
return result
def plot_trends(trades):
f, axarr = plt.subplots(2, 2, sharex = True)
sp00 = calc_trends(trades, dep_time = 'interim', dep_method = 'sum', indep_method = 'sum')
sp10 = calc_trends(trades, dep_time = 'interim', dep_method = 'sharpe', indep_method = 'sum')
sp01 = calc_trends(trades, dep_time = 'end', dep_method = 'sum', indep_method = 'sum')
sp11 = calc_trends(trades, dep_time = 'end', dep_method = 'sharpe', indep_method = 'sum')
sp00.plot(ax = axarr[0, 0])
sp10.plot(ax = axarr[1, 0])
sp01.plot(ax = axarr[0, 1])
sp11.plot(ax = axarr[1, 1])
axarr[0, 0].set_xscale('log')
axarr[1, 0].set_xscale('log')
axarr[0, 1].set_xscale('log')
axarr[1, 1].set_xscale('log')
axarr[0, 0].set_title('Interim')
axarr[0, 0].set_ylabel('Sum')
axarr[1, 0].set_ylabel('Sharpe')
axarr[0, 1].set_title('End')
# TODO Test signal performance against TrendBenchmark
class TrendBenchmark(object):
'''
The TrendBenchmark is not intended for use in a strategy, but for testing the performance
of an indicator against ideal, perfect hindsight identification of trends.
'''
def __init__(self, period):
self.period = period
def __call__(self, strategy):
prices = strategy.get_indicator_prices()
trend = DataFrame(None, index = prices.index, columns = prices.columns, dtype = float)
last_SP = Series(None, index = prices.columns)
current_trend = Series('-', index = prices.columns)
for i in range(prices.shape[0] - self.period):
# If there are not any new highs in the recent period then must have been
# a swing point high.
SPH = ~(prices.iloc[(i + 1):(i + self.period)] > prices.iloc[i]).any()
# NaN in series will produce false signals and need to be removed
SPH = SPH[prices.iloc[i].notnull()]
SPH = SPH[SPH]
# Only mark as swing point high if currently in uptrend or unidentified trend, otherwise ignore.
SPH = SPH[current_trend[SPH.index] != 'DOWN']
if not SPH.empty:
current_trend[SPH.index] = 'DOWN'
trend.loc[trend.index[i], SPH.index] = prices.iloc[i][SPH.index]
# Repeat for swing point lows.
SPL = ~(prices.iloc[(i + 1):(i + self.period)] < prices.iloc[i]).any()
SPL = SPL[prices.iloc[i].notnull()]
SPL = SPL[SPL]
SPL = SPL[current_trend[SPL.index] != 'UP']
if not SPL.empty:
current_trend[SPL.index] = 'UP'
trend.loc[trend.index[i], SPL.index] = prices.iloc[i][SPL.index]
self.trend = trend.interpolate()
# Analysis of Filter performance with trades
class FilterPerformance():
def __init__(self, trades):
self.trades = trades
self.trade_df = trades.as_dataframe()
self.result = None
def add(self, *args):
for filter in args:
self.trade_df = self.trades.add_to_df(self.trade_df, filter)
def summarise(self, filter_values, bins = 5):
'''
filter_values is the name of one of the filters already added to the
trade_df.
bins is an iterable of boundary points e.g. (-1, 0, 0.5, 1, etc...), or an integer of
the number of bins to produce (default 5). This is passed to pandas qcut.
'''
try:
values = self.trade_df[filter_values]
except KeyError as E:
print("{0} not yet assessed. Please add with 'add_to_df' and try again.".format(filter_values))
return None
if isinstance(bins, int):
type_bins = qcut(self.trade_df[filter_values], bins)
else:
type_bins = cut(self.trade_df[filter_values], bins)
mu = self.trade_df.groupby(type_bins).base_return.mean()
sd = self.trade_df.groupby(type_bins).base_return.std()
N = self.trade_df.groupby(type_bins).base_return.count()
self.result = {"mean" : mu, "std" : sd, "count" : N}
return result
def group(self, filter, bins):
'''
Provides a summary of filter performance for provided bins. Bins must be a sequence of boundary
points e.g. (-1, 0, 0.25...). Each filter type will be provided as a column.
'''
if isinstance(bins, int):
raise ValueError("Bins must be a sequence for filter grouping")
self.add_filter_to_df(filter)
mu = DataFrame()
sd = DataFrame()
N = DataFrame()
for type in filter.types:
type_bins = cut(self.trade_df[type], bins)
mu[type] = self.trade_df.groupby(type_bins).base_return.mean()
sd[type] = self.trade_df.groupby(type_bins).base_return.std()
N[type] = self.trade_df.groupby(type_bins).base_return.count()
self.result = {"mean" : mu, "std" : sd, "count" : N}
def compare(self, f1_name, f2_name, bins1 = 5, bins2 = 5):
'''
Provides a matrix comparing mean, std dev, and count for each combination of filter
values. Note only the first type of each filter is considered.
'''
if isinstance(bins1, int):
f1_bins = qcut(self.trade_df[f1_name], bins1)
else:
f1_bins = cut(self.trade_df[f1_name], bins1)
if isinstance(bins2, int):
f2_bins = qcut(self.trade_df[f2_name], bins2)
else:
f2_bins = cut(self.trade_df[f2_name], bins2)
grouping = self.trade_df.groupby([f1_bins, f2_bins]).base_return
mu = DataFrame(grouping.mean()).unstack()
sd = DataFrame(grouping.std()).unstack()
N = DataFrame(grouping.count()).unstack()
self.result = {"mean" : mu, "std" : sd, "count" : N}
def trailing_count(self):
removed = self.result['count'].shift(1)
removed.iloc[0] = 0
return self.result['count'].sum() - removed.cumsum()
def set_x_labels(self, ax):
x_labels = self.result['count'].index
ax.set_xticks(arange(len(x_labels)))
ax.set_xticklabels(x_labels)
plt.setp(ax.get_xticklabels(),
rotation=45,
ha="right",
rotation_mode="anchor",
fontsize = 8)
def plot_count(self, ax, **kwargs):
count = self.trailing_count()
ax2 = ax.twinx()
count.plot(ax = ax2, **kwargs)
ax2.set_ylabel('Count')
self.set_x_labels(ax2)
def plot_Sharpe(self, **kwargs):
Sharpe = self.result['mean'] / self.result['std']
if 'title' not in kwargs:
kwargs['title'] = self.result['mean'].index.name + ' Sharpe'
ax = Sharpe.plot(**kwargs)
ax.set_ylabel('Sharpe ratio')
def plot_mean(self, **kwargs):
mean_plus = self.result['mean'] + self.result['std']
mean_minus = self.result['mean'] - self.result['std']
ax = self.result['mean'].plot(**kwargs)
kwargs['style'] = '-'
mean_plus.plot(**kwargs)
mean_minus.plot(**kwargs)
ax.set_ylabel('Mean')
return ax
# Trade Summary Report
def summary_trade_volume(trades):
winners = trades.find(lambda trade: trade.base_return > 0)
losers = trades.find(lambda trade: trade.base_return < 0)
evens = trades.find(lambda trade: trade.base_return == 0)
trade_volume = Series(dtype = float)
trade_volume['Number of trades'] = trades.count
trade_volume['Percent winners'] = round(100 * (float(winners.count) / trades.count), 1)
trade_volume['Number winners'] = winners.count
trade_volume['Number losers'] = losers.count
trade_volume['Number even'] = evens.count
return trade_volume
def summary_returns(trades):
winners = trades.find(lambda trade: trade.base_return > 0)
losers = trades.find(lambda trade: trade.base_return < 0)
evens = trades.find(lambda trade: trade.base_return == 0)
returns = Series(dtype = float)
returns['Average return'] = round(100 * trades.mean_return, 2)
returns['Average return inc slippage'] = round(100 * trades.returns_slippage.mean(), 2)
returns['Median return'] = round(100 * trades.returns.median(), 2)
returns['Average winning return'] = round(100 * winners.mean_return, 2)
returns['Average losing return'] = round(100 * losers.mean_return, 2)
returns['Ratio average win to loss'] = round(winners.mean_return / abs(losers.mean_return), 2)
returns['Largest winner'] = round(100 * max(trades.returns), 2)
returns['Largest loser'] = round(100 * min(trades.returns), 2)
#returns['Sharpe by trade'] = round(trades.Sharpe, 2)
#returns['Sharpe by trade inc slippage'] = round(trades.returns_slippage.mean() / trades.returns_slippage.std(), 2)
returns['Sharpe annualised'] = round(trades.Sharpe_annual, 2)
returns['Sharpe annualised inc slippage'] = round(trades.Sharpe_annual_slippage, 2)
returns['Opt F'] = round(OptF(trades.returns), 2)
returns['G by trade'] = round(trades.G, 2)
returns['G annualised'] = round(trades.G_annual, 2)
# HACK geometric growth rate has assumed in the market 100%
returns['Geom. growth rate'] = round(GeometricGrowth(trades.returns, 250 / trades.durations.mean()), 2)
return returns
def summary_duration(trades):
winners = trades.find(lambda trade: trade.base_return > 0)
losers = trades.find(lambda trade: trade.base_return < 0)
evens = trades.find(lambda trade: trade.base_return == 0)
positive_runs, negative_runs = trades.consecutive_wins_losses()
duration = Series(dtype = float)
duration['Average duration'] = round(trades.durations.mean(), 2)
duration['Average duration winners'] = round(winners.durations.mean(), 2)
duration['Average duration losers'] = round(losers.durations.mean(), 2)
# Whilst consecutive winners/losers is interesting I'm not confident
# that this is being calculated by the TradeCollection in a meaningful way.
# duration['Max consecutive winners'] = positive_runs.max()
# duration['Max consecutive losers'] = negative_runs.max()
# duration['Avg consecutive winners'] = round(positive_runs.mean(), 2)
# duration['Avg consecutive losers'] = round(negative_runs.mean(), 2)
return duration
def summary_report(trades = None, **kwargs):
'''
Provides a summary of the trade statistics
'''
if trades is not None:
trade_volume = summary_trade_volume(trades)
returns = summary_returns(trades)
duration = summary_duration(trades)
return concat((trade_volume, returns, duration))
else:
df = DataFrame()
for label, trades in kwargs.items():
df[label] = summary_report(trades)
return df
def summary_by_period(trades, periods = 5):
entries = [T.entry for T in trades.as_list()]
entries.sort()
bin_size = round(trades.count / periods) + 1
bin_size = max(bin_size, 25)
start, end = (0, bin_size)
period_summary = DataFrame(dtype = float)
while start < trades.count:
end = min(end, trades.count)
start_date = entries[start]
end_date = entries[end - 1]
label = '{}:{}'.format(start_date.strftime('%b-%y'), end_date.strftime('%b-%y'))
subset = trades.find(lambda trade: start_date <= trade.entry <= end_date)
period_summary[label] = summary_report(subset)
start = end + 1
end += bin_size
return period_summary
class Sampler:
def __init__(self, N = 20, subset_fraction = 0.7):
self.N = N
self.subset_fraction = subset_fraction
self.clear()
def clear(self):
self.sampled_returns = DataFrame(dtype = float)
self.summary_report = DataFrame(dtype = float)
def check_robustness(self, returns):
'''
check_robustness takes a Returns object and samples at random
according to the Sampler parameters. The sampled returns are stored
for later processing in the `sampled_returns` attribute.
'''
tickers = returns.columns
ReturnsClass = returns.__class__
sample_size = round(len(tickers) * self.subset_fraction)
self.sampled_returns['selected'] = returns.combined().data
print('Running {} samples: '.format(self.N), end = '')
for n in range(self.N):
sample_tickers = list(random.choice(tickers, sample_size, replace = False))
subset = ReturnsClass(returns[sample_tickers])
self.sampled_returns[n] = subset.combined().data
print('.', end = '')
self.sampled_returns = AverageReturns(self.sampled_returns)
print('\ndone.')
def check_selection_skill(self, selected, base):
'''
check_select_skill attempts to assess the skill in a selection process
(e.g. a filter) vs a random selection of the same size from the base
collection.
selected - the TradeCollection produced by the selection process
base - the TradeCollection representing the pool of trades selected from
'''
self.summary_report['selected'] = summary_report(selected)
print('Running {} samples: '.format(self.N), end = '')
for n in range(self.N):
samples = random.choice(range(base.count), selected.count, replace = False)
# random.choice returns an array of numpy.int32, so we need to cast to int
samples = [int(s) for s in samples]
trade_subset = base.subset(samples)
self.summary_report[n] = summary_report(trade_subset)
print('.', end = '')
print('\ndone.')
def sample_hist(self, bins = 20):
'''
Using the summary dataframe from a robustness check and plots
the mean, std dev, and Sharpe.
'''
keys = ['mean', 'std. dev.', 'Sharpe']
mean = self.sampled_returns.annual_mean()
std = self.sampled_returns.volatility()
sharpe = self.sampled_returns.sharpe()
results = [mean, std, sharpe]
fig, axarr = plt.subplots(1, 3, sharey=True)
for i in range(3):
results[i][1:].hist(ax = axarr[i], bins = bins)
axarr[i].set_title(keys[i])
axarr[i].axvline(results[i]['selected'], color='k', linestyle='dashed', linewidth=1)
return (fig, axarr)
def skill_hist(self, metric, **kwargs):
values = self.summary_report.loc[metric]
# first value is the selected, so we remove from the histogram
ax = values[1:].hist(**kwargs)
ax.axvline(values['selected'], color='k', linestyle='dashed', linewidth=1)
return ax
# Market stability
# Performs cross-validation on several sub sets of the market
def cross_validate_trades(trades, N = 20, subset_fraction = 0.7):
tickers = trades.tickers
sample_size = round(len(tickers) * subset_fraction)
summary = DataFrame(dtype = float)
for n in range(N):
sample_tickers = list(random.choice(tickers, sample_size, replace = False))
trade_subset = trades.find(lambda T: T.ticker in sample_tickers)
summary[n] = summary_report(trade_subset)
result = DataFrame(dtype = float)
result['Base'] = summary_report(trades)
result['Mean'] = summary.mean(axis = 1)
result['Std'] = summary.std(axis = 1)
result['Median'] = summary.median(axis = 1)
result['Max'] = summary.max(axis = 1)
result['Min'] = summary.min(axis = 1)
return (result, summary)
def cross_validate_portfolio(portfolio, N = 20, subset_fraction = 0.7):
tickers = portfolio.strategy.market.tickers
sample_size = round(len(tickers) * subset_fraction)
summary = {
'market' : DataFrame(dtype = float),
'portfolio' : DataFrame(dtype = float)
}
for n in range(N):
sample_tickers = list(random.choice(tickers, sample_size, replace = False))
strat_subset = portfolio.strategy.subset(sample_tickers)
sub_portfolio = Portfolio(strat_subset, portfolio.starting_capital)
sub_portfolio.run()
summary['market'][n] = strat_subset.market_returns.combined().data
summary['portfolio'][n] = sub_portfolio.returns.data
summary['market']['base'] = portfolio.strategy.market_returns.combined().data
summary['portfolio']['base'] = portfolio.returns.data
summary['market'] = Returns(summary['market'])
summary['portfolio'] = Returns(summary['portfolio'])
return summary
def cross_validate_positions(strategy, N = 20, subset_fraction = 0.7):
trades = strategy.trades
original_positions = strategy.positions.copy()
tickers = trades.tickers
start_date = strategy.positions.start
base_returns = strategy.returns
sample_size = round(len(tickers) * subset_fraction)
for n in range(N):
sample_tickers = list(random.choice(tickers, sample_size, replace = False))
trade_subset = trades.find(lambda T: T.ticker in sample_tickers)
strategy.trades = trade_subset
strategy.positions.update_from_trades(trade_subset)
sub_returns = strategy.returns.plot(start = start_date, color = 'grey')
base_returns.plot(start = start_date, color = 'black')
strategy.market_returns.plot(start = start_date, color = 'red')
strategy.positions = original_positions
strategy.trades = trades
class ParameterFuzzer:
def __init__(self, strategy, base_parameters, processes = None):
self.strategy = strategy
if strategy.trades is None:
strategy.run()
self.base = summary_report(strategy.trades)
self.base_pars = base_parameters
if processes is None:
processes = cpu_count()
self.processes = processes
self._fuzzed_pars = None
self.results = None
self.summary = None
@property
def metrics(self):
return self.base.index
@property
def parameter_tuples(self):
# Note: below assumes last column in fuzzed_pars is 'Fuzz size'
return [tuple(pars) for pars in self.fuzzed_pars[self.fuzzed_pars.columns[:-1]].values]
@property
def fuzzed_strategies(self):
output = []
for pars in self.parameter_tuples:
strategy = self.strategy.copy()
strategy.signal_generator.update_param(pars)
output.append((pars, strategy))
return output
@property
def fuzzed_pars(self):
return self._fuzzed_pars
@fuzzed_pars.setter
def fuzzed_pars(self, values):
if isinstance(values, DataFrame):
if 'Fuzz size' not in values.columns:
# We assume the base parameters are the first row
values['Fuzz size'] = self.fuzz_size(values)
self._fuzzed_pars = values
elif isinstance(values, list):
# We assume we have a list of tuples
values = DataFrame(values)
values['Fuzz size'] = self.fuzz_size(values)
self._fuzzed_pars = values
else:
raise TypeError("values not recognised, must be DataFrame or list of tuples")
def fuzz(self):
'''
fuzz runs the strategy with the fuzzed_pars and collates the results
'''
pool = Pool(processes = self.processes)
self.results = pool.map(self.strategy_runner, self.fuzzed_strategies)
def strategy_runner(self, inputs):
'''
strategy_runner is designed to be run in parallel processing.
It runs the strategy with the provided parameters
inputs - a tuple (parameters, strategy)
'''
pars = inputs[0]
strategy = inputs[1]
try:
strategy.run()
except:
pass
return (pars, strategy)
def summarise(self):
if self.results is None:
self.fuzz()
pool = Pool(processes = self.processes)
summaries = pool.map(self.summary_runner, self.results)
summary_table = DataFrame(dict(summaries))
# TODO there's no guarantee that the results are in the same order as fuzz size
summary_table.loc['Fuzz size'] = self.fuzzed_pars['Fuzz size'].values
self.summary = summary_table
def summary_runner(self, result):
'''
summary_runner is designed to support parallel processing
It takes the strategy results and calculates the summary report
outputting a tuple of (label, summary_report).
The result input should contain the parameter tuple, and strategy.
'''
# result[0] will be the parameter tuple
# result[1] will be the strategy
label = ':'.join(['{:0.1f}'] * len(result[0])).format(*result[0])
return (label, summary_report(result[1].trades))
def fuzz_parameters(self, fuzz_range = 0.15, num_trials = 20):
'''
fuzz_parameters takes a base set of parameters and creates random variations
fuzz_range - the (approx) percent variation (+/-) to apply to the parameters
num_trials - the number of samples to generate
'''
parameter_labels = ['P' + str(n) for n in list(range(len(self.base_pars)))]
multiples = DataFrame((1 - fuzz_range) + random.rand(num_trials, len(self.base_pars)) * (2 * fuzz_range), columns = parameter_labels)
fuzzed_pars = DataFrame(0, index = list(range(num_trials)), columns = parameter_labels)
for par in parameter_labels:
fuzzed_pars[par] = self.base_pars[parameter_labels.index(par)] * multiples[par]
fuzzed_pars['Fuzz size'] = self.fuzz_size(fuzzed_pars, multiples)
self.fuzzed_pars = fuzzed_pars
def fuzz_size(self, fuzzed_pars, multiples = None):
'''
fuzz_size takes a dataframe of multiples (i.e. variation * base parameters)
and produces a metric of how far the sample is from the base parameter set.
If multiples are not provided they will be calculated from the provided fuzzed_pars
'''
if multiples is None:
multiples = fuzzed_pars / self.base_pars
fuzz_size = ((multiples - 1) ** 2).sum(axis = 'columns') ** 0.5
fuzz_magnitude = (fuzzed_pars ** 2).sum(axis = 'columns') - (Series(self.base_pars) ** 2).sum()
return (fuzz_size * sign(fuzz_magnitude)).round(2)
def summarise_metric(self, metric):
columns = self.summary.columns
# assumes headings are of form '##.#:##.#' e.g. '100.0:50.0'
df = DataFrame()
values = self.summary.loc[metric]
for c in columns:
row = int(c.split(".")[0])
col = float(c.split(":")[1]) / row
df.loc[row, col] = values[c]
return df
def plot_metric(self, metric, **kwargs):
df = self.summarise_metric(metric)
if 'title' not in kwargs:
kwargs['title'] = metric
ax = df.plot(**kwargs)
ax.legend()
ax.set_title(metric)
return ax
def plot(self, metric):
plt.scatter(self.summary.loc['Fuzz size'], self.summary.loc[metric])
plt.scatter(0, self.base.loc[metric], color = 'red')
def signal_coincidence(self, strategy):
'''
Assesses how often entry signals arrive and typical number
arriving together. The thinking being that you want signals to arrive
often, but separately.
Returns a tuple of ('% of days with entries', 'Average no. of coincident entries')
'''
event_df = strategy.events.as_dataframe()
events_per_date = event_df.date.value_counts()
percent_events = len(events_per_date) / len(strategy.market.index)
average_coincidence = events_per_date.mean()
return (percent_events, average_coincidence)
# Analysis of exit conditions
def test_trailing_stop(strat, stops):
result = DataFrame(columns = [0] + stops)
result[0] = summary_report(strat.trades)
for s in stops:
result[s] = summary_report(strat.trades.apply_exit_condition(TrailingStop(s)))
return result
def test_stop_loss(strat, stops):
result = DataFrame(columns = [0] + stops)
result[0] = summary_report(strat.trades)
for s in stops:
result[s] = summary_report(strat.trades.apply_exit_condition(StopLoss(s)))
return result
class PortfolioAnalyser:
"""
The PortfolioAnalyser as its name suggests analyses the performance of a Portfolio.
In particular it provides methods for assessing the robustness of the Portfolio
settings in terms of target number of positions, or starting capital.
"""
def __init__(self, portfolio):
if portfolio.trades is None:
portfolio.run_events()
self.portfolio = portfolio
self.subsets = {}
def clear(self):
self.subsets = {}
def vary_starting_capital(self, variations = [10000, 15000, 20000, 25000, 30000]):
for capital in variations:
variation = self.portfolio.copy()
variation.change_starting_capital(capital)
variation.run_events()
self.subsets["Starting_Cash_" + str(round(capital / 1000, 0)) + "k"] = variation
def vary_target_positions(self, variations = [3, 4, 5, 6, 7, 8, 9, 10]):
var = 1
for positions in variations:
print("Running variation", var, "of", len(variations))
var += 1
variation = self.portfolio.copy()
variation.sizing_strategy.update_target_positions(positions)
variation.run_events()
self.subsets["Target_Pos_" + str(positions)] = variation
def trades_dict(self):
trades = {}
trades["Base"] = self.portfolio.trades
for label, portfolio in self.subsets.items():
trades[label] = portfolio.trades
return trades
def totals_dataframe(self):
start = self.portfolio.trade_start_date
df = DataFrame()
df['Base'] = self.portfolio.summary[start:].Total
for label, portfolio in self.subsets.items():
raw_total = portfolio.summary[start:].Total
starting_ratio = (df.Base.iloc[0] / raw_total.iloc[0])
df[label] = raw_total * starting_ratio
return df
def plot_vs_base(self, **kwargs):
df = self.totals_dataframe()
df.plot(color = 'grey', **kwargs)
df.Base.plot(color = 'blue')
def plot_all(self, **kwargs):
df = self.totals_dataframe()
df.plot(**kwargs)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,132 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/rules/signal_rules.py |
from rules import PositionRuleElement, Position
class PositionFromDiscreteSignal(PositionRuleElement):
'''
Creates positions sized based on the signal level.
The position size is specified per level using keyword args.
If no size is specified it is assumed to be zero.
'''
def __init__(self, **kwargs):
self.level_sizes = kwargs
self.name = ", ".join(["{} [{}]".format(key, value) for key, value in self.level_sizes.items()])
def execute(self, strategy):
pos_data = strategy.get_empty_dataframe(fill_data = 0)
signal = strategy.signal.at(strategy.trade_entry)
for level, position_size in self.level_sizes.items():
pos_data[signal.data == level] = position_size
return Position(pos_data)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,133 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/measures/__init__.py |
from system.interfaces import SignalElement
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,134 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/data_types/events.py | """
The events module provides classes for dealing with events related to
position changes, e.g. entries, exits, or adjustments.
"""
import pandas as pd
from data_types import Collection, CollectionItem
from data_types.constants import TradeSelected
class EventCollection(Collection):
def __init__(self, events, tickers, index):
self.factory = EventFactory()
self.items = events
self.tickers = tickers
self.index = index
self._related_entries = {} # Dict of entries by ticker
self._related_exits = {} # Dict of exits by ticker
@staticmethod
def from_position_data(pos_data):
# Creation of events
delta = pos_data - pos_data.shift(1)
delta.iloc[0] = 0
# Add entries occuring on first day
non_zero_start = (pos_data.iloc[0] != 0)
if any(non_zero_start):
delta.iloc[0][non_zero_start] = pos_data.iloc[0][non_zero_start]
# Identify locations of events
event_keys = pd.DataFrame("-", index = pos_data.index, columns = pos_data.columns, dtype = str)
# Note adjustment goes first and then gets overwritten by entry and exit
event_keys[delta != 0] = AdjustmentEvent.Label
# TODO: Event creation logic will not work if switching from long to short position
# in one day (i.e. from positive to negative size), or vice versa.
event_keys[(delta != 0) & (delta == pos_data)] = EntryEvent.Label
event_keys[(delta != 0) & (pos_data == 0)] = ExitEvent.Label
factory = EventFactory()
events = []
tickers = event_keys.columns[pos_data.abs().sum() != 0]
for ticker in tickers:
ticker_events = event_keys[ticker]
ticker_deltas = delta[ticker]
event_dates = ticker_events.index[ticker_events != "-"]
event_types = ticker_events[event_dates]
event_sizes = ticker_deltas[event_dates]
event_data = list(zip(event_types, [ticker] * len(event_types), event_dates, event_sizes))
events.extend([factory.build(*event) for event in event_data])
return EventCollection(events, tickers, delta.index)
def copy_with(self, items):
return EventCollection(items, self.tickers, self.index)
@property
def last_date(self):
return self.index[-1]
def related_entries(self, ticker):
if ticker in self._related_entries:
return self._related_entries[ticker]
else:
related_entries = self.find(lambda e: e.Label == EntryEvent.Label and e.ticker == ticker)
self._related_entries[ticker] = related_entries
return related_entries
def related_exits(self, ticker):
if ticker in self._related_exits:
return self._related_exits[ticker]
else:
related_exits = self.find(lambda e: e.Label == ExitEvent.Label and e.ticker == ticker)
self._related_exits[ticker] = related_exits
return related_exits
def next_exit(self, entry, exits = None):
if exits is None:
# Find all exits related to the entry.ticker and after the entry.date
exits = self.related_exits(entry.ticker)
exits = [exit for exit in exits if exit.date > entry.date]
if len(exits):
# sort exits by date ascending (i.e. earliest first).
# and return the soonest
exits.sort(key = lambda e: e.date)
return exits[0]
else:
# create an exit event for on the last day
exit_date = self.last_date
return self.factory.build(ExitEvent.Label, entry.ticker, exit_date, -entry.size)
class EventFactory:
def __init__(self):
self.event = {
EntryEvent.Label : EntryEvent,
ExitEvent.Label : ExitEvent,
AdjustmentEvent.Label : AdjustmentEvent}
def build(self, type, ticker, date, size):
return self.event[type](ticker, date, size)
class TradeEvent(CollectionItem):
Label = "base event"
def __init__(self, ticker, date, size):
self.ticker = ticker
self.date = date
self.size = size
self.tuple_fields = ['ticker', 'Label', 'date', 'size']
def __str__(self):
first_line = '{0:^10}\n'.format(self.ticker)
second_line = 'Date: {0:10}\n'.format(str(self.date))
third_line = 'Size: {0:^10.1f}\n'.format(self.size)
return first_line + second_line + third_line
def update(self, positions):
positions.type.loc[self.ticker] = self.Label
positions.selected.loc[self.ticker] = TradeSelected.UNDECIDED
class EntryEvent(TradeEvent):
Label = "entry"
def update(self, positions):
positions.target_size.loc[self.ticker] = self.size
super().update(positions)
class ExitEvent(TradeEvent):
Label = "exit"
def update(self, positions):
positions.target_size.loc[self.ticker] = 0
super().update(positions)
class AdjustmentEvent(TradeEvent):
Label = "adjustment"
def update(self, positions):
positions.target_size.loc[self.ticker] += self.size
positions.type.loc[self.ticker] = self.Label
if positions.applied_size[self.ticker] != 0:
positions.selected.loc[self.ticker] = TradeSelected.UNDECIDED
else:
positions.selected.loc[self.ticker] = TradeSelected.NO
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,135 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/signals/carver_forecasters.py |
"""
These forecasters are inspired by the book Systematic Trading Development by Robert Carver.
They produce a normalised forecast based on the provided measurements. Forecasts range from
-20/20 with a target absolute mean of 10.
"""
from pandas import Panel
from system.interfaces import SignalElement
from data_types.signals import Signal
from measures.moving_averages import EMA
class EwmacFamily(SignalElement):
def __init__(self, vol_method, par_pairs):
self.vol = vol_method
self.par_pairs = par_pairs
def execute(self, strategy):
measures = {}
for pars in self.par_pairs:
name = "ewmac_{}_{}".format(max(pars), min(pars))
ewmac = EWMAC(EMA(max(pars)), EMA(min(pars)), self.vol)
measures[name] = ewmac(strategy).data
measures = Panel(measures)
return Signal(measures.mean(axis = 'items'), [-20, 20], measures)
class CarverForecast(SignalElement):
"""
Interface for creating normalised forecasts.
"""
def normalise(self, forecast):
"""
Normalises the forecast to be between -20/20 with absolute average of 10.
"""
overall_mean = forecast.abs().mean().mean()
adjustment = forecast.abs()
adjustment.iloc[0, :] = overall_mean
adjustment = adjustment.ewm(200).mean()
forecast = forecast * (10 / adjustment)
forecast[forecast > 20] = 20
forecast[forecast < -20] = -20
return forecast
class CarverForecastFamily(CarverForecast):
"""
Holds multiple forecasters and returns the mean forecast.
"""
def __init__(self, *args):
self.forecasters = args
def execute(self, strategy):
forecasts = {}
for forecaster in self.forecasters:
forecasts[forecaster.name] = forecaster(strategy).data
forecasts = Panel(forecasts)
mean_fcst = self.normalise(forecasts.mean(axis = 'items'))
return Signal(mean_fcst, [-20, 20], forecasts)
class EWMAC(CarverForecast):
"""
Exponentially Weighted Moving Average Crossover.
Creates a forecast based on the separation between two EMA measures.
The measures are normalised based on the volatility.
"""
def __init__(self, slow, fast, vol_method):
self.slow = slow
self.fast = fast
self.vol = vol_method
self.name = 'EWMAC_{}x{}'.format(fast, slow)
def execute(self, strategy):
prices = strategy.indicator_prices
slow = self.slow(prices)
fast = self.fast(prices)
vol = self.vol(prices)
forecast = self.normalise((fast - slow) / vol)
return Signal(forecast, [-20, 20], Panel({"Fast" : fast, "Slow" : slow, "Volatility" : vol}))
class PriceCrossover(CarverForecast):
"""
Calculates the forecast based on the difference between a set of base values (e.g. valuations),
and those of a measure derived from market prices.
"""
def __init__(self, base, measure, vol_method):
self.base = base.data
self.measure = measure
self.vol = vol_method
self.name = "_".join([base.name, measure.name])
def execute(self, strategy):
prices = strategy.indicator_prices
indicator = self.measure(prices)
vol = self.vol(prices)
forecast = self.normalise((self.base - indicator) / vol)
return Signal(forecast, [-20, 20], Panel({"Base" : self.base, "Ind" : indicator, "Volatility" : vol}))
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,136 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/data_types/signals.py | '''
Created on 13 Dec 2014
@author: Mark
'''
from system.interfaces import DataElement
class Signal(DataElement):
'''
Indicator represent possible trades for the strategy.
data should be a dataframe of True / False values for determine trade entries & exits
measures should be a panel of the measures used to derive the signals.
'''
def __init__(self, data, levels, measures):
self.data = data
self.measures = measures
self._levels = levels
@property
def levels(self):
if self._levels is None:
data = self.data.iloc[:, 0]
data = data[data.notnull()]
self._levels = set(data)
self._levels = sorted(self._levels)
return self._levels
@property
def index(self):
return self.data.index
@property
def columns(self):
return self.data.columns
def __getitem__(self, ticker):
return self.data[ticker]
def __len__(self):
return len(self.data)
def plot_measures(self, ticker, start = None, end = None, ax = None):
self.measures.minor_xs(ticker)[start:end].plot(ax = ax)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,137 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/rules/forecast_rules.py |
from copy import deepcopy
from numpy import sign
from rules import PositionRuleElement, Position
class CarterPositions(PositionRuleElement):
"""
Calculates positions based on the normalised forecast (-20 to 20),
and the current standard deviation of the instrument.
"""
def __init__(self, volatility_method, target_volatility, long_only = True):
self.volatility_method = volatility_method
self.target_vol = target_volatility
self.long_only = long_only
def execute(self, strategy):
forecasts = strategy.signal.at(strategy.trade_entry)
current_annual_volatility = self.volatility_method(strategy.indicator_prices)
volatility_scalar = self.target_vol / current_annual_volatility # This is the size we should hold for a forecast of 10
positions = (forecasts.data * volatility_scalar) / 10
if self.long_only:
positions[positions < 0] = 0
return Position(positions)
class OptimalFSign(PositionRuleElement):
'''
Returns positions sized according to the sign of the opt F calc (i.e. 1 or -1).
Requires a forecaster.
'''
def __init__(self, forecaster):
self.forecast = forecaster
def execute(self, strategy):
forecasts = self.forecast(strategy)
optimal_size = forecasts.optF()
positions = Position(sign(optimal_size))
positions.forecasts = forecasts
return positions
@property
def name(self):
return 'Default positions'
class OptimalPositions(PositionRuleElement):
def __init__(self, forecaster):
self.forecast = forecaster
def execute(self, strategy):
forecasts = self.forecast(strategy)
optimal_size = forecasts.optF()
positions = Position(optimal_size)
positions.forecasts = forecasts
return positions
@property
def name(self):
return 'Optimal F positions'
class SingleLargestF(PositionRuleElement):
def __init__(self, forecaster):
self.forecast = forecaster
def execute(self, strategy):
forecasts = self.forecast(strategy)
optimal_size = forecasts.optF()
result = deepcopy(optimal_size)
result[:] = 0
maximum_locations = optimal_size.abs().idxmax(axis = 1)
directions = sign(optimal_size)
for row, col in enumerate(maximum_locations):
if col not in result.columns:
pass
else:
result[col][row] = directions[col][row]
positions = Position(result)
positions.forecasts = forecasts
return positions
@property
def name(self):
return 'Single Largest F'
class HighestRankedFs(PositionRuleElement):
'''
Provides equal weighted positions of the 'n' highest ranked opt F forecasts.
'''
def __init__(self, forecaster, num_positions):
self.forecast = forecaster
self.num_positions = num_positions
self.name = '{} Highest Ranked Fs'.format(num_positions)
def execute(self, strategy):
forecasts = self.forecast(strategy)
optimal_size = forecasts.optF()
result = deepcopy(optimal_size)
result[:] = 0
ranks = abs(optimal_size).rank(axis = 1, ascending = False)
result[ranks <= self.num_positions] = 1
result *= sign(optimal_size)
result /= self.num_positions
positions = Position(result)
positions.forecasts = forecasts
return positions
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,138 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/measures/oscillators.py |
import pandas as pd
class BollingerBands(SignalElement):
def __init__(self, moving_average, vol_method, bands):
'''
Accepts moving average, and volatility calculation methods.
Uses these along with the provided bands parameter to provide
the measure.
bands should be a scalar multiple (e.g. 1.5 or 2) to be applied
to the volatility.
'''
self.moving_average = moving_average
self.vol_method = vol_method
self.bands = bands
@property
def name(self):
return "Bollinger.{0}.{1}x{2}".format(self.moving_average.name, self.bands, self.vol_method.name)
def update_param(self, new_params):
self.vol_period = new_params[0]
self.bands = new_params[1]
def __call__(self, prices):
'''
Returns a panel with the moving average, and
upper and lower volatility bands.
'''
moving_average = self.moving_average(prices)
volatility = self.vol_method(prices)
upper = moving_average + self.bands * volatility
lower = moving_average - self.bands * volatility
return pd.Panel.from_dict({"average" : moving_average,
"upper" : upper,
"lower" : lower})
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,139 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/data_types/trades.py |
from pandas import Series, DataFrame, qcut, cut, concat
from numpy import sign, log, exp, hstack, NaN
import matplotlib.pyplot as plt
from system.metrics import Drawdowns
from data_types import Collection, CollectionItem
from data_types.returns import Returns
from data_types.constants import TRADING_DAYS_PER_YEAR
class TradeCollection(Collection):
def __init__(self, items):
self.tickers = list(set([trade.ticker for trade in items]))
self.tickers.sort()
self.items = items
self.slippage = 0.011
self._returns = None
self._durations = None
self._daily_returns = None
def copy_with(self, items):
return TradeCollection(items)
def as_dataframe_with(self, *args):
'''
requires that args are a DataElement or a
dataframe with dates on index and columns of tickers.
'''
df = self.as_dataframe()
for arg in args:
self.add_to_df(df, arg)
return df
def add_to_df(self, df, data_element):
df[data_element.name] = NaN
for i in df.index:
ticker = df.loc[i].ticker
entry = df.loc[i].entry
try:
df.loc[i, data_element.name] = data_element.loc[entry, ticker]
except KeyError:
# Leave this entry blank.
pass
return df
@property
def returns(self):
if self._returns is None:
self._returns = Series([trade.weighted_return for trade in self.items])
return self._returns
@property
def returns_slippage(self):
return self.returns - self.slippage
@property
def durations(self):
if self._durations is None:
self._durations = Series([trade.duration for trade in self.items])
return self._durations
@property
def MAEs(self):
return [trade.MAE for trade in self.items]
@property
def MFEs(self):
return [trade.MFE for trade in self.items]
@property
def ETDs(self):
'''
End Trade Drawdown is defined as the difference between the MFE and the end return
'''
return [trade.MFE - trade.weighted_return for trade in self.items]
@property
def mean_return(self):
return self.returns.mean()
@property
def std_return(self):
return self.returns.std()
@property
def Sharpe(self):
try:
sharpe = self.mean_return / self.std_return
except ZeroDivisionError:
sharpe = NaN
return sharpe
@property
def Sharpe_annual(self):
returns = self.daily_returns
return Returns(returns).sharpe()
@property
def Sharpe_annual_slippage(self):
returns = self.daily_returns
total_slippage = self.count * self.slippage
slippage_per_day = total_slippage / len(returns)
returns = returns - slippage_per_day
return Returns(returns).sharpe()
@property
def G(self):
# Refer research note: EQ-2011-003
S_sqd = self.Sharpe ** 2
return ((1 + S_sqd) ** 2 - S_sqd) ** 0.5 - 1
@property
def G_annual(self):
S_sqd = self.Sharpe_annual ** 2
return ((1 + S_sqd) ** 2 - S_sqd) ** 0.5 - 1
@property
def max_duration(self):
return max(self.durations)
@property
def max_MAE(self):
return min(self.MAEs)
@property
def max_MFE(self):
return max(self.MFEs)
def consecutive_wins_losses(self):
'''
Calculates the positive and negative runs in the trade series.
'''
trade_df = self.as_dataframe().sort_values(by = 'exit')
win_loss = sign(trade_df.base_return)
# Create series which has just 1's and 0's
positive = Series(hstack(([0], ((win_loss > 0) * 1).values, [0])))
negative = Series(hstack(([0], ((win_loss < 0) * 1).values, [0])))
pos_starts = positive.where(positive.diff() > 0)
pos_starts = Series(pos_starts.dropna().index.tolist())
pos_ends = positive.where(positive.diff() < 0)
pos_ends = Series(pos_ends.dropna().index.tolist())
positive_runs = pos_ends - pos_starts
neg_starts = negative.where(negative.diff() > 0)
neg_starts = Series(neg_starts.dropna().index.tolist())
neg_ends = negative.where(negative.diff() < 0)
neg_ends = Series(neg_ends.dropna().index.tolist())
negative_runs = neg_ends - neg_starts
return (positive_runs, negative_runs)
def trade_frame(self, compacted = True, cumulative = True):
'''
Returns a dataframe of daily cumulative return for each trade.
Each row is a trade, and columns are days in trade.
'''
df = DataFrame(None, index = range(self.count), columns = range(self.max_duration), dtype = float)
for i, trade in enumerate(self.items):
df.loc[i] = trade.cumulative
if not cumulative:
df = ((df + 1).T / (df + 1).T.shift(1)).T - 1
if compacted and df.shape[1] > 10:
cols = [(11, 15), (16, 20), (21, 30), (31, 50), (51, 100), (101, 200)]
trade_df = df.loc[:, 1:10]
trade_df.columns = trade_df.columns.astype(str)
for bounds in cols:
if df.shape[1] <= bounds[1]:
label = '{}+'.format(bounds[0])
trade_df[label] = df.loc[:, bounds[0]:].mean(axis = 1)
break
else:
label = '{}-{}'.format(*bounds)
trade_df[label] = df.loc[:, bounds[0]:bounds[1]].mean(axis = 1)
final_bound = cols[-1][1]
if df.shape[1] > final_bound:
label = '{}+'.format(final_bound + 1)
trade_df[label] = df.loc[:, (final_bound + 1):].mean(axis = 1)
return trade_df
else:
return df
@property
def daily_returns(self):
'''
Returns an unsorted and unorderd list of daily returns for all trades.
Used for calculating daily or annualised statistics.
'''
if self._daily_returns is None:
daily = self.trade_frame(compacted = False, cumulative = False)
returns = []
for col in daily:
returns.extend(daily[col].tolist())
returns = Series(returns)
self._daily_returns = returns.dropna()
return self._daily_returns
def plot_ticker(self, ticker):
for trade in self[ticker]:
trade.plot_cumulative()
def hist(self, **kwargs):
# First remove NaNs
returns = self.returns.dropna()
plt.hist(returns, **kwargs)
def plot_MAE(self):
MAEs = self.MAEs
returns = self.returns
x_range = (min(MAEs) -0.05, 0.05)
y_range = (min(returns) - 0.05, max(returns) + 0.05)
plt.scatter(self.MAEs, self.returns)
plt.plot((0, 0), y_range, color = 'black')
plt.plot(x_range, (0, 0), color = 'black')
plt.plot((x_range[0], y_range[1]), (x_range[0], y_range[1]), color = 'red')
plt.xlabel('MAE')
plt.ylabel('Return')
plt.xlim(x_range)
plt.ylim(y_range)
def plot_MFE(self):
MFEs = self.MFEs
returns = self.returns
x_range = (-0.05, max(MFEs) + 0.05)
y_range = (min(returns) - 0.05, max(returns) + 0.05)
plt.scatter(MFEs, returns)
plt.plot((0, 0), y_range, color = 'black')
plt.plot(x_range, (0, 0), color = 'black')
plt.plot((x_range[0], y_range[1]), (x_range[0], y_range[1]), color = 'red')
plt.xlabel('MFE')
plt.ylabel('Return')
plt.xlim(x_range)
plt.ylim(y_range)
# TODO Instead of Trade holding prices, consider retaining a reference to the Market
class Trade(CollectionItem):
def __init__(self, ticker, entry_date, exit_date, prices, position_size = 1.0):
self.ticker = ticker
self.entry = entry_date
self.exit = exit_date
self.entry_price = self.get_price(entry_date, prices)
self.exit_price = self.get_price(exit_date, prices)
self._position_size = position_size
self.prices = prices[self.entry:self.exit]
daily_returns = (self.prices / self.prices.shift(1)) - 1
daily_returns[0] = (self.prices[0] / self.entry_price) - 1
self.base_returns = Returns(daily_returns)
self.calculate_weighted_returns()
# Fields to use when converting to a tuple
self.tuple_fields = ["ticker", "entry", "exit", "entry_price", "exit_price", "base_return", "duration", "annualised_return", "normalised_return"]
def __str__(self):
first_line = '{0:^23}\n'.format(self.ticker)
second_line = '{0:10} : {1:10} ({2} days)\n'.format(str(self.entry.date()), str(self.exit.date()), self.duration)
third_line = '{0:^10.2f} : {1:^10.2f} ({2:.1f} %)\n'.format(self.entry_price, self.exit_price, self.base_return * 100)
return first_line + second_line + third_line
def get_price(self, date, prices):
price = prices[date]
#if isnull(price):
# price = prices[prices.index >= date].dropna()[0]
return price
@property
def date(self):
'''
Supports searching the collection by date.
'''
return self.entry
@property
def duration(self):
"""
Duration is measured by days-in-market not calendar days
"""
return len(self.cumulative)
@property
def position_size(self):
return self._position_size
@position_size.setter
def position_size(self, size):
self._position_size = size
self.calculate_weighted_returns()
@property
def base_return(self):
return self.base_returns.final()
@property
def weighted_return(self):
return self.weighted_returns.final()
@property
def cumulative(self):
return Series(self.weighted_returns.cumulative().values)
@property
def annualised_return(self):
return self.weighted_returns.annualised()
@property
def normalised_return(self):
return self.weighted_returns.normalised()
@property
def MAE(self):
# Maximum adverse excursion
return min(self.cumulative)
@property
def MFE(self):
# Maximum favourable excursion
return max(self.cumulative)
@property
def ETD(self):
# End trade drawdown
return (1 + self.base_return) / (1 + self.MFE) - 1
def drawdowns(self):
# Note we want to return drawdowns with integer index, not
# date indexed
return self.weighted_returns.int_indexed().drawdowns()
def calculate_weighted_returns(self):
# Short returns are the inverse of daily returns, hence the exponent to the sign of position size.
base_returns = self.base_returns.data
position_size = self.position_size
if isinstance(position_size, int) or isinstance(position_size, float):
weighted_returns = (1 + (base_returns * abs(position_size))) ** sign(self.position_size) - 1
elif isinstance(position_size, Series):
position_size = position_size.shift(1)[self.entry:self.exit]
weighted_returns = (1 + (base_returns * abs(position_size))) ** sign(position_size[1]) - 1
else:
weighted_returns = None
self.weighted_returns = Returns(weighted_returns)
# Trade modifiers
# TODO - revise_entry and revise_exit could be parameter setters
def revise_entry(self, entry_day):
'''
revise_entry accepts an entry_day (integer), and readjusts the trade to
start on the new (later) entry day.
'''
if self.duration > entry_day:
new_entry = self.base_returns.index[entry_day]
revised = Trade(self.ticker, new_entry, self.exit, self.prices, self.position_size)
return revised
else:
return None
def revise_exit(self, exit_day):
'''
revise_exit accepts an exit_day (integer), and readjusts the trade to
end on the new exit day.
'''
if exit_day > 0:
new_exit = self.base_returns.index[exit_day]
revised = Trade(self.ticker, self.entry, new_exit, self.prices, self.position_size)
return revised
else:
return None
# Plotting
def plot_result(self):
_, axarr = plt.subplots(2, 1, sharex = True)
axarr[0].set_ylabel('Return')
axarr[1].set_ylabel('Drawdown')
axarr[1].set_xlabel('Days in trade')
self.cumulative.plot(ax = axarr[0])
self.plot_highwater(ax = axarr[0], color = 'red')
self.plot_drawdowns(ax = axarr[1])
def plot_drawdowns(self, **kwargs):
self.drawdowns().Drawdown.plot(**kwargs)
def plot_highwater(self, **kwargs):
self.drawdowns().Highwater.plot(**kwargs)
def trade_frame(positions, returns, prices):
pass
class TradeGroups:
'''
Derivative of Positions. Attempts to keep all data as DataFrame's
using groupby to produce by-trade statistics.
'''
def __init__(self, pos_data):
self.positions = pos_data
self._trade_numbers = None
def clear_cache(self):
self._trade_numbers = None
def get_trade_numbers(self):
if self._trade_numbers is None:
# To get the trade numbers we produce a rolling
# count of trades starting with the left most column (ticker)
# and progressing through the dataframe.
pos_data = self.positions
# Find the entries for each position
delta = pos_data - pos_data.shift(1)
delta.iloc[0] = 0
entries = (delta != 0) & (delta == pos_data)
# Increment successive entries by 1
col_counts = (1 * entries).cumsum() * sign(pos_data)
# We have trade counts starting from one in each column
# Need to step each column up by the count from the previous
col_step = col_counts.max().cumsum().shift(1)
col_step.iloc[0] = 0
# Before we add the step, need to replace zeroes with NaN
# so that the zeroes don't get incremented
col_counts[col_counts == 0] = NaN
col_counts += col_step
self._trade_numbers = col_counts.stack()
return self._trade_numbers
def get_groups(self, data):
'''
Returns a groupby object of the supplied dataframe
Note: We need to stack the data into a Series to get a
continuous trade count, otherwise it would be by column.
'''
# Note: stacking the dataframe will produce a multi-index
# series. First level of index is dates, second level is ticker.
data = data.stack()
trades = self.get_trade_numbers()
return data.groupby(trades)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,140 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/system/interfaces.py |
"""
interfaces contains the basic structures for strategy building blocks. Most of the classes in this module
are not intended to be used directly, but to be inherited from for customised functionality.
The interfaces are broken into two broad categories:
1. The interfaces for data structures (e.g. results of calculations) which predominately handle the
correct alignment in time with other calculated data.
2. The interfaces for calculation methods, which can be thought of to be the mappings between data
types. These generally will need to be callable, and will accept a strategy as input (for access
to the contained data).
"""
from copy import copy, deepcopy
# DATA CONTAINER TYPES
class DataElement:
'''
DataElements represent the data objects used by Strategy.
Each DataElement is assumed to have a (DataFrame) field called data.
DataElements also control the appropriate lagging of data to align with other calculation periods.
When lagged the DataElement returns a copy of itself, and the current applied lag.
Calculation timing represents the timing for when the data is calculated and may be a single value,
e.g. ["decision", "entry", "exit", "open", "close"], or a twin value which represents the calculations
occur over some span of time, e.g. for returns which have timing ["entry", "exit"]
'''
def shift(self, lag):
lagged = self.copy()
lagged.data = self.data.copy() # Note: deepcopy doesn't seem to copy the dataframe properly; hence this line.
lagged.data = lagged.data.shift(lag)
lagged.lag += lag
return lagged
def at(self, timing):
'''
'at' returns a lagged version of the data appropriate for the timing.
'timing' is a parameter of the strategy e.g. strategy.decision, strategy.entry...
This will expose a method called 'get_lag' that determines the lag from this
object's timing ["decision", "entry", "exit", "open", "close"].
'''
lag = self.get_lag(timing)
return self.shift(lag)
def align_with(self, other):
'''
'align_with' returns a lagged version of the data so that it is aligned with the
timing of the supplied other data object. This ensures that this data will be available at the
time creation of the other data object would have started.
The logic for the overall lag calculated in align_with is as follows:
- total lag = alignment lag + other lag
- alignment lag = lag between this data calc end to the other data calc start
- other lag = the lag already applied to the other data.
'''
alignment_lag = self.get_lag(other.calculation_timing[0])
total_lag = alignment_lag + other.lag
return self.shift(total_lag)
def get_lag(self, target_timing):
'''
Calculate the lag between the completion of calculating this data object and the requested timing.
'''
return target_timing.get_lag(self.calculation_timing[-1])
@property
def index(self):
return self.data.index
@property
def tickers(self):
return self.data.columns
# Reproducing DataFrame methods
def __getitem__(self, key):
return self.data[key]
def head(self, *args, **kwargs):
return self.data.head(*args, **kwargs)
@property
def loc(self):
return self.data.loc
@property
def iloc(self):
return self.data.iloc
def copy(self):
return deepcopy(self)
def diff(self, *args, **kwargs):
return self.data.diff(*args, **kwargs)
def ewm(self, *args, **kwargs):
return self.data.ewm(*args, **kwargs)
def rolling(self, *args, **kwargs):
return self.data.rolling(*args, **kwargs)
def ffill(self, *args, **kwargs):
return self.data.ffill(*args, **kwargs)
class IndexerFactory:
def __init__(self, trade_timing, ind_timing):
if trade_timing not in ["O", "C"]:
raise ValueError("Trade timing must be one of: 'O', 'C'.")
self.trade_timing = trade_timing
if ind_timing not in ["O", "C"]:
raise ValueError("Ind_timing must be one of: 'O', 'C'")
self.ind_timing = ind_timing
self.timing_map = {"decision" : self.ind_timing,
"trade" : self.trade_timing,
"open" : "O",
"close" : "C"}
def __call__(self, target):
timing = target.lower()
if timing not in self.timing_map.keys():
raise ValueError("{0}\nTiming must be one of: {1}".format(self.end, ", ".join(self.timing_map.keys())))
return Indexer(self.timing_map, target)
class Indexer:
"""
Indexer is responsible for determining the amount of lag to add to
a DataElement based on the DataElement calculated timing and the
target timing.
"""
def __init__(self, timing_map, target):
self.timing_map = timing_map
self.end = target
@property
def target(self):
return self.convert_timing(self.end)
def get_lag(self, start):
start = self.convert_timing(start)
end = self.convert_timing(self.end)
if "OC" in start + end:
lag = 0
else:
lag = 1
return lag
def convert_timing(self, timing):
timing = timing.lower()
if timing not in self.timing_map.keys():
raise ValueError("{0}\nTiming must be one of: {1}".format(self.end, ", ".join(self.timing_map.keys())))
return self.timing_map[timing]
# CALCULATION TYPES
class StrategyElement:
'''
The StrategyElement class provides the basic interface for those objects which
perform calculations based on the strategy data. e.g. to create signals.
It defines the base functionality required, as well as handling the details of
assigning the ag values.
'''
def __call__(self, strategy):
result = self.execute(strategy)
result.calculation_timing = self.calculation_timing
result.lag = self.starting_lag()
return result
def execute(self, strategy):
raise NotImplementedError("Strategy Element must define 'execute'")
def starting_lag(self):
return 0
@property
def typename(self):
"""
Returns the class name.
Assumes type returns "<class '[Parents].[Name]'>"
"""
return str(type(self)).split(".")[-1][:-2]
class SignalElement(StrategyElement):
@property
def calculation_timing(self):
return ["decision"]
class PositionRuleElement(StrategyElement):
@property
def calculation_timing(self):
return ["entry"]
class FilterInterface:
def __call__(self, strategy):
return strategy.trades.find(self.accepted_trade)
def get(self, date, ticker):
try:
value = self.values.loc[date, ticker]
except KeyError:
value = None
return value
def accepted_trade(self, trade):
'''
Each filter must implement a method accepted_trade which accepts a trade object
and returns a boolean to determine if the trade should be kept.
'''
raise NotImplementedError("Filter must implement 'accepted_trade' method")
def plot(self, ticker, start, end, ax):
raise NotImplementedError("Filter must implement 'plot' method")
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,141 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/rules/__init__.py |
from system.interfaces import PositionRuleElement
from data_types.positions import Position | {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,142 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/system/core.py | '''
Created on 21 Dec 2014
@author: Mark
'''
import matplotlib.pyplot as plt
import numpy as np
from pandas import DateOffset, DataFrame, Series
from system.interfaces import IndexerFactory
from data_types.trades import TradeCollection
from data_types.positions import Position
from data_types.returns import Returns
from data_types.constants import TradeSelected
from data_types.events import ExitEvent
from measures.volatility import StdDevEMA
class Strategy:
'''
Strategy manages creation of positions and trades for a given
strategy idea and plotting of results.
'''
def __init__(self, trade_timing, ind_timing):
self.name = None
self.market = None
# Calculation results
self.signal = None
self.positions = None
# Component methods
self.signal_generator = None
self.position_rules = None
self.filters = []
# Timing parameters
self.indexer = IndexerFactory(trade_timing, ind_timing)
self.decision = self.indexer("decision")
self.trade_entry = self.indexer("trade")
self.open = self.indexer("open")
self.close = self.indexer("close")
def __str__(self):
if self.name is not None:
first_line = '{}\n'.format(self.name)
else:
first_line = ''
second_line = 'Signal:\t{}\n'.format(self.signal_generator.name)
third_line = 'Position Rule:\t{}\n'.format(self.position_rules.name)
if len(self.filters) > 0:
fourth_line = 'Filter:\t{}\n'.format('\n'.join([f.name for f in self.filters]))
else:
fourth_line = 'No filter specified.\n'
return first_line + second_line + third_line + fourth_line
@property
def trade_timing(self):
'''
Return the timing (open, close) for when trades occur.
'''
return self.indexer.trade_timing
@property
def ind_timing(self):
'''
Return the timing (open, close) for when calculations to determine
actions are performed.
'''
return self.indexer.ind_timing
@property
def trades(self):
return self.positions.trades
@trades.setter
def trades(self, trades):
self.positions.update_from_trades(trades)
@property
def events(self):
return self.positions.events
@property
def prices(self):
return self.market
@property
def indicator_prices(self):
return self.prices.at(self.decision)
@property
def trade_prices(self):
return self.prices.at(self.trade_entry)
def copy(self):
strat_copy = Strategy(self.trade_timing, self.ind_timing)
strat_copy.market = self.market
strat_copy.signal_generator = self.signal_generator
strat_copy.position_rules = self.position_rules
strat_copy.filters = self.filters
return strat_copy
def run(self):
'''
Run the strategy with the current settings.
This will create the signals, trades, and base positions.
Any filters specified will be applied also.
'''
self.generate_signals()
self.apply_rules()
self.apply_filters()
self.rebase()
def rerun(self):
'''
Run the strategy by first clearing any previous calculated data.
Typically used when the strategy has already been run, but changes have been
made to the settings
'''
self.reset()
self.run()
def reset(self):
'''
Clears all current results from the Strategy.
'''
self.signal = None
self.positions = None
def rebase(self):
'''
rebase makes a copy of the positions (and trades) as base reference.
Any further changes to these can then be compared with the base result.
'''
self.base_positions = self.positions.copy()
def generate_signals(self):
self.signal = self.signal_generator(self)
def apply_rules(self):
self.positions = self.position_rules(self)
self.positions.trades = self.positions.create_trades(self)
def apply_filters(self):
if len(self.filters) == 0:
return
for filter in self.filters:
self.trades = filter(self)
def apply_filter(self, filter):
'''
Add a filter to a strategy which has already been run.
This will run the filter, and add it to the list of
existing filters for the strategy.
'''
self.filters += [filter]
self.trades = filter(self)
def apply_exit_condition(self, condition):
'''
Accepts an exit condition object e.g. StopLoss, which is
passed to the Trade Collection to be applied to each trade.
'''
self.trades = self.trades.apply(condition)
def get_empty_dataframe(self, fill_data = None):
'''
Returns a dataframe with the same index as the market, and with
columns equal to the tickers in the market.
'''
return self.market.get_empty_dataframe(fill_data)
def subset(self, subset_tickers):
'''
subset supports cross validation across market constituents.
The idea being multiple subsets are taken and performance is
compared to determine sensitivity of the strategy to the tickers
included in the market.
'''
new_strat = Strategy(self.trade_timing, self.ind_timing)
new_strat.market = self.market.subset(subset_tickers)
new_strat.positions = self.positions.subset(subset_tickers)
return new_strat
def buy_and_hold_trades(self):
'''
Return the TradeCollection assuming all tickers are bought and held
for the duration of the test period.
'''
signal_data = self.get_empty_dataframe()
signal_data[:] = 1
return Position(signal_data).create_trades(self)
@property
def market_returns(self):
'''
Gets the dataframe of market returns relevant for the trade timing.
'''
return self.market.at(self.trade_entry).returns()
@property
def returns(self):
'''
Gets the dataframe of strategy returns, i.e. positions applied to the market
returns.
'''
return self.positions.applied_to(self.market_returns)
@property
def long_returns(self):
'''
Gets the strategy returns for long trades only.
'''
positions = self.positions.long_only()
return positions.applied_to(self.market_returns)
@property
def short_returns(self):
'''
Gets the strategy returns for short trades only.
'''
positions = self.positions.short_only()
return positions.applied_to(self.market_returns)
# Reporting methods
def plot_measures(self, ticker, start, end, ax):
self.signal.plot_measures(ticker, start, end, ax)
def plot_result(self, long_only = False, short_only = False, color = "blue", **kwargs):
'''
Plots the returns of the strategy vs the market returns.
'''
if long_only:
returns = self.long_returns
elif short_only:
returns = self.short_returns
else:
returns = self.returns
start = self.positions.start
returns.plot(start = start, color = color, label = "Strategy", **kwargs)
self.market_returns.plot(start = start, color = "black", label = "Market")
plt.legend(loc = "upper left")
def plot_trade(self, key):
'''
Given the key of a trade (trade number, or ticker), this will produce a candlestick plt,
along with the measures for the trade, entry, and exit.
'''
trades = self.trades[key]
if isinstance(trades, list):
if len(trades) == 0:
print('No trades for {}'.format(key))
return
entries, exits = zip(*[(T.entry, T.exit) for T in trades])
entries = list(entries)
exits = list(exits)
ticker = key
else:
entries = [trades.entry]
exits = [trades.exit]
ticker = trades.ticker
start = min(entries) - DateOffset(10)
end = max(exits) + DateOffset(10)
_, ax = self.market.candlestick(ticker, start, end)
self.plot_measures(ticker, start, end, ax)
for filter in self.filters:
filter.plot(ticker, start, end, ax)
lo_entry = self.market.low[ticker][entries] * 0.95
hi_exit = self.market.high[ticker][exits] * 1.05
plt.scatter(entries, lo_entry, marker = '^', color = 'green')
plt.scatter(exits, hi_exit, marker = 'v', color = 'red')
plt.title(ticker)
# TODO Clean up unused Portfolio attributes and methods
# TODO consider merging Transactions and PositionChanges
# TODO find a better way to update Portfolio positions from PositionChanges
class Portfolio:
'''
The portfolio class manages cash and stock positions, as well as rules
regarding the size of positions to hold and rebalancing.
The portfolio contains a list of trade conditions. Each one is a function which
accepts the portfolio, and trade, and returns a boolean. Each one of the conditions
must return True for the trade to be accepted.
'''
def __init__(self, strategy, starting_cash):
self.strategy = strategy
self.share_holdings = self.strategy.get_empty_dataframe() # Number of shares
self.dollar_holdings = self.strategy.get_empty_dataframe(0) # Dollar value of positions
self.positions = self.strategy.get_empty_dataframe() # Nominal positions
self.position_states = PositionState(self.share_holdings.columns, starting_cash)
self.summary = DataFrame(0, index = self.share_holdings.index, columns = ["Cash", "Holdings", "Total"])
self.summary["Cash"] = starting_cash
self.costs = DataFrame(0, index = self.share_holdings.index, columns = ["Commissions", "Slippage", "Total"])
self.rebalancing_strategy = NoRebalancing()
self.sizing_strategy = SizingStrategy()
volatilities = StdDevEMA(40)(strategy.indicator_prices.at(strategy.trade_entry))
self.sizing_strategy.multipliers.append(VolatilityMultiplier(0.2, volatilities))
self.position_checks = [PositionNaCheck(), PositionCostThreshold(0.02)]
self.trades = None
self.targets = strategy.positions.data.copy()
def copy(self):
port_copy = Portfolio(self.strategy, self.starting_capital)
port_copy.position_checks = self.position_checks
port_copy.sizing_strategy = self.sizing_strategy
return port_copy
def reset(self):
'''
reset - Sets the Portfolio back to its starting condition ready to be run again.
'''
starting_cash = self.starting_capital
self.share_holdings = self.strategy.get_empty_dataframe() # Number of shares
self.dollar_holdings = self.strategy.get_empty_dataframe(0) # Dollar value of positions
self.positions = self.strategy.get_empty_dataframe() # Nominal positions
self.position_states = PositionState(self.share_holdings.columns, starting_cash)
self.summary = DataFrame(0, index = self.share_holdings.index, columns = ["Cash", "Holdings", "Total"])
self.summary["Cash"] = starting_cash
self.costs = DataFrame(0, index = self.share_holdings.index, columns = ["Commissions", "Slippage", "Total"])
self.trades = None
def change_starting_capital(self, starting_cash):
self.reset()
self.summary["Cash"] = starting_cash
def run(self, position_switching = False):
'''
This approach gets the series of events from the strategy, and the portfolio can
also add its own events (e.g. rebalancing). Portfolio events are always applied
after the Strategy events (i.e. can be used to overrule Strategy events).
The events are turned into Transactions for execution.
'''
trading_days = self.share_holdings.index
trade_prices = self.strategy.trade_prices
#progress = ProgressBar(total = len(trading_days))
for date in trading_days:
strategy_events = self.strategy.events[date]
# TODO rebalancing strategy needs to add events to the queue.
#if date in self.rebalancing_strategy.rebalance_dates:
# self.rebalancing_strategy(strategy_events)
if not len(strategy_events):
continue
self.position_states.update(self, date)
self.position_states.apply(strategy_events)
self.position_states.estimate_transactions()
self.process_exits(self.position_states)
self.check_positions(self.position_states)
self.select(self.position_states)
self.apply(self.position_states)
#progress.print(trading_days.get_loc(date))
self.positions = Position(self.positions.ffill().fillna(0))
self.trades = self.positions.create_trades(self.strategy)
self.share_holdings = self.share_holdings.ffill().fillna(0)
self.dollar_holdings = trade_prices.data * self.share_holdings
self.dollar_holdings = self.dollar_holdings.ffill()
self.summary["Holdings"] = self.dollar_holdings.sum(axis = 1)
self.summary["Total"] = self.cash + self.holdings_total
self.costs["Total"] = self.costs["Commissions"] + self.costs["Slippage"]
def process_exits(self, positions):
positions.select_exits()
self.positions.loc[positions.date, positions.exit_mask] = 0
def check_positions(self, positions):
for check in self.position_checks:
check(self, positions)
# TODO select needs to be a separate plug-in strategy
def select(self, positions):
# First apply all the trades which will reduce positions (i.e. increase cash)
undecided_sells = ((positions.undecided_mask) &
(positions.target_size < positions.applied_size))
positions.select(undecided_sells)
# Select buys which will cost the least slippage + commissions as long
# as there is cash available.
perct_cost = positions.cost / positions.trade_size
while True:
undecided = positions.undecided_mask
if not any(undecided):
break
lowest_cost = perct_cost[undecided].idxmin()
if positions.trade_size[lowest_cost] >= (positions.available_cash()):
positions.deselect(lowest_cost)
else:
positions.select(lowest_cost)
self.positions.loc[positions.date, lowest_cost] = positions.target_size[lowest_cost]
positions.finalise()
def dollar_ratio(self, date):
return self.sizing_strategy(self, date)
def apply(self, positions):
date = positions.date
self.cash.loc[date:] -= positions.txns.total_cost
self.costs.loc[date:, "Commissions"] += positions.txns.total_commissions
self.costs.loc[date:, "Slippage"] += positions.txns.total_slippage
self.share_holdings.loc[date] = positions.current_shares
@property
def starting_capital(self):
return self.cash.iloc[0]
@property
def cash(self):
'''
Returns the series of dollar value of cash held over time.
'''
return self.summary.loc[:, "Cash"]
@property
def holdings_total(self):
'''
Returns the series of dollar value of all holdings (excluding cash).
'''
return self.summary["Holdings"]
@property
def value(self):
'''
Returns the series of total dollar value of the portfolio
'''
return self.summary["Total"]
@property
def current_value(self):
'''
Returns the current value of the portfolio
Typically used while the portfolio is performing calculations.
'''
return self.position_states.current_dollars.sum() + self.position_states.current_cash
@property
def value_ex_cost(self):
'''
Returns the series of total dollar value assuming zero costs
'''
return self.value + self.costs["Total"]
@property
def returns(self):
'''
Returns the daily returns for the portfolio
'''
returns = self.value / self.value.shift(1) - 1
returns[0] = 0
return Returns(returns)
@property
def returns_ex_cost(self):
'''
Returns the daily returns for the portfolio assuming zero costs
'''
returns = self.value_ex_cost / self.value_ex_cost.shift(1) - 1
returns[0] = 0
return Returns(returns)
@property
def cumulative_returns(self):
'''
Returns the cumulative returns series for the portfolio
'''
return self.returns.cumulative()
@property
def drawdowns(self):
'''
Returns the calculated drawdowns and highwater series for the portfolio returns.
'''
return self.returns.drawdowns()
def max_position_percent(self):
pct_holdings = self.dollar_holdings.divide(self.value, axis = 0)
return pct_holdings.max(axis = 1)
@property
def trade_start_date(self):
return self.dollar_holdings.index[self.dollar_holdings.sum(axis = 1) > 0][0]
def plot_result(self, dd_ylim = None, rets_ylim = None):
'''
Plots the portfolio returns and drawdowns vs the market.
'''
start = self.trade_start_date
_, axarr = plt.subplots(2, 1, sharex = True)
axarr[0].set_ylabel('Return')
axarr[1].set_ylabel('Drawdown')
axarr[1].set_xlabel('Days in trade')
self.cumulative_returns[start:].plot(ax = axarr[0], ylim = rets_ylim)
self.returns_ex_cost.cumulative()[start:].plot(ax = axarr[0], color = 'cyan', linewidth = 0.5)
dd = self.drawdowns
dd.Highwater[start:].plot(ax = axarr[0], color = 'red')
dd.Drawdown[start:].plot(ax = axarr[1], ylim = dd_ylim)
mkt_returns = self.strategy.market_returns
mkt_dd = mkt_returns.drawdowns().Drawdown
mkt_returns.plot(start = start, ax = axarr[0], color = 'black')
mkt_dd[start:].plot(ax = axarr[1], color = 'black')
return axarr
class PositionState:
def __init__(self, tickers, current_cash):
self.current_cash = current_cash
self.current_shares = Series(0, index = tickers)
self.applied_size = Series(0, index = tickers)
self.target_size = Series(index = tickers, dtype = float)
self.selected = Series(TradeSelected.NO, index = tickers)
self.type = Series("-", index = tickers)
self.pending_events = [] # events which were not actioned (e.g. due to missing price data)
def update(self, portfolio, date):
# Get the prices from yesterday's indicator timing.
self.prices = portfolio.strategy.indicator_prices.at(portfolio.strategy.trade_entry).loc[date]
self.current_dollars = self.current_shares * self.prices
self.dollar_ratio = portfolio.dollar_ratio(date)
self.current_nominal = self.current_dollars / self.dollar_ratio
self.target_size = Series(index = self.current_shares.index)
self.selected = Series(TradeSelected.NO, index = self.current_shares.index)
self.type = Series("-", index = self.current_shares.index)
self.date = date
def finalise(self):
self.current_shares += self.txns.num_shares
self.current_cash -= self.txns.total_cost
# applied_size represents the nominal size that the portfolio has moved towards
# this may be different from the target_size if, for example, an adjustment or entry wasn't
# acted upon.
self.applied_size.loc[self.selected_mask] = self.target_size[self.selected_mask]
@property
def exit_mask(self):
return self.type == ExitEvent.Label
@property
def undecided_mask(self):
return self.selected == TradeSelected.UNDECIDED
@property
def selected_mask(self):
return self.selected == TradeSelected.YES
def apply(self, events):
self.pending_events.extend(events)
all_events = self.pending_events
self.pending_events = []
for event in all_events:
if np.isnan(self.prices[event.ticker]):
self.pending_events.append(event)
else:
event.update(self)
def apply_rebalancing(self, tickers = None):
if tickers is None:
# All tickers which have not been touched by an event are rebalanced.
tickers = np.isnan(self.target_size)
self.target_size.loc[tickers] = self.applied_size[tickers]
#TODO below should use a RebalanceEvent.Label not string.
self.type.loc[tickers] = "rebalance"
def estimate_transactions(self):
num_shares = (self.dollar_ratio * self.target_size / self.prices)
num_shares -= self.current_shares
num_shares[np.isnan(num_shares)] = 0
self.txns = Transactions(num_shares.astype(int), self.prices, self.date)
@property
def cost(self):
return self.txns.slippage + self.txns.commissions
@property
def trade_size(self):
return self.txns.dollar_positions
@property
def num_shares(self):
return self.txns.num_shares
def select(self, tickers):
self.selected.loc[tickers] = TradeSelected.YES
def deselect(self, tickers):
self.selected.loc[tickers] = TradeSelected.NO
self.trade_size.loc[tickers] = 0
self.num_shares.loc[tickers] = 0
self.cost.loc[tickers] = 0
def select_exits(self):
self.select(self.exit_mask)
def available_cash(self):
return self.current_cash - self.total_cost()
def total_cost(self):
return self.trade_size[self.selected_mask].sum() + self.cost[self.selected_mask].sum()
class SizingStrategy:
'''
The SizingStrategy is responsible for providing the dollar ratio to turn
the strategy's nominal size into the size in dollars.
There are basically two components:
1. The base dollar size - this is basically determined by the target
number of positions to be held (i.e. capital / number of positions)
2. Multipliers - there can be an arbitrary number of multipliers which
modify the size for each instrument (e.g. for volatility scaling)
The strategy aims to increase the number of positions as capital allows.
The rate at which positions are added is dictated by the
diversifier parameter which must be in the range 0-1. A diversifier close
to zero will hold the minimum number of positions possible while still
satisfying the maximum size constraint (as a proportion of total capital).
This would therefore act as targeting a fixed number of positions (1 / max_size).
A diversifier close to 1 will increase the number of positions as soon as
the minimum position size constraint can be met (as a dollar size).
'''
def __init__(self, diversifier = 0.5, min_size = 2500, max_size = 0.3):
self.diversifier = diversifier
self.min_size = min_size
self.max_size = max_size
self.multipliers = []
def __call__(self, portfolio, date):
dollar_ratio = self.dollar_ratio(portfolio, date)
for multiplier in self.multipliers:
dollar_ratio *= multiplier(portfolio, date)
return dollar_ratio
def dollar_ratio(self, portfolio, date):
max_num_positions = portfolio.current_value / self.min_size
min_num_positions = (1 / self.max_size)
target = min_num_positions + self.diversifier * (max_num_positions - min_num_positions)
# Note: we convert target to an int to round down the target number
# of positions, and bump up the nominal dollar size to provide some
# leeway for multipliers which may want to reduce the size.
return portfolio.current_value / int(target)
class VolatilityMultiplier:
'''
Adjusts the position multiplier based on the current volatility
up or down towards the specified target.
'''
def __init__(self, vol_target, volatilities):
self.target = vol_target
self.volatilities = volatilities
self.ratio = vol_target / volatilities
def __call__(self, portfolio, date):
return self.ratio.loc[date]
# REBALANCING STRATEGIES
class NoRebalancing:
def __init__(self):
self.rebalancing_dates = []
def __call__(self, positions, date):
pass
class FixedRebalanceDates:
def __init__(self):
self.rebalancing_dates = []
def set_weekly_rebalancing(self, daily_series, day = "FRI"):
# Refer to the following link for options:
# http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
# Note the count method is only used to stop pandas from throwing a warning, as
# it wants to know how to aggregate the data.
self.rebalancing_dates = daily_series.resample('W-' + day).count().index
def set_month_end_rebalancing(self, daily_series):
self.rebalancing_dates = daily_series.resample('M').count().index
def __call__(self, positions, date):
if date in self.rebalancing_dates:
positions.apply_rebalancing()
# Portfolio Trade Acceptance Criteria
class MinimimumPositionSize:
def __call__(self, portfolio, trade):
'''
Provides a trade condition where the cash at the time of entry must be greater
than the minimum allowable portfolio size.
'''
return portfolio.cash[trade.entry] > min(portfolio.trade_size)
class MinimumTradePrice:
def __init__(self, min_price):
self.min_price = min_price
def __call__(self, portfolio, trade):
"""
Accepts trades provided the entry price is above a defined threshold.
The idea is to stop positions taken in shares which would incur excessive slippage.
"""
return trade.entry_price >= self.min_price
class Transactions:
"""
Transactions holds a series of buy and sell transactions for each ticker for a particular day.
The Transactions object can then calculate the total cash flows, and position movements for
the Portfolio.
"""
def __init__(self, num_shares, prices, date):
self.date = date
nominal_size = num_shares * prices
trim_factor = 0.02 # This reduces the size of purchases to account for transaction costs
trim_size = (nominal_size * trim_factor) / prices
trim_size[np.isnan(trim_size)] = 0
trim_size = trim_size.astype(int) + 1 # Round to ceiling
sales = num_shares <= 0
trim_size[sales] = 0
num_shares -= trim_size
self.num_shares = num_shares
self.tickers = num_shares.index
self.dollar_positions = num_shares * prices
self.slippage = self.estimate_slippage(prices, num_shares)
self.commissions = Series(0, self.tickers)
self.commissions[num_shares != 0] = 11 # $11 each way
def estimate_slippage(self, prices, num_shares):
"""
Estimates the slippage assuming that the spread is at least one price increment wide.
Price increments used are as defined by the ASX:
Up to $0.10 0.1c
Up to $2.00 0.5c
$2.00 and over 1c
"""
slippage = Series(0, self.tickers)
slippage[prices < 0.1] = num_shares[prices < 0.1] * 0.001
slippage[(prices >= 0.1) & (prices < 2.0)] = num_shares[(prices >= 0.1) & (prices < 2.0)] * 0.005
slippage[prices >= 2.0] = num_shares[prices >= 2.0] * 0.005
return abs(slippage)
def remove(self, tickers):
self.num_shares.loc[tickers] = 0
self.dollar_positions.loc[tickers] = 0
self.slippage.loc[tickers] = 0
self.commissions.loc[tickers] = 0
@property
def active(self):
return self.tickers[self.num_shares != 0]
@property
def total_cost(self):
return self.dollar_positions.sum() + self.total_commissions + self.total_slippage
@property
def total_commissions(self):
return self.commissions.sum()
@property
def total_slippage(self):
return self.slippage.sum()
# These checks can be used to control the position selection process
# If the check fails the position change is removed from consideration.
class PositionNaCheck:
def __call__(self, portfolio, positions):
nans = np.isnan(positions.trade_size)
positions.deselect(nans)
zeroes = positions.trade_size == 0
positions.deselect(zeroes)
class PositionMaxSize:
def __init__(self, size):
self.limit = size
def __call__(self, portfolio, positions):
exceeding_limit = positions.trade_size > self.limit
positions.deselect(exceeding_limit)
class PositionMinSize:
def __init__(self, size):
self.limit = size
def __call__(self, portfolio, positions):
exceeding_limit = positions.trade_size < self.limit
positions.deselect(exceeding_limit)
class PositionCostThreshold:
def __init__(self, threshold):
self.threshold = threshold
def __call__(self, portfolio, positions):
perct_cost = positions.cost / positions.trade_size
exceeding_limit = perct_cost > self.threshold
positions.deselect(exceeding_limit)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,143 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/system/metrics.py |
# Metrics based on a return series
# Each of these methods expect a pandas Series.
from pandas import Series, DataFrame
from numpy import sign, log, NaN
from sklearn.linear_model import LinearRegression
from data_types.constants import TRADING_DAYS_PER_YEAR
def Sharpe(returns):
try:
sharpe = returns.mean() / returns.std()
except ZeroDivisionError:
sharpe = NaN
return sharpe * (TRADING_DAYS_PER_YEAR ** 0.5)
def OptF(returns):
try:
optf = returns.mean() / (returns.std() ** 2)
except ZeroDivisionError:
optf = NaN
return optf
def G(returns):
'''
The growth rate assuming investment at Optimal F
'''
S_sqd = Sharpe(returns) ** 2
return ((1 + S_sqd) ** 2 - S_sqd) ** 0.5 - 1
def GeometricGrowth(returns, N = TRADING_DAYS_PER_YEAR):
G_base = ((1 + returns.mean()) ** 2 - (returns.std() ** 2))
G = (abs(G_base) ** 0.5)
return sign(G_base) * (G ** N) - 1
def K_Ratio(returns):
lm = LinearRegression(fit_intercept = False)
returns = returns.dropna()
returns = ((1 + returns).apply(log)).cumsum()
X = Series(returns.index).reshape(len(returns), 1)
lm.fit(X, returns)
std_error = (Series((lm.predict(X) - returns) ** 2).mean()) ** 0.5
return ((250 ** 0.5) / len(returns)) * (lm.coef_[0] / std_error)
def Drawdowns(returns):
'''
Drawdowns accepts a cumulative returns series, and returns a dataframe with
columns [Drawdowns, Highwater]
'''
high_water = Series(0, index = returns.index, dtype = float)
for i in range(1, len(returns)):
high_water[i] = max(high_water[i - 1], returns[i])
dd = ((returns + 1) / (high_water + 1)) - 1
return DataFrame({'Drawdown' : dd, 'Highwater' : high_water}) | {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,144 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/trade_modifiers/exit_conditions.py |
from pandas import Series
class ExitCondition:
def get_limit_hits(self, trade):
raise NotImplementedError("Exit condition must impelement get_limit_hits")
def __call__(self, trade):
limit_hits = self.get_limit_hits(trade)
if len(limit_hits):
return trade.revise_exit(min(limit_hits))
else:
return trade
class TrailingStop(ExitCondition):
def __init__(self, stop_level):
self.stop = -1 * abs(stop_level)
def get_limit_hits(self, trade):
drawdowns = trade.drawdowns().Drawdown
return drawdowns.index[drawdowns <= self.stop]
class StopLoss(ExitCondition):
def __init__(self, stop_level):
self.stop = -1 * abs(stop_level)
def get_limit_hits(self, trade):
returns = trade.cumulative
return returns.index[returns <= self.stop]
class ReturnTriggeredTrailingStop(ExitCondition):
def __init__(self, stop_level, return_level):
self.stop = -1 * abs(stop_level)
self.return_level = return_level
def get_limit_hits(self, trade):
dd = trade.drawdowns()
drawdowns = dd.Drawdown
highwater = dd.Highwater
return highwater.index[(highwater >= self.return_level) & (drawdowns <= self.stop)]
class PositionBasedStop(StopLoss):
'''
The PositionBasedStop varies its stop level based on the position size
of the trade it is applied to. This accounts for adjustments such as
volatility sizing applied to the position, where you would have a stop
placement inversely proportional to the position (proportional to vol).
In this case stop_level refers to the base stop percentage for a position
size of one.
'''
def __init___(self, stop_level):
self.base_stop = -1 * abs(stop_level)
self.stop = self.base_stop
def get_limit_hits(self, trade):
'''
This stop is not designed for strategies with daily variable
position sizes (i.e. where trade.position_size is a series)
'''
self.stop = self.base_stop / trade.position_size
super().get_limit_hits(trade)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,145 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/TestScript.py | '''
Created on 15 Feb 2015
@author: Mark
'''
from multiprocessing import Pool
import datetime
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import pickle
# Add dev folder of related package(s)
import sys
import os
sys.path.append(os.path.join("C:\\Users", os.getlogin(), "Source\\Repos\\FinancialDataHandling\\financial_data_handling"))
from store.file_system import Storage
# The following is due to working directory not being set correctly on workstation:
#if os.getlogin() == "Mark":
os.chdir(os.path.join("C:\\Users", os.getlogin(), "Source\\Repos\\EnsembleSystemDevelopment\\ensemble_trading_system"))
# Local imports
from data_types.market import Market
from data_types.trades import TradeCollection
from system.core import Strategy, Portfolio
from system.core import VolatilityMultiplier, SizingStrategy
from measures.moving_averages import EMA, KAMA, LinearTrend
from measures.volatility import StdDevEMA
from measures.breakout import TrailingHighLow
from measures.valuations import ValueRatio, ValueRank
from signals.level_signals import Crossover, Breakout
from signals.carter_forecasters import PriceCrossover, EWMAC, CarterForecastFamily
from rules.signal_rules import PositionFromDiscreteSignal
from rules.forecast_rules import CarterPositions
from trade_modifiers.exit_conditions import StopLoss, TrailingStop, ReturnTriggeredTrailingStop
from trade_modifiers.filters import HighPassFilter
from system.core import PositionCostThreshold, PositionMaxSize, PositionMinSize
from system.analysis import Timer, summary_report, ParameterFuzzer
# TODO Strategy should keep full list of trades after filter, to allow easy reapplication of filters without having to
# run full strategy again.
# TODO Strategy idea
# Conditions - Entry
# - Market index EMA(50-200) must be long
# - Individual ticker EMA(50-120) must be long
# - Ticker value ratio (Adjusted) > 2
# - Value rank filter at 10
# Conditions - Exit
# - Individual ticker EMA(50-120) goes short
# - 15% Stop loss
# - Apply 20% trailing stop when returns exceed 30%
# - Apply 10% trailing stop when returns exceed 50%
pd.set_option('display.width', 120)
store = Storage("NYSE")
def signalStratSetup(trade_timing = "O", ind_timing = "C", params = (120, 50), store = store):
strategy = Strategy(trade_timing, ind_timing)
strategy.market = Market(store)
strategy.signal_generator = Crossover(slow = EMA(params[0]), fast = EMA(params[1]))
strategy.position_rules = PositionFromDiscreteSignal(Up = 1)
return strategy
def createEwmacStrategy(ema_params = (120, 50), store = store):
strategy = Strategy("O", "C")
strategy.market = Market(store)
strategy.signal_generator = EWMAC(EMA(max(ema_params)), EMA(min(ema_params)), StdDevEMA(36))
strategy.position_rules = CarterPositions(StdDevEMA(36), 0.25, long_only = True)
return strategy
def createBreakoutStrategy(window = 20, store = store):
strategy = Strategy("O", "C")
strategy.market = Market(store)
strategy.signal_generator = Breakout(TrailingHighLow(window))
strategy.position_rules = PositionFromDiscreteSignal(Up = 1)
return strategy
def createValueRatioStrategy(ema_pd = 90, valuations = ["Adjusted", "Base", "Min"], store = store):
strategy = Strategy("O", "C")
strategy.market = Market(store)
signal_generators = []
for valuation in valuations:
value_ratio = ValueRatio("EPV", valuation)
value_ratios = value_ratio(strategy)
signal_generators.append(PriceCrossover(value_ratios, EMA(ema_pd), StdDevEMA(36)))
strategy.signal_generator = CarterForecastFamily(*signal_generators)
strategy.position_rules = CarterPositions(StdDevEMA(36), 0.25, long_only = True)
return strategy
print("Preparing strat...")
strat = signalStratSetup('O', 'C', params = (150, 75))
##strat = createBreakoutStrategy(window = 60)
# adjusted = ValueRatio('EPV', 'Adjusted')(strat)
# base = ValueRatio('EPV', 'Base')(strat)
# cyclic = ValueRatio('EPV', 'Cyclic')(strat)
# strat.filters.append(HighPassFilter(adjusted, -0.5))
# strat.filters.append(HighPassFilter(cyclic, 0.0))
print("Running base strat...")
with Timer() as t:
strat.run()
print("Completed in {:2}s".format(t.secs))
print("Generated", strat.trades.count, "trades.")
# print("Applying stops...")
# strat.apply_exit_condition(TrailingStop(0.15))
# strat.apply_exit_condition(StopLoss(0.15))
# strat.apply_exit_condition(ReturnTriggeredTrailingStop(0.2, 0.3))
# strat.apply_exit_condition(ReturnTriggeredTrailingStop(0.1, 0.5))
#with open(r'D:\Investing\Workspace\signal_strat.pkl', 'rb') as file:
# strat = pickle.load(file)
#print("Creating ewmac strat...")
#strat = createEwmacStrategy(store)
#print("Running ewmac strat...")
#strat.run()
#strat.positions = strat.positions.discretise(min_size = 0.7, max_size = 2.0, step = 0.5)
#print("Loading strat...")
#with open(r'D:\Investing\Workspace\test_strat.pkl', 'rb') as file:
# strat = pickle.load(file)
# print("Preparing portfolio...")
# port = Portfolio(strat, 15000)
# port.sizing_strategy = SizingStrategy(diversifier = 0.5)
# port.position_checks.append(PositionCostThreshold(0.02))
# print("Running portfolio...")
# port.run()
# print("Done...")
# from system.analysis import ParameterFuzzer
# fuzzer = ParameterFuzzer(strategy, base_parameters = (150, 75), processes = 2)
# fuzzer.fuzzed_pars = [(200, 160), (200, 100), (200, 40), (150, 120), (150, 75), (150, 30), (100, 80), (100, 50), (100, 20)]
# fuzzer.summarise()
# fig, axarr = plt.subplots(1, 3)
# fuzzer.plot_metric('Number of trades', ax = axarr[0])
# fuzzer.plot_metric('Percent winners', ax = axarr[1])
# fuzzer.plot_metric('Ratio average win to loss', ax = axarr[2])
# plt.tight_layout()
# print("Applying weights...")
# from trade_modifiers.weighting import TradeWeighting
# volatilities = StdDevEMA(40)(strat.indicator_prices)
# strat.trades = strat.trades.apply(TradeWeighting(0.3 / volatilities))
print("Ready...")
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,146 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /tests/TestHelpers.py | '''
Created on 22 Dec 2014
@author: Mark
'''
from pandas import DataFrame, Panel
from numpy.matlib import randn
from numpy.random import choice
from pandas.tseries.index import date_range
# Constructors
def buildNumericPanel(items, columns, length):
panel_dict = {item:buildNumericDataFrame(columns, length) for item in items}
return Panel(panel_dict)
def buildTextPanel(items, columns, length, factors = ["False", "True"]):
panel_dict = {item:buildTextDataFrame(columns, length) for item in items}
return Panel(panel_dict)
def buildNumericDataFrame(columns, length):
index = date_range("1/1/2010", periods = length, freq = "D")
return DataFrame(randn(length, len(columns)), index = index, columns = columns)
def buildTextDataFrame(columns, length, factors = ["False", "True"]):
index = date_range("1/1/2010", periods = length, freq = "D")
return DataFrame(choice(factors, (length, len(columns))), index = index, columns = columns)
import time
class Timer(object):
'''
Usage:
with Timer() as t:
[run method to be timed]
print("some words: %s s" % t.secs)
or the following will output as milliseconds "elapsed time: [time] ms":
with Timer(verbose = True) as t:
[run method to be timed]
'''
def __init__(self, verbose=False):
self.verbose = verbose
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.secs = self.end - self.start
self.msecs = self.secs * 1000 # millisecs
if self.verbose:
print("elapsed time: %f ms" % self.msecs)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,147 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/measures/volatility.py |
from . import SignalElement
# TODO Average True Range volatility measure
class EfficiencyRatio(SignalElement):
'''
The Efficiency Ratio is taken from Kaufman's KAMA indicator.
Refer New Trading Systems and Methods 4th Ed (p732)
The Efficiency Ratio is the ratio of the price change of a period
divided by the sum of daily changes.
prices - expected to be a DataFrame (dates vs tickers)
period - an integer lookback window.
'''
def __init__(self, period):
self.period = period
self.name = "EfficiencyRatio{}".format(period)
def __call__(self, prices):
overall_change = prices.diff(self.period).abs()
daily_sum = prices.diff().abs().rolling(window = self.period, center = False).sum()
return overall_change / daily_sum
class StdDevRolling(SignalElement):
"""
Given a set of prices; calculates the annualised rolling standard deviation of returns.
"""
def __init__(self, period):
self.period = period
self.annualisation_factor = 16 # SQRT(256)
def __call__(self, prices):
rtns = (prices.data / prices.data.shift(1)) - 1
return self.annualisation_factor * rtns.rolling(span = self.period).std()
class StdDevEMA(SignalElement):
"""
Given a set of prices; calculates the annualised exponentially weighted average standard deviation of returns.
"""
def __init__(self, period):
self.period = period
self.annualisation_factor = 16 # SQRT(256)
def __call__(self, prices):
rtns = (prices.data / prices.data.shift(1)) - 1
return self.annualisation_factor * rtns.ewm(span = self.period).std() | {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,148 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/event_signals.py | '''
The event_signals module handles creation of signals from disrete events rather than
continuous measures. This allows creation of trades from separate entry and exit setups.
'''
from pandas import Panel, DataFrame
from system.interfaces import SignalElement
from data_types.signals import Signal
class EventSignal(SignalElement):
'''
EventSignal is the basic class for generation of signals from event based entries and exits.
'''
def __init__(self, entries, exits):
self.entries = entries
self.exits = exits
def execute(self, strategy):
events_data = strategy.get_empty_dataframe(fill_data = '-')
for entry_setup in self.entries:
events_data = entry_setup.fill_events(strategy, events_data)
for exit_setup in self.exits:
events_data = exit_setup.fill_events(strategy, events_data)
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,149 | chetanmehra/EnsembleSystemDevelopment | refs/heads/master | /ensemble_trading_system/measures/valuations.py | """
These measures all deal with fundamental valuations of the underlying business
as well as potentially incorporating the current price level(s)
"""
from . import SignalElement
class ValueRatio(SignalElement):
"""
ValueRatio provides the relative value at the current price. A ValueRatio
of zero indicates fair value, negative values is overvalued, and positive are
overvalued.
"""
def __init__(self, valuation_type, sub_type, price_denominator = True):
self.valuation_type = valuation_type
self.sub_type = sub_type
self.price_denominator = price_denominator
@property
def name(self):
return "_".join([self.valuation_type, self.sub_type, "ratio"])
def __call__(self, strategy):
values = strategy.market.get_valuations(self.valuation_type, self.sub_type)
prices = strategy.indicator_prices
if self.price_denominator:
ratios = values.data / prices.data - 1
else:
ratios = prices.data / values.data
ratios.name = self.name
return ratios
class ValueRank(ValueRatio):
"""
ValueRank returns the relative rank at a given day between each security,
based on the valuations provided and the price at the given day.
"""
@property
def name(self):
return "_".join([self.valuation_type, self.sub_type, "rank"])
def __call__(self, strategy):
ratios = super().__call__(strategy)
ranks = ratios.rank(axis = 1, ascending = False)
ranks.name = self.name
return ranks
| {"/ensemble_trading_system/measures/moving_averages.py": ["/ensemble_trading_system/measures/__init__.py", "/ensemble_trading_system/measures/volatility.py"], "/ensemble_trading_system/measures/cross_section.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/breakout.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/volatility.py": ["/ensemble_trading_system/measures/__init__.py"], "/ensemble_trading_system/measures/valuations.py": ["/ensemble_trading_system/measures/__init__.py"]} |
47,180 | KabaevaValentina/my-first-blog | refs/heads/master | /main/migrations/0003_auto_20200608_1331.py | # Generated by Django 3.0.7 on 2020-06-08 06:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20200606_0103'),
]
operations = [
migrations.AlterModelOptions(
name='review',
options={'verbose_name': 'Отзыв', 'verbose_name_plural': 'Отзывы'},
),
migrations.AlterField(
model_name='review',
name='text',
field=models.TextField(null=True, verbose_name='Текст отзыва'),
),
]
| {"/main/forms.py": ["/main/models.py"], "/service/views.py": ["/service/models.py"], "/main/views.py": ["/main/forms.py", "/main/models.py"], "/service/admin.py": ["/service/models.py"], "/main/urls.py": ["/main/views.py"]} |
47,181 | KabaevaValentina/my-first-blog | refs/heads/master | /main/forms.py | from django import forms
from main.models import Review
class ReviewForm(forms.ModelForm):
class Meta:
model=Review
fields = '__all__'
widgets = {
'title':forms.TextInput(attrs={'class':'form-control'}),
'text': forms.Textarea(attrs={'class': 'form-control'}),
'phone': forms.TextInput(attrs={'class': 'form-control'}),
'email': forms.TextInput(attrs={'class': 'form-control'}),
} | {"/main/forms.py": ["/main/models.py"], "/service/views.py": ["/service/models.py"], "/main/views.py": ["/main/forms.py", "/main/models.py"], "/service/admin.py": ["/service/models.py"], "/main/urls.py": ["/main/views.py"]} |
47,182 | KabaevaValentina/my-first-blog | refs/heads/master | /main/migrations/0001_initial.py | # Generated by Django 3.0.7 on 2020-06-05 17:20
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Reviews',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=20, verbose_name='Заглавие')),
('text', models.TextField(blank=True, null=True, verbose_name='Текст отзыва')),
('phone', models.CharField(blank=True, max_length=15, null=True, verbose_name='Номер телефона')),
('email', models.EmailField(max_length=30, null=True, verbose_name='Email')),
('date', models.DateTimeField(auto_now_add=True)),
],
),
]
| {"/main/forms.py": ["/main/models.py"], "/service/views.py": ["/service/models.py"], "/main/views.py": ["/main/forms.py", "/main/models.py"], "/service/admin.py": ["/service/models.py"], "/main/urls.py": ["/main/views.py"]} |
47,183 | KabaevaValentina/my-first-blog | refs/heads/master | /main/models.py | from django.db import models
from django.urls import reverse
class Review(models.Model):
title = models.CharField(verbose_name='Заглавие', max_length=20)
text = models.TextField(verbose_name='Текст отзыва', null=True)
phone = models.CharField(verbose_name='Номер телефона', max_length=15, null=True, blank=True)
email = models.EmailField(verbose_name='Email', max_length=30, null=True)
date = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'Отзыв'
verbose_name_plural = 'Отзывы'
def get_detailUrl(self):
return reverse('rev_detail', kwargs={'pk': self.pk})
def get_absolute_url(self):
return reverse('rev_list')
# Create your models here.
| {"/main/forms.py": ["/main/models.py"], "/service/views.py": ["/service/models.py"], "/main/views.py": ["/main/forms.py", "/main/models.py"], "/service/admin.py": ["/service/models.py"], "/main/urls.py": ["/main/views.py"]} |
47,184 | KabaevaValentina/my-first-blog | refs/heads/master | /service/views.py | from django.shortcuts import render
from django.views.generic.base import View
from .models import Category, Doctor, Service
from django.views import generic
# Create your views here.
class ServicesView(View):
"""Список услуг"""
def get(self, request):
services = Service.objects.all()
return render(request, "main/service_list.html", {"service_list": services})
| {"/main/forms.py": ["/main/models.py"], "/service/views.py": ["/service/models.py"], "/main/views.py": ["/main/forms.py", "/main/models.py"], "/service/admin.py": ["/service/models.py"], "/main/urls.py": ["/main/views.py"]} |
47,185 | KabaevaValentina/my-first-blog | refs/heads/master | /main/views.py | from django.shortcuts import render
from django.views import generic
from .forms import ReviewForm
from .models import Review
class ReviewListView(generic.ListView):
queryset = Review.objects.all()
template_name = 'main/reviewlist.html'
context_object_name = 'rev'
class ReviewDetailView(generic.DetailView):
model = Review
template_name = 'main/reviewdetail.html'
context_object_name = 'rev'
class ReviewCreate(generic.CreateView):
form_class = ReviewForm
template_name = 'main/reviewcreate.html'
# Create your views here.
| {"/main/forms.py": ["/main/models.py"], "/service/views.py": ["/service/models.py"], "/main/views.py": ["/main/forms.py", "/main/models.py"], "/service/admin.py": ["/service/models.py"], "/main/urls.py": ["/main/views.py"]} |
47,186 | KabaevaValentina/my-first-blog | refs/heads/master | /service/admin.py | from django.contrib import admin
from .models import Category, Doctor, Service, Analysis
admin.site.register(Category)
admin.site.register(Doctor)
admin.site.register(Service)
admin.site.register(Analysis)
# Register your models here.
| {"/main/forms.py": ["/main/models.py"], "/service/views.py": ["/service/models.py"], "/main/views.py": ["/main/forms.py", "/main/models.py"], "/service/admin.py": ["/service/models.py"], "/main/urls.py": ["/main/views.py"]} |
47,187 | KabaevaValentina/my-first-blog | refs/heads/master | /main/urls.py | from django.urls import path
from django.http import HttpResponse
from .views import ReviewListView, ReviewDetailView, ReviewCreate
def testView(request):
return HttpResponse('<div align="center"><h1 style="color:blue">Это тестовая страница!</h1></div>')
urlpatterns=[
path('', ReviewListView.as_view(), name='rev_list'),
path('detail/<int:pk>', ReviewDetailView.as_view(), name='rev_detail'),
path('create/', ReviewCreate.as_view(), name='rev_create'),
] | {"/main/forms.py": ["/main/models.py"], "/service/views.py": ["/service/models.py"], "/main/views.py": ["/main/forms.py", "/main/models.py"], "/service/admin.py": ["/service/models.py"], "/main/urls.py": ["/main/views.py"]} |
47,188 | KabaevaValentina/my-first-blog | refs/heads/master | /service/models.py | from django.db import models
class Category(models.Model):
"""Категории"""
name = models.CharField("Категория", max_length=150)
description = models.TextField("Описание")
url = models.SlugField(max_length=160, unique=True)
def __str__(self):
return self.name
class Meta:
verbose_name = "Категория"
verbose_name_plural = "Категории"
class Doctor(models.Model):
"""Врачи"""
name = models.CharField("Имя", max_length=100)
description = models.TextField("Описание")
image = models.ImageField("Изображение", upload_to="doctors/")
def __str__(self):
return self.name
class Meta:
verbose_name = "Ветеринарный врач"
verbose_name_plural = "Ветеринарные врачи"
class Service(models.Model):
"""Услуга"""
title = models.CharField("Название", max_length=100)
doctors = models.ManyToManyField(Doctor, verbose_name="Ветеринарный врач", related_name="doctors")
price = models.PositiveIntegerField("Цена", default=0,
help_text="указывать сумму в рублях")
category = models.ForeignKey(
Category, verbose_name="Категория", on_delete=models.SET_NULL, null=True
)
url = models.SlugField(max_length=130, unique=True)
draft = models.BooleanField("Черновик", default=False)
def __str__(self):
return self.title
class Meta:
verbose_name = "Услуга"
verbose_name_plural = "Услуги"
class Analysis(models.Model):
"""Анализ"""
title = models.CharField("Название", max_length=100)
description = models.TextField("Описание")
price = models.PositiveIntegerField("Цена", default=0,
help_text="указывать сумму в рублях")
day = models.PositiveIntegerField("Сроки исполнения", default=0,
help_text="указывать срок исполнения в днях")
category = models.ForeignKey(
Category, verbose_name="Категория", on_delete=models.SET_NULL, null=True
)
url = models.SlugField(max_length=130, unique=True)
draft = models.BooleanField("Черновик", default=False)
def __str__(self):
return self.title
class Meta:
verbose_name = "Анализ"
verbose_name_plural = "Анализы"
# Create your models here.
| {"/main/forms.py": ["/main/models.py"], "/service/views.py": ["/service/models.py"], "/main/views.py": ["/main/forms.py", "/main/models.py"], "/service/admin.py": ["/service/models.py"], "/main/urls.py": ["/main/views.py"]} |
47,189 | KabaevaValentina/my-first-blog | refs/heads/master | /service/migrations/0002_auto_20200610_1050.py | # Generated by Django 3.0.7 on 2020-06-10 03:50
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('service', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='doctor',
name='created',
field=models.DateTimeField(auto_now_add=True, default=1),
preserve_default=False,
),
migrations.AddField(
model_name='doctor',
name='date',
field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='Дата и время'),
),
migrations.AddField(
model_name='doctor',
name='is_active',
field=models.BooleanField(default=True, verbose_name='Активность'),
),
migrations.AddField(
model_name='doctor',
name='updated',
field=models.DateTimeField(auto_now=True),
),
migrations.CreateModel(
name='Reservation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Name', models.CharField(max_length=100, verbose_name='Как вас зовут?')),
('phone', models.CharField(max_length=15, null=True, verbose_name='Ваш телефон')),
('email', models.EmailField(max_length=30, null=True, verbose_name='Ваш Email')),
('ReserveDate', models.DateTimeField(verbose_name='дата записи')),
('date', models.DateTimeField(auto_now_add=True)),
('category', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='service.Category', verbose_name='Категория')),
],
options={
'verbose_name': 'Заявка на запись к ветеринарному врачу',
'verbose_name_plural': 'Заявки на запись к ветеринарному врачу',
},
),
migrations.CreateModel(
name='DateMaster',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Дата и время')),
('name', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='service.Category')),
],
options={
'verbose_name': 'график работы ветеринарного врача',
'verbose_name_plural': 'графики работы ветеринарных врачей',
},
),
migrations.CreateModel(
name='Analysis',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100, verbose_name='Название')),
('description', models.TextField(verbose_name='Описание')),
('price', models.PositiveIntegerField(default=0, help_text='указывать сумму в рублях', verbose_name='Цена')),
('day', models.PositiveIntegerField(default=0, help_text='указывать срок исполнения в днях', verbose_name='Сроки исполнения')),
('url', models.SlugField(max_length=130, unique=True)),
('draft', models.BooleanField(default=False, verbose_name='Черновик')),
('category', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='service.Category', verbose_name='Категория')),
],
options={
'verbose_name': 'Анализ',
'verbose_name_plural': 'Анализы',
},
),
]
| {"/main/forms.py": ["/main/models.py"], "/service/views.py": ["/service/models.py"], "/main/views.py": ["/main/forms.py", "/main/models.py"], "/service/admin.py": ["/service/models.py"], "/main/urls.py": ["/main/views.py"]} |
47,190 | KabaevaValentina/my-first-blog | refs/heads/master | /service/migrations/0001_initial.py | # Generated by Django 3.0.7 on 2020-06-08 12:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150, verbose_name='Категория')),
('description', models.TextField(verbose_name='Описание')),
('url', models.SlugField(max_length=160, unique=True)),
],
options={
'verbose_name': 'Категория',
'verbose_name_plural': 'Категории',
},
),
migrations.CreateModel(
name='Doctor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Имя')),
('description', models.TextField(verbose_name='Описание')),
('image', models.ImageField(upload_to='doctors/', verbose_name='Изображение')),
],
options={
'verbose_name': 'Ветеринарный врач',
'verbose_name_plural': 'Ветеринарные врачи',
},
),
migrations.CreateModel(
name='Service',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100, verbose_name='Название')),
('price', models.PositiveIntegerField(default=0, help_text='указывать сумму в рублях', verbose_name='Цена')),
('url', models.SlugField(max_length=130, unique=True)),
('draft', models.BooleanField(default=False, verbose_name='Черновик')),
('category', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='service.Category', verbose_name='Категория')),
('doctors', models.ManyToManyField(related_name='doctors', to='service.Doctor', verbose_name='Ветеринарный врач')),
],
options={
'verbose_name': 'Услуга',
'verbose_name_plural': 'Услуги',
},
),
]
| {"/main/forms.py": ["/main/models.py"], "/service/views.py": ["/service/models.py"], "/main/views.py": ["/main/forms.py", "/main/models.py"], "/service/admin.py": ["/service/models.py"], "/main/urls.py": ["/main/views.py"]} |
47,198 | akashsrikanth2310/expertiza-topic-bidding | refs/heads/master | /app/__init__.py | from flask import Flask
from flask import Flask, jsonify, abort, request, make_response, url_for
from app import json_unpacker
from app import matching_model
app= Flask(__name__,static_folder=None)
@app.route("/match", methods=['POST']) #using the post method with /match in the url to get the required app route
def matching():
if not request.json: #will abort the request if it fails to load the json
abort(400) #will have a return status of 400 in case of failure
bidding_data = json_unpacker.JsonUnpacker(request.json) #calles the json_unpacker to get the necessary bidding_data
model = matching_model.MatchingModel(bidding_data.student_ids,
bidding_data.topic_ids,
bidding_data.student_preferences_map,
bidding_data.topic_preferences_map, bidding_data.q_S) #model to get the student_ids,topic_ids,student_preference_map,topic_prefernce_map
return jsonify(model.get_matching()) #returns a json object
| {"/main.py": ["/app/__init__.py"]} |
47,199 | akashsrikanth2310/expertiza-topic-bidding | refs/heads/master | /app/json_unpacker.py | import json
import operator
from random import shuffle
import random
from copy import deepcopy
class JsonUnpacker:
"""
Class for unpacking bidding data from JSON Object.
ATTRIBUTES:
----------
json_dict : dict
The JSON object represented as a python dictionary.
topic_ids : list
{String, String, ....}
A list of the topic_ids of all the topics in the assignment.
student_ids : list
{String, String, ....}
A list containing all the Student IDs.
student_preferences_map : dict
{String : [String, String, ....], String : [String, String, ....], ....}
A dictionary that maps a student ID to a list of topic IDs in the linear
order of the student's preference.
key : Student ID
value : list of topic IDs in the linear order of student's preference.
topic_preferences_map : dict
{String : [String, String, ....], String : [String, String, ....], ....}
A dictionary that maps a topic ID to a list of students in the linear
order of the topic's preference.
key : Topic ID
value : list of student IDs in the linear order of topic's preference.
"""
def __init__(self,data):
self.json_dict = data
self.topic_ids = self.json_dict['tids']
self.student_ids = list(self.json_dict['users'].keys())
self.student_preferences_map = self.gen_stud_pref_map(self.json_dict)
self.topic_preferences_map = self.gen_topic_pref_map(self.json_dict)
self.q_S = int(self.json_dict['q_S'])
def gen_stud_pref_map(self,json_dict):
student_preferences_map = dict()
for student_id in self.student_ids:
chosen_topic_ids = json_dict['users'][student_id]['tid']
if(len(chosen_topic_ids) == 0):
self_topic = json_dict['users'][student_id]['otid']
student_preferences_map[student_id] = deepcopy(self.topic_ids)
shuffle(student_preferences_map[student_id])
if self_topic in student_preferences_map[student_id]:
student_preferences_map[student_id].remove(self_topic)
student_preferences_map[student_id].append(self_topic)
self.json_dict['users'][student_id]['priority'] = random.sample(range(1, len(student_preferences_map[student_id])+1), len(student_preferences_map[student_id]))
self.json_dict['users'][student_id]['time'] = [0]
else:
chosen_topic_priorities = json_dict['users'][student_id]['priority']
student_preferences_map[student_id] = [x for x,_ in
sorted(zip(chosen_topic_ids,
chosen_topic_priorities))]
unchosen_topic_ids = list(set(self.topic_ids).difference(set(
chosen_topic_ids)))
self_topic = json_dict['users'][student_id]['otid']
if self_topic in unchosen_topic_ids:
unchosen_topic_ids.remove(self_topic)
student_preferences_map[student_id] += unchosen_topic_ids
student_preferences_map[student_id].append(self_topic)
return student_preferences_map
def gen_topic_pref_map(self,json_dict):
topic_preferences_map = dict()
for topic_id in self.topic_ids:
topic_preferences_map[topic_id] = []
for student_id in self.student_ids:
if(topic_id in self.student_preferences_map[student_id]):
timestamp = max(json_dict['users'][student_id]['time'])
topic_priority = self.student_preferences_map[
student_id].index(topic_id)
num_chosen_topics = len(json_dict['users'][student_id][
'tid'])
topic_preferences_map[topic_id].append((student_id,
topic_priority,
num_chosen_topics,
timestamp))
topic_preferences_map[topic_id].sort(key = operator.itemgetter(1,2,
3))
topic_preferences_map[topic_id] = [x for x,_,_,_ in
topic_preferences_map[topic_id]]
return topic_preferences_map
| {"/main.py": ["/app/__init__.py"]} |
47,200 | akashsrikanth2310/expertiza-topic-bidding | refs/heads/master | /main.py | from app import app
if __name__ == "__main__":
app.debug = True #setting the debug mode to make error finding easier
app.run() #run the entire flask application
| {"/main.py": ["/app/__init__.py"]} |
47,201 | akashsrikanth2310/expertiza-topic-bidding | refs/heads/master | /app/matching_model.py | import math
import random
import json
class Topic:
"""
Base class for Assignment Topics
ATTRIBUTES:
----------
model : MatchingModel
The parent matching model according to whose rules the matching will be
done.
id : String
The topic ID corresponding to the topic.
preferences : list
{String, String, ....}
List of student IDs in the linear order of the topic's preference.
current_proposals : list
{String, String, ....}
The list of student_ids to which the topic has proposed in the current
step. Initially empty.
accepted_proposals : list
{String, String, ....}
The list of student_ids who have accepted the topic's proposal so far.
Initially empty.
last_proposed : Integer
The position of the student_id in the topic's preference list to which
the topic has last proposed. Initialized to -1.
num_remaining_slots : Integer
Number of students the topic can still be assigned to. Or equivalently,
number of students the topic can still propose to. Initially
model.p_ceil.
"""
current_proposals = []
accepted_proposals = []
last_proposed = -1
def __init__(self,model,id,preferences):
self.id = id
self.preferences = preferences
self.model = model
self.num_remaining_slots = self.model.p_ceil
def propose(self,num):
"""
Proposes to accept 'num' number of Students it has not yet proposed to,
or proposes to accept all the Students it has not yet proposed to if
they are less in number than 'num'.
"""
if(self.last_proposed+num <= len(self.preferences)-1):
self.current_proposals = self.preferences[self.last_proposed + 1
:self.last_proposed+num+1]
self.last_proposed = self.last_proposed + num
else:
self.current_proposals = self.preferences[self.last_proposed + 1
:len(self.preferences)]
self.last_proposed = len(self.preferences)-1
for student_id in self.current_proposals:
self.model.get_student_by_id(student_id).receive_proposal(self.id)
def acknowledge_acceptance(self,student_id):
"""
Acknowledges acceptance of proposal by a student.
"""
self.accepted_proposals.append(student_id)
self.num_remaining_slots -= 1
def done_proposing(self):
'''
Returns a boolean indicating whether the topic has proposed to all the
students in its preference list.
'''
return (self.last_proposed >= len(self.preferences)-1)
def slots_left(self):
'''
Returns a boolean indicating whether the topic has any slots left in its
quota of students.
'''
return self.num_remaining_slots > 0
class Student:
"""
Base class for Review Participants ie., Students.
ATTRIBUTES:
----------
model : MatchingModel
The parent matching model according to whose rules the matching will be
done.
id : String
The Student ID corresponding to the student.
preferences : list
{String, String, ....}
List of topic IDs in the linear order of the student's preference.
current_proposals : list
{String, String, ....}
The list of topic_ids who have proposed to the student in the current
step. Initially empty.
accepted_proposals : list
{String, String, ....}
The list of topic_ids whose proposals the student has accepted so far.
Initially empty.
num_remaining_slots : Integer
The number of topics the student can be still assigned.
Initially model.q_S.
"""
current_proposals = []
accepted_proposals = []
def __init__(self,model,id,preferences):
self.model = model
self.id = id
self.preferences = preferences
self.num_remaining_slots = self.model.q_S
def receive_proposal(self,topic_id):
"""
Receives Proposal from a topic.
"""
self.current_proposals.append(topic_id)
def accept_proposals(self):
"""
Accepts no more than k = num_remaining_slots proposals according to
their preferences, rejecting the rest.
"""
self.current_proposals = list(set(self.current_proposals))
self.current_proposals.sort(key=lambda x: self.preferences.index(x))
self.accepted_proposals = self.accepted_proposals + \
self.current_proposals[:min(len(self.current_proposals),
max(self.num_remaining_slots,0))]
self.current_proposals = []
for topic_id in self.accepted_proposals:
self.model.get_topic_by_id(topic_id).acknowledge_acceptance(self.id)
self.num_remaining_slots -= len(self.accepted_proposals)
class MatchingModel:
"""
Base Class for the Many-to-Many Matching Problem/Model
ATTRIBUTES:
----------
student_ids : list
{String, String, ....}
A list containing all the Student IDs.
topic_ids : list
{String, String, ....}
A list containing all the Topic IDs.
students : list
{Student, Student, ....}
A list containing objects of the 'Student' class, corresponding to the
student IDs in student_ids.
topics : list
{Topic, Topic, ....}
A list containing objects of the 'Topic' class, corresponding to the
topic IDs in topic_ids.
q_S : Integer
Number of topics a student must be assigned.
num_students : Integer
Total number of students.
num_topics : Integer
Total number of topics in the assignment.
p_floor : Integer
Floor of average number of students assigned each topic.
p_ceil : Integer
Ceil of average number of students assigned each topic.
"""
def __init__(self,student_ids,topic_ids,student_preferences_map,
topic_preferences_map,q_S):
self.student_ids = student_ids
self.topic_ids = topic_ids
self.q_S = q_S
self.num_students = len(self.student_ids)
self.num_topics = len(self.topic_ids)
if(self.num_topics==0):
self.num_topics=1
self.p_floor = math.floor(self.num_students * q_S/self.num_topics)
self.p_ceil = math.ceil(self.num_students * q_S/self.num_topics)
self.students = list(map(lambda student_id: Student(self,student_id,
student_preferences_map[student_id]), student_ids))
self.topics = list(map(lambda topic_id: Topic(self,topic_id,
topic_preferences_map[topic_id]), topic_ids))
def get_student_by_id(self,student_id):
"""
Returns Student object corresponding to the given student_id.
"""
student_id_index = self.student_ids.index(student_id)
return self.students[student_id_index]
def get_topic_by_id(self,topic_id):
"""
Returns Topic object corresponding to the given topic_id.
"""
topic_id_index = self.topic_ids.index(topic_id)
return self.topics[topic_id_index]
def stop_condition(self):
"""
Returns a boolean indicating whether the stop condition to the algorithm
has been met.
"""
flag = True
for topic in self.topics:
if (topic.slots_left()):
if not topic.done_proposing():
flag = False
break
return flag
def get_matching(self):
"""
Runs the Many-to-Many matching algorithm on the students and students
according to the specified quotas and returns a stable matching.
RETURNS:
-------
matching : dict
{String : list of Strings, String : list of Strings, ....}
key: Student ID
value: List of topic IDs corresponding to the topics assigned to
the student.
"""
# Highly Recommended: Read the algorithm in the wiki page to better
# understand the following code.
# Wiki Link: http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2019_-_E1986._Allow_reviewers_to_bid_on_what_to_review
# Step 1: Each topic proposes to accept the first p_ceil students in
# its preference list.
# Each student accepts no more than q_S proposals according to their
# preferences, rejecting the rest.
for topic in self.topics:
topic.propose(self.p_ceil)
for student in self.students:
student.accept_proposals()
# Step k: Each course that has z < p_ceil students proposes to accept
# p_ceil - z students it has not yet proposed to.
# Each student accepts no more than qS proposals according to their
# preferences, rejecting the others.
# The algorithm stops when every topic that has not reached the
# maximum quota p_ceil has proposed acceptance to every student.
while(self.stop_condition() == False):
for topic in self.topics:
topic.propose(num = topic.num_remaining_slots)
for student in self.students:
student.accept_proposals()
# Return a dictionary that represents the resultant stable matching.
matching = dict()
for student in self.students:
matching[student.id] = student.accepted_proposals
return matching
| {"/main.py": ["/app/__init__.py"]} |
47,202 | akashsrikanth2310/expertiza-topic-bidding | refs/heads/master | /test/test.py | import json
with open('input.json') as json_file:
data = JsonUnpacker(json.loads(json_file))
model = matching_model.MatchingModel(bidding_data.student_ids,
bidding_data.topic_ids,
bidding_data.student_preferences_map,
bidding_data.topic_preferences_map, bidding_data.q_S)
with open('output.json') as json_file:
json.dump(model.get_matching(),json_file)
| {"/main.py": ["/app/__init__.py"]} |
47,204 | computationalcore/ants-simulation | refs/heads/master | /state.py | from random import randint
from gameobjects.vector2 import Vector2
from config import SCREEN_SIZE, NEST_POSITION, NEST_SIZE
class State(object):
"""
Base Class for a State
"""
def __init__(self, name):
self.name = name
def do_actions(self):
pass
def check_conditions(self):
pass
def entry_actions(self):
pass
def exit_actions(self):
pass
class StateMachine(object):
"""
The class that manage all states.
The StateMachine class stores an instance of each of the states in a dictionary and manages the currently active
state.
"""
def __init__(self):
"""
Class constructor that initialize states dictionary and set state to none.
"""
self.states = {}
self.active_state = None
def add_state(self, state):
"""
Add a instance to the internal dictionary.
:param state: the name of the state
"""
self.states[state.name] = state
def think(self):
"""
Runs once per frame,
:return:
"""
# Only continue if there is an active state
if self.active_state is None:
return
# Perform the actions of the active state, and check conditions
self.active_state.do_actions()
new_state_name = self.active_state.check_conditions()
if new_state_name is not None:
self.set_state(new_state_name)
def set_state(self, new_state_name):
"""
Change states and perform any exit / entry actions.
:param new_state_name: name of the state to be set
"""
if self.active_state is not None:
self.active_state.exit_actions()
self.active_state = self.states[new_state_name]
self.active_state.entry_actions()
class AntStateExploring(State):
"""
The Exploring State for Ants.
The ant moves randomly over the screen area.
"""
def __init__(self, ant):
"""
Call the base class constructor to initialize the State.
:param ant: ant instance that this state belongs to
"""
State.__init__(self, "exploring")
self.ant = ant
def random_destination(self):
"""
Select a point randomly in the screen
"""
w, h = SCREEN_SIZE
self.ant.destination = Vector2(randint(0, w), randint(0, h))
def do_actions(self):
"""
Change ant direction, 1 in 20 calls
"""
if randint(1, 20) == 1:
self.random_destination()
def check_conditions(self):
"""
Check conditions of the ant and environment to decide if state should change.
"""
# If there is a nearby leaf, switch to seeking state
leaf = self.ant.world.get_close_entity("leaf", self.ant.location)
if leaf is not None:
self.ant.leaf_id = leaf.id
return "seeking"
# If there is a nearby spider, switch to hunting state
spider = self.ant.world.get_close_entity("spider", NEST_POSITION, NEST_SIZE)
if spider is not None:
if self.ant.location.get_distance_to(spider.location) < 100.:
self.ant.spider_id = spider.id
return "hunting"
return None
def entry_actions(self):
"""
Actions executed by the ant when it enter explore state.
"""
# Start with random speed and heading
self.ant.speed = 120. + randint(-30, 30)
self.random_destination()
class AntStateSeeking(State):
"""
The Seeking State for Ants.
The ant moves toward a leaf that gets closer to it.
"""
def __init__(self, ant):
"""
Call the base class constructor to initialize the State.
:param ant: ant instance that this state belongs to
"""
State.__init__(self, "seeking")
self.ant = ant
self.leaf_id = None
def check_conditions(self):
"""
Check conditions of the ant and environment to decide if state should change.
"""
# If the leaf is gone, then go back to exploring
leaf = self.ant.world.get(self.ant.leaf_id)
if leaf is None:
return "exploring"
# If we are next to the leaf, pick it up and deliver it
if self.ant.location.get_distance_to(leaf.location) < 5.0:
self.ant.carry(leaf.image)
self.ant.world.remove_entity(leaf)
return "delivering"
return None
def entry_actions(self):
"""
Actions executed by the ant when it enter explore state.
"""
# Set the destination to the location of the leaf
leaf = self.ant.world.get(self.ant.leaf_id)
if leaf is not None:
self.ant.destination = leaf.location
self.ant.speed = 160. + randint(-20, 20)
class AntStateDelivering(State):
"""
The Delivering State for Ants.
The ant moves toward the nest with the collected object.
"""
def __init__(self, ant):
"""
Call the base class constructor to initialize the State.
:param ant: ant instance that this state belongs to
"""
State.__init__(self, "delivering")
self.ant = ant
def check_conditions(self):
"""
Check conditions of the ant and environment to decide if state should change.
"""
# If inside the nest, randomly drop the object
if Vector2(*NEST_POSITION).get_distance_to(self.ant.location) < NEST_SIZE:
if randint(1, 10) == 1:
self.ant.drop(self.ant.world.background)
return "exploring"
return None
def entry_actions(self):
"""
Actions executed by the ant when it enter explore state.
"""
# Move to a random point in the nest
self.ant.speed = 60.
random_offset = Vector2(randint(-20, 20), randint(-20, 20))
self.ant.destination = Vector2(*NEST_POSITION) + random_offset
class AntStateHunting(State):
"""
The Delivering State for Ants.
The ant moves toward the spider with random speed.
"""
def __init__(self, ant):
"""
Call the base class constructor to initialize the State.
:param ant: ant instance that this state belongs to
"""
State.__init__(self, "hunting")
self.ant = ant
self.got_kill = False
self.speed = 0
def do_actions(self):
"""
Check conditions of the ant and environment to decide if state should change.
"""
spider = self.ant.world.get(self.ant.spider_id)
if spider is None:
return
self.ant.destination = spider.location
if self.ant.location.get_distance_to(spider.location) < 15.:
# Give the spider a fighting chance
if randint(1, 5) == 1:
spider.bitten()
# If the spider is dead, move it back to the nest
if spider.health <= 0:
self.ant.carry(spider.image)
self.ant.world.remove_entity(spider)
self.got_kill = True
def check_conditions(self):
"""
Check conditions of the ant and environment to decide if state should change.
"""
if self.got_kill:
return "delivering"
spider = self.ant.world.get(self.ant.spider_id)
# If the spider has been killed then return to exploring state
if spider is None:
return "exploring"
# If the spider gets far enough away, return to exploring state
if spider.location.get_distance_to(NEST_POSITION) > NEST_SIZE * 3:
return "exploring"
return None
def entry_actions(self):
"""
Actions executed by the ant when it enter hunting state.
"""
self.speed = 160. + randint(0, 50)
def exit_actions(self):
"""
Exit state action.
"""
self.got_kill = False | {"/state.py": ["/config.py"], "/main.py": ["/entity.py", "/config.py"], "/entity.py": ["/config.py", "/state.py"]} |
47,205 | computationalcore/ants-simulation | refs/heads/master | /main.py | import pygame
from pygame.locals import *
from entity import Ant, Leaf, Spider
from random import randint
from gameobjects.vector2 import Vector2
from config import ANT_COUNT, SCREEN_SIZE, NEST_POSITION, NEST_SIZE
class World(object):
"""
The World class that the simulation entities live in.
It contain the nest, represented by a circle in the center of the screen, and a number of Ants, Spiders and Leafs
entities.
"""
def __init__(self):
self.entities = {}
self.entity_id = 0
# Draw the nest (a circle) on the background
self.background = pygame.surface.Surface(SCREEN_SIZE).convert()
self.background.fill((255, 255, 255))
pygame.draw.circle(self.background, (200, 222, 187), NEST_POSITION, int(NEST_SIZE))
def add_entity(self, entity):
"""
Stores the entity then advances the current id.
:param entity: The entity instance to be added
:return:
"""
self.entities[self.entity_id] = entity
entity.id = self.entity_id
self.entity_id += 1
def remove_entity(self, entity):
"""
Remove the entity from the world.
:param entity: The entity instance to be removed
:return:
"""
del self.entities[entity.id]
def get(self, entity_id):
"""
Find the entity, given its id (or None if it is not found).
:param entity_id: The ID of the entity
:return:
"""
if entity_id in self.entities:
return self.entities[entity_id]
else:
return None
def process(self, time_passed):
"""
Process every entity in the world.
:param time_passed: Time passed since the last render
"""
time_passed_seconds = time_passed / 1000.0
for entity in self.entities.values():
entity.process(time_passed_seconds)
def render(self, surface):
"""
Draw the background and all the entities.
:param surface: The pygame surface
"""
surface.blit(self.background, (0, 0))
for entity in self.entities.itervalues():
entity.render(surface)
def get_close_entity(self, name, location, distance_range=100.):
"""
Find an entity within range of a location.
:param name: Name of the entity
:param location: location
:param distance_range: The circular distance of the range (circular "field of view")
"""
location = Vector2(*location)
for entity in self.entities.itervalues():
if entity.name == name:
distance = location.get_distance_to(entity.location)
if distance < distance_range:
return entity
return None
def run():
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
pygame.display.set_caption('Ant Simulation')
world = World()
w, h = SCREEN_SIZE
clock = pygame.time.Clock()
ant_image = pygame.image.load("ant.png").convert_alpha()
leaf_image = pygame.image.load("leaf.png").convert_alpha()
spider_image = pygame.image.load("spider.png").convert_alpha()
for ant_no in xrange(ANT_COUNT):
ant = Ant(world, ant_image)
ant.location = Vector2(randint(0, w), randint(0, h))
ant.brain.set_state("exploring")
world.add_entity(ant)
full_screen = False
while True:
for event in pygame.event.get():
if event.type == QUIT:
return
if event.type == KEYDOWN:
if event.key == K_f:
full_screen = not full_screen
if full_screen:
screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32)
else:
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
time_passed = clock.tick(30)
if randint(1, 10) == 1:
leaf = Leaf(world, leaf_image)
leaf.location = Vector2(randint(0, w), randint(0, h))
world.add_entity(leaf)
if randint(1, 100) == 1:
# Make a 'dead' spider image by turning it upside down
spider = Spider(world, spider_image, pygame.transform.flip(spider_image, 0, 1))
spider.location = Vector2(-50, randint(0, h))
spider.destination = Vector2(w+50, randint(0, h))
world.add_entity(spider)
world.process(time_passed)
world.render(screen)
pygame.display.update()
if __name__ == "__main__":
run()
| {"/state.py": ["/config.py"], "/main.py": ["/entity.py", "/config.py"], "/entity.py": ["/config.py", "/state.py"]} |
47,206 | computationalcore/ants-simulation | refs/heads/master | /config.py | """
Load configuration file into configparser object.
"""
import os
import ConfigParser
dir_name = os.path.abspath(os.path.dirname(__file__))
config = ConfigParser.RawConfigParser()
config.read( 'app.cfg')
ANT_COUNT = config.getint('general', 'ants')
SCREEN_SIZE = (config.getint('general', 'screen_size_x'), config.getint('general', 'screen_size_y'))
NEST_POSITION = (config.getint('nest', 'position_x'), config.getint('nest', 'position_y'))
NEST_SIZE = config.getfloat('nest', 'size')
SPIDER_HEALTH = config.getint('general', 'spider_health') | {"/state.py": ["/config.py"], "/main.py": ["/entity.py", "/config.py"], "/entity.py": ["/config.py", "/state.py"]} |
47,207 | computationalcore/ants-simulation | refs/heads/master | /setup.py | #! coding: utf-8
from setuptools import setup
# All versions
install_requires = [
'configparser',
'gameobjects',
'pygame',
'setuptools'
]
setup(
name='Ants Simulation',
version='0.1.0',
description='.',
author=[],
author_email='computationalcore@gmail.com',
url='',
packages=[],
install_requires=install_requires,
dependency_links=['https://github.com/computationalcore/gameobjects/tarball/master#egg=package-0.0.3']
) | {"/state.py": ["/config.py"], "/main.py": ["/entity.py", "/config.py"], "/entity.py": ["/config.py", "/state.py"]} |
47,208 | computationalcore/ants-simulation | refs/heads/master | /entity.py | from config import SCREEN_SIZE, SPIDER_HEALTH
from random import randint
from gameobjects.vector2 import Vector2
from state import StateMachine, AntStateExploring, AntStateSeeking, AntStateDelivering, AntStateHunting
class SimulationEntity(object):
"""
The Base Class for the simulation Entity.
"""
def __init__(self, world, name, image):
"""
Constructor of the SimulationEntity instance.
:param world: The world which the entity belongs
:param name: Name of the entity
:param image: Sprite of the entity
"""
self.world = world
self.name = name
self.image = image
self.location = Vector2(0, 0)
self.destination = Vector2(0, 0)
self.speed = 0.
self.id = 0
self.brain = StateMachine()
def render(self, surface):
"""
Draw the entity.
:param surface: pygame surface object
"""
x, y = self.location
w, h = self.image.get_size()
surface.blit(self.image, (x - w / 2, y - h / 2))
def process(self, time_passed):
"""
Process the entity data.
:param time_passed: Time passed since the last render
"""
self.brain.think()
if self.speed > 0. and self.location != self.destination:
vec_to_destination = self.destination - self.location
distance_to_destination = vec_to_destination.get_length()
heading = vec_to_destination.get_normalized()
travel_distance = min(distance_to_destination, time_passed * self.speed)
self.location += travel_distance * heading
class Ant(SimulationEntity):
"""
The Ant Entity Class
"""
def __init__(self, world, image):
"""
Constructor of the Ant instance.
:param world: The world which the entity belongs
:param image: Sprite of the Ant
"""
SimulationEntity.__init__(self, world, "ant", image)
exploring_state = AntStateExploring(self)
seeking_state = AntStateSeeking(self)
delivering_state = AntStateDelivering(self)
hunting_state = AntStateHunting(self)
self.brain.add_state(exploring_state)
self.brain.add_state(seeking_state)
self.brain.add_state(delivering_state)
self.brain.add_state(hunting_state)
self.carry_image = None
def carry(self, image):
"""
Set carry image.
:param image: the carry image
"""
self.carry_image = image
def drop(self, surface):
if self.carry_image:
x, y = self.location
w, h = self.carry_image.get_size()
surface.blit(self.carry_image, (x - w, y - h / 2))
self.carry_image = None
def render(self, surface):
"""
Draw the ant.
:param surface: pygame surface object
"""
SimulationEntity.render(self, surface)
if self.carry_image:
x, y = self.location
w, h = self.carry_image.get_size()
surface.blit(self.carry_image, (x - w, y - h / 2))
class Leaf(SimulationEntity):
"""
The Leaf Entity Class
"""
def __init__(self, world, image):
"""
Constructor of the Leaf instance.
:param world: The world which the entity belongs
:param image: Sprite of the Leaf
"""
SimulationEntity.__init__(self, world, "leaf", image)
class Spider(SimulationEntity):
"""
The Spider Entity Class
"""
def __init__(self, world, image, dead_image):
"""
Constructor of the Spider instance.
:param world: The world which the entity belongs
:param image: Sprite of the default spider
:param dead_image: Sprite of the dead spider
"""
SimulationEntity.__init__(self, world, "spider", image)
self.dead_image = dead_image
self.health = SPIDER_HEALTH
self.speed = 50. + randint(-20, 20)
def bitten(self):
"""
Execute when spider has been bitten.
"""
self.health -= 1
if self.health <= 0:
self.speed = 0.
self.image = self.dead_image
self.speed = 140.
def render(self, surface):
"""
Draw the spider.
:param surface: pygame surface object
"""
SimulationEntity.render(self, surface)
# Draw a health bar
x, y = self.location
w, h = self.image.get_size()
bar_x = x - 12
bar_y = y + h / 2
surface.fill((255, 0, 0), (bar_x, bar_y, 25, 4))
surface.fill((0, 255, 0), (bar_x, bar_y, self.health, 4))
def process(self, time_passed):
"""
Process the spider data.
:param time_passed: Time passed since the last render
"""
x, y = self.location
if x > SCREEN_SIZE[0] + 2:
self.world.remove_entity(self)
return
SimulationEntity.process(self, time_passed)
| {"/state.py": ["/config.py"], "/main.py": ["/entity.py", "/config.py"], "/entity.py": ["/config.py", "/state.py"]} |
47,209 | brahimmade/RH-System | refs/heads/master | /core/migrations/0003_remove_company_logo.py | # Generated by Django 3.1.1 on 2021-08-05 14:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20210805_1041'),
]
operations = [
migrations.RemoveField(
model_name='company',
name='logo',
),
]
| {"/core/views.py": ["/core/models.py", "/core/forms.py"], "/core/forms.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]} |
47,210 | brahimmade/RH-System | refs/heads/master | /core/views.py | from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from .models import Company, Department, Employee, User
from .forms import CompanyForm, DepartmentForm, EmployeeForm
def index_view(request):
companys = Company.objects.all()
return render(request, 'index.html', {'companys': companys})
def companyForm_view(request):
if request.method == "GET":
form = CompanyForm()
return render(request, 'company_form.html', {'form': form})
else:
form = CompanyForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
return render(request, 'company_form.html', {'form': form})
def updateCompany_view(request, id):
company = Company.objects.get(id=id)
form = CompanyForm(request.POST or None, instance=company)
if form.is_valid():
form.save()
return redirect('index')
return render(request, 'company_form.html', {'form': form, 'company': company})
def deleteCompany_view(request, id):
company = Company.objects.get(id=id)
if request.method == "GET":
return render(request, 'delete_company.html', {'company': company})
else:
company.delete()
return redirect('index')
return render(request, 'delete_company.html')
def departmentsView(request, id):
company = get_object_or_404(Company, id=id)
departments = Department.objects.filter(company=company)
return render(request, 'companys.html', {'company': company, 'departments': departments})
def departmentForm_view(request, id):
company = get_object_or_404(Company, id=id)
user = get_object_or_404(User)
if request.method == "GET":
form = DepartmentForm()
return render(request, 'department_form.html', {'form': form, 'company': company, 'user': user})
else:
form = DepartmentForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
return render(request, 'department_form.html', {'form': form, 'company': company, 'user': user})
def updateDepartment_view(request, id, pk):
company = Company.objects.get(id=id)
department = Department.objects.get(pk=pk)
form = DepartmentForm(request.POST or None, instance=department)
if form.is_valid():
form.save()
return redirect('index')
return render(request, 'department_form.html', {'form': form, 'company': company, 'department': department})
def deleteDepartment_view(request, id, pk):
company = Company.objects.get(id=id)
department = Department.objects.get(pk=pk)
if request.method == "GET":
return render(request, 'delete_department.html', {'company': company, 'department': department})
else:
department.delete()
return redirect('index')
return render(request, 'delete_department.html')
def employees_view(request, id):
company = get_object_or_404(Company, id=id)
employees = Employee.objects.filter(company=company)
return render(request, 'employees.html', {'company': company, 'employees': employees})
def employeeForm_view(request, id):
company = get_object_or_404(Company, id=id)
departments = Department.objects.filter(company=company)
user = get_object_or_404(User)
if request.method == "GET":
form = EmployeeForm()
return render(request, 'user_form.html',
{'form': form, 'company': company, 'user': user, 'departments': departments})
else:
form = EmployeeForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
return render(request, 'user_form.html',
{'form': form, 'company': company, 'user': user, 'departments': departments})
def updateEmployee_view(request, id, pk):
company = get_object_or_404(Company, id=id)
departments = Department.objects.filter(company=company)
employee = Employee.objects.get(pk=pk)
form = EmployeeForm(request.POST or None, instance=employee)
if form.is_valid():
form.save()
return redirect('index')
return render(request, 'user_form.html',
{'form': form, 'company': company, 'departments': departments, 'employee': employee})
def deleteEmployee_view(request, id, pk):
company = get_object_or_404(Company, id=id)
employee = Employee.objects.get(pk=pk)
if request.method == "GET":
return render(request, 'delete_employee.html', {'company': company, 'employee': employee})
else:
employee.delete()
return redirect('index')
return render(request, 'delete_employee.html')
| {"/core/views.py": ["/core/models.py", "/core/forms.py"], "/core/forms.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]} |
47,211 | brahimmade/RH-System | refs/heads/master | /core/forms.py | from django import forms
from .models import Company, Department, Employee
class CompanyForm(forms.ModelForm):
class Meta:
model = Company
fields = ('name', 'legal_number')
widgets = {
'name': forms.TextInput(attrs={'class': 'form-control'}),
'legal_number': forms.TextInput(attrs={'class': 'form-control'}),
}
class DepartmentForm(forms.ModelForm):
class Meta:
model = Department
fields = ('company', 'name', 'status', 'Admin')
class EmployeeForm(forms.ModelForm):
class Meta:
model = Employee
fields = ('name', 'age', 'gender', 'company', 'department', 'user', 'phone', 'role', 'salary', 'joining_date')
| {"/core/views.py": ["/core/models.py", "/core/forms.py"], "/core/forms.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]} |
47,212 | brahimmade/RH-System | refs/heads/master | /core/admin.py | from django.contrib import admin
# Register your models here.
from core.models import Company, Employee, Department
admin.site.register(Employee)
admin.site.register(Department)
admin.site.register(Company)
| {"/core/views.py": ["/core/models.py", "/core/forms.py"], "/core/forms.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]} |
47,213 | brahimmade/RH-System | refs/heads/master | /core/migrations/0002_auto_20210805_1041.py | # Generated by Django 3.1.1 on 2021-08-05 13:41
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('core', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='company',
name='legal_number',
field=models.CharField(default='', max_length=14, unique=True, verbose_name='CNPJ'),
),
migrations.AddField(
model_name='company',
name='logo',
field=models.ImageField(default='', upload_to='media', verbose_name='Logo'),
preserve_default=False,
),
migrations.AddField(
model_name='company',
name='name',
field=models.CharField(default='', max_length=255, unique=True, verbose_name='Nome Fantasia'),
preserve_default=False,
),
migrations.AddField(
model_name='department',
name='Admin',
field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to='auth.user'),
preserve_default=False,
),
migrations.AddField(
model_name='department',
name='company',
field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to='core.company'),
preserve_default=False,
),
migrations.AddField(
model_name='department',
name='name',
field=models.CharField(default='', max_length=255, verbose_name='Departamento'),
preserve_default=False,
),
migrations.AddField(
model_name='department',
name='status',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='employee',
name='company',
field=models.ForeignKey(default='', on_delete=django.db.models.deletion.PROTECT, to='core.company'),
preserve_default=False,
),
migrations.AddField(
model_name='employee',
name='department',
field=models.ForeignKey(default='', on_delete=django.db.models.deletion.PROTECT, to='core.department'),
preserve_default=False,
),
migrations.AlterField(
model_name='company',
name='create_user',
field=models.UUIDField(editable=False, null=True),
),
migrations.AlterField(
model_name='company',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='company',
name='update_user',
field=models.UUIDField(editable=False, null=True),
),
migrations.AlterField(
model_name='department',
name='create_user',
field=models.UUIDField(editable=False, null=True),
),
migrations.AlterField(
model_name='department',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='department',
name='update_user',
field=models.UUIDField(editable=False, null=True),
),
migrations.AlterField(
model_name='employee',
name='create_user',
field=models.UUIDField(editable=False, null=True),
),
migrations.AlterField(
model_name='employee',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='employee',
name='update_user',
field=models.UUIDField(editable=False, null=True),
),
]
| {"/core/views.py": ["/core/models.py", "/core/forms.py"], "/core/forms.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]} |
47,214 | brahimmade/RH-System | refs/heads/master | /core/migrations/0001_initial.py | # Generated by Django 3.1.1 on 2020-09-25 18:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Company',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('create_user', models.UUIDField(default=uuid.UUID('48986eaf-811a-4b64-95f1-142236ce5d58'), editable=False)),
('update_user', models.UUIDField(default=uuid.UUID('fba67b55-383d-455e-862c-3ac8df614ce7'), editable=False)),
],
),
migrations.CreateModel(
name='Department',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('create_user', models.UUIDField(default=uuid.UUID('057ff1ed-c230-4600-9fd1-99492719a89b'), editable=False)),
('update_user', models.UUIDField(default=uuid.UUID('e838368c-8039-4f0c-8e08-304e3a85ab94'), editable=False)),
],
),
migrations.CreateModel(
name='Employee',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),
('name', models.CharField(max_length=100)),
('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female'), ('O', 'Others')], max_length=1)),
('phone', models.CharField(default='Sem Telefone', max_length=14)),
('role', models.CharField(default='Sem Atribuição', max_length=50)),
('age', models.IntegerField(default=0)),
('joining_date', models.DateField(null=True)),
('salary', models.DecimalField(decimal_places=2, default=0, max_digits=12)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('create_user', models.UUIDField(default=uuid.UUID('3f8658c0-b59d-4a93-806b-fc3e32ec56eb'), editable=False)),
('update_user', models.UUIDField(default=uuid.UUID('6e87b72e-3b18-4ef3-b26c-fe4aca9becc1'), editable=False)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
],
),
]
| {"/core/views.py": ["/core/models.py", "/core/forms.py"], "/core/forms.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]} |
47,215 | brahimmade/RH-System | refs/heads/master | /core/urls.py | from django.urls import path
from . import views
urlpatterns = [
path('', views.index_view, name='index'),
path('company/add', views.companyForm_view, name='companys'),
path('update/<int:id>', views.updateCompany_view, name='update_company'),
path('delete/<int:id>', views.deleteCompany_view, name='delete_company'),
path('<int:id>/departments', views.departmentsView, name='departments'),
path('<int:id>/departments/add', views.departmentForm_view, name='create_department'),
path('<int:id>/update/<int:pk>/', views.updateDepartment_view, name='update_department'),
path('<int:id>/delete/<int:pk>/', views.deleteDepartment_view, name='delete_department'),
path('<int:id>/employees', views.employees_view, name='employees'),
path('<int:id>/employees/add', views.employeeForm_view, name='create_employee'),
path('<int:id>/update-employee/<int:pk>', views.updateEmployee_view, name='update_employee'),
path('<int:id>/delete-employee/<int:pk>', views.deleteEmployee_view, name='delete_employee'),
]
| {"/core/views.py": ["/core/models.py", "/core/forms.py"], "/core/forms.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]} |
47,216 | brahimmade/RH-System | refs/heads/master | /core/models.py | from django.contrib.auth.models import User
from django.db import models
class Company(models.Model):
name = models.CharField('Nome Fantasia', max_length=255, unique=True,)
legal_number = models.CharField('CNPJ', max_length=14, unique=True, default="")
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)
create_user = models.UUIDField(editable=False, null=True)
update_user = models.UUIDField(editable=False, null=True)
def __str__(self):
return self.name
class Department(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE)
name = models.CharField('Departamento', max_length=255)
status = models.BooleanField(default=True)
Admin = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)
create_user = models.UUIDField(editable=False, null=True)
update_user = models.UUIDField(editable=False, null=True)
def __str__(self):
return self.name
class Employee(models.Model):
name = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.PROTECT)
GENDER = (
('M', 'Male'),
('F', 'Female'),
('O', 'Others')
)
gender = models.CharField(max_length=1, choices=GENDER)
department = models.ForeignKey(Department, on_delete=models.PROTECT)
company = models.ForeignKey(Company, on_delete=models.PROTECT)
phone = models.CharField(max_length=14, default='Sem Telefone')
role = models.CharField(max_length=50, default='Sem Atribuição')
age = models.IntegerField(default=0)
joining_date = models.DateField(null=True)
salary = models.DecimalField(decimal_places=2, max_digits=12, default=0)
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)
create_user = models.UUIDField(editable=False, null=True)
update_user = models.UUIDField(editable=False, null=True)
def __str__(self):
return str(self.name)
| {"/core/views.py": ["/core/models.py", "/core/forms.py"], "/core/forms.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]} |
47,227 | bipoza/unikastaroak | refs/heads/master | /tutorials/urls.py | from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.article_list, name='article_list'),
url(r'^article/(?P<pk>[0-9]+)/$', views.article_detail, name='article_detail'),
url(r'^article/new/$', views.article_new, name='article_new'),
url(r'^article/(?P<pk>[0-9]+)/edit/$', views.article_edit, name='article_edit'),
url(r'^article/user/(?P<username>[a-zA-Z0-9]+)$', views.user_articles, name='user_articles'),
url(r'^drafts/$', views.article_draft_list, name='article_draft_list'),
url(r'^article/(?P<pk>\d+)/remove/$', views.article_remove, name='article_remove'),
url(r'^article/(?P<pk>\d+)/publish/$', views.article_publish, name='article_publish'),
url(r'^categories/$', views.categories_list, name='categories_list'),
url(r'^accounts/register/$', views.signup, name='register'),
url(r'^accounts/profile/(?P<username>[a-zA-Z0-9]+)$', views.profile, name='profile'),
url(r'^categories/article_list/(?P<categoryParam>[a-zA-Z0-9]+)$', views.article_list_category, name='article_list_catergory'),
] | {"/tutorials/views.py": ["/tutorials/forms.py"]} |
47,228 | bipoza/unikastaroak | refs/heads/master | /tutorials/migrations/0017_article_category.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-11-27 07:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tutorials', '0016_remove_article_file'),
]
operations = [
migrations.AddField(
model_name='article',
name='category',
field=models.TextField(blank=True, null=True),
),
]
| {"/tutorials/views.py": ["/tutorials/forms.py"]} |
47,229 | bipoza/unikastaroak | refs/heads/master | /tutorials/migrations/0004_auto_20171114_1111.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-14 10:11
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tutorials', '0003_auto_20171114_1023'),
]
operations = [
migrations.AlterField(
model_name='article',
name='url',
field=models.URLField(blank=True, validators=[django.core.validators.URLValidator()]),
),
]
| {"/tutorials/views.py": ["/tutorials/forms.py"]} |
47,230 | bipoza/unikastaroak | refs/heads/master | /tutorials/forms.py | from django import forms
from .models import Article
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import categories
class ArticleForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Izenburua'}))
text = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Edukia'}))
url = forms.URLField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'http://www.uni.hezkuntza.net/web/guest/inicio', 'type':'url'}),required=False)
drive_url = forms.URLField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'https://drive.google.com/drive/my-drive', 'pattern':'https?://drive.google.com/.+', 'title':'Sartu google drive-eko partekatze esteka', 'type':'url'}),required=False)
category = forms.CharField(widget=forms.Select(choices=categories, attrs={'class':'form-control'}),required=True)
class Meta:
model = Article
fields = ('title', 'text','category', 'url', 'drive_url' )
class CreateUserForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)
class UserFormEdit(forms.ModelForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'value':'********'}))
class Meta:
model = User
fields = ('username','password','first_name', 'last_name', 'email') | {"/tutorials/views.py": ["/tutorials/forms.py"]} |
47,231 | bipoza/unikastaroak | refs/heads/master | /tutorials/migrations/0015_auto_20171121_0955.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-11-21 08:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tutorials', '0014_article_file'),
]
operations = [
migrations.AlterField(
model_name='article',
name='file',
field=models.FileField(blank=True, null=True, upload_to='documents/%Y/%m/%d/'),
),
]
| {"/tutorials/views.py": ["/tutorials/forms.py"]} |
47,232 | bipoza/unikastaroak | refs/heads/master | /tutorials/views.py | from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Article
from .forms import ArticleForm, UserFormEdit, CreateUserForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from .models import categories
# coding: utf-8
# -*- coding: utf-8 -*-
# Create your views here.
def article_list(request):
articles = Article.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return render(request, 'tutorials/article_list.html', {'articles':articles})
def article_detail(request, pk):
article = get_object_or_404(Article, pk=pk)
return render(request, 'tutorials/article_detail.html', {'article': article})
@login_required
def article_new(request):
if request.method == "POST":
form = ArticleForm(request.POST,request.FILES)
if form.is_valid():
#print(form.url_drive)
article = form.save(commit=False)
article.author = request.user
# article.published_date = timezone.now()
article.save()
return redirect ('article_detail', pk=article.pk)
else:
form = ArticleForm()
return render(request, 'tutorials/article_edit.html', {'form':form})
@login_required
def article_edit(request, pk):
article = get_object_or_404(Article, pk=pk)
current_user = request.user
if current_user.id == article.author_id:
if request.method == "POST":
form = ArticleForm(request.POST, instance=article)
if form.is_valid():
article = form.save(commit=False)
article.author = request.user
article.save()
return redirect('article_detail', pk=article.pk)
else:
form = ArticleForm(instance=article)
return render(request, 'tutorials/article_edit.html', {'form': form})
else:
return redirect('/')
@login_required
def article_draft_list(request):
if request.user.is_authenticated():
userid = request.user.id
articles = Article.objects.filter(published_date__isnull=True, author_id=userid).order_by('created_date')
return render(request, 'tutorials/articles_draft_list.html', {'articles': articles})
def article_publish(request, pk):
article = get_object_or_404(Article, pk=pk)
article.published_date = timezone.now()
article.save()
return redirect('article_detail', pk=pk)
def article_remove(request, pk):
article = get_object_or_404(Article, pk=pk)
article.delete()
return redirect('article_list')
def signup(request):
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('/')
else:
form = CreateUserForm()
return render(request, 'registration/register.html', {'form': form})
def profile(request, username):
user = User.objects.get(username=username)
userArticles = Article.objects.filter(author_id=user.id).filter(published_date__isnull=False).order_by('-published_date')
userArticlesDrafts = Article.objects.filter(author_id=user.id).filter(published_date__isnull=True)
#form = UserFormEdit(initial={'username': user.username, 'first_name':user.first_name, 'last_name':user.last_name, 'email':user.email})
return render(request, 'registration/profile.html', {'user': user, 'userArticles':userArticles, 'userArticlesDrafts':userArticlesDrafts})
def user_articles(request, username):
user = User.objects.get(username=username)
articles= Article.objects.filter(author_id=user.id).exclude(published_date__isnull=True)
return render(request, 'tutorials/article_list.html',{'articles':articles})
def categories_list(request):
categories= Article.objects.exclude(category__isnull=True).values_list('category', flat=True).distinct()
return render(request, 'tutorials/categories_list.html',{'categories':categories})
def article_list_category(request, categoryParam):
print(categoryParam)
articles = Article.objects.filter(published_date__lte=timezone.now(), category=categoryParam).order_by('-published_date')
return render(request, 'tutorials/article_list.html', {'articles':articles})
| {"/tutorials/views.py": ["/tutorials/forms.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.