body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
8ea36962d97d3792c08bc92fd7e8ca37997e8e60ccf5de7e158b00690659df12 | @requires_firmware_version('1.1.2018091003')
def configure_field_control_output_mode(self, mode='CLLOOP', output_enabled=True):
'Configure the field control mode and state.\n\n Args:\n mode (str):\n * Determines whether the field control is in open or closed loop mode\n * "CLLOOP" (closed loop control)\n * "OPLOOP" (open loop control, voltage output)\n\n output_enabled (bool):\n Turn the field control voltage output on or off.\n\n '
self.command(('SOURCE:FIELD:MODE ' + mode))
self.command(('SOURCE:FIELD:STATE ' + str(int(output_enabled)))) | Configure the field control mode and state.
Args:
mode (str):
* Determines whether the field control is in open or closed loop mode
* "CLLOOP" (closed loop control)
* "OPLOOP" (open loop control, voltage output)
output_enabled (bool):
Turn the field control voltage output on or off. | lakeshore/teslameter.py | configure_field_control_output_mode | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.1.2018091003')
def configure_field_control_output_mode(self, mode='CLLOOP', output_enabled=True):
'Configure the field control mode and state.\n\n Args:\n mode (str):\n * Determines whether the field control is in open or closed loop mode\n * "CLLOOP" (closed loop control)\n * "OPLOOP" (open loop control, voltage output)\n\n output_enabled (bool):\n Turn the field control voltage output on or off.\n\n '
self.command(('SOURCE:FIELD:MODE ' + mode))
self.command(('SOURCE:FIELD:STATE ' + str(int(output_enabled)))) | @requires_firmware_version('1.1.2018091003')
def configure_field_control_output_mode(self, mode='CLLOOP', output_enabled=True):
'Configure the field control mode and state.\n\n Args:\n mode (str):\n * Determines whether the field control is in open or closed loop mode\n * "CLLOOP" (closed loop control)\n * "OPLOOP" (open loop control, voltage output)\n\n output_enabled (bool):\n Turn the field control voltage output on or off.\n\n '
self.command(('SOURCE:FIELD:MODE ' + mode))
self.command(('SOURCE:FIELD:STATE ' + str(int(output_enabled))))<|docstring|>Configure the field control mode and state.
Args:
mode (str):
* Determines whether the field control is in open or closed loop mode
* "CLLOOP" (closed loop control)
* "OPLOOP" (open loop control, voltage output)
output_enabled (bool):
Turn the field control voltage output on or off.<|endoftext|> |
b224cedd30596c90f724c72ebf7ef5f252e6731da8aa21afab4b4b6ee4eef91b | @requires_firmware_version('1.1.2018091003')
def get_field_control_output_mode(self):
'Returns the mode and state of the field control output.'
output_state = {'mode': self.query('SOURCE:FIELD:MODE?'), 'output_enabled': bool(int(self.query('SOURCE:FIELD:STATE?')))}
return output_state | Returns the mode and state of the field control output. | lakeshore/teslameter.py | get_field_control_output_mode | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.1.2018091003')
def get_field_control_output_mode(self):
output_state = {'mode': self.query('SOURCE:FIELD:MODE?'), 'output_enabled': bool(int(self.query('SOURCE:FIELD:STATE?')))}
return output_state | @requires_firmware_version('1.1.2018091003')
def get_field_control_output_mode(self):
output_state = {'mode': self.query('SOURCE:FIELD:MODE?'), 'output_enabled': bool(int(self.query('SOURCE:FIELD:STATE?')))}
return output_state<|docstring|>Returns the mode and state of the field control output.<|endoftext|> |
45ac6160b5f4b2fe5b2a07d200f32e7862b5dbb6af9f8558be3cd02ef48c6a8a | @requires_firmware_version('1.1.2018091003')
def configure_field_control_pid(self, gain=None, integral=None, ramp_rate=None):
'Configures the closed loop control parameters of the field control output.\n\n Args:\n gain (float):\n Also known as P or Proportional in PID control.\n This controls how strongly the control output reacts to the present error.\n Note that the integral value is multiplied by the gain value.\n\n integral (float):\n Also known as I or Integral in PID control.\n This controls how strongly the control output reacts to the past error *history*\n\n ramp_rate (float):\n This value controls how quickly the present field setpoint will transition to a new setpoint.\n The ramp rate is configured in field units per second.\n\n '
if (gain is not None):
self.command(('SOURCE:FIELD:CLL:GAIN ' + str(gain)))
if (integral is not None):
self.command(('SOURCE:FIELD:CLL:INTEGRAL ' + str(integral)))
if (ramp_rate is not None):
self.command(('SOURCE:FIELD:CLL:RAMP ' + str(ramp_rate))) | Configures the closed loop control parameters of the field control output.
Args:
gain (float):
Also known as P or Proportional in PID control.
This controls how strongly the control output reacts to the present error.
Note that the integral value is multiplied by the gain value.
integral (float):
Also known as I or Integral in PID control.
This controls how strongly the control output reacts to the past error *history*
ramp_rate (float):
This value controls how quickly the present field setpoint will transition to a new setpoint.
The ramp rate is configured in field units per second. | lakeshore/teslameter.py | configure_field_control_pid | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.1.2018091003')
def configure_field_control_pid(self, gain=None, integral=None, ramp_rate=None):
'Configures the closed loop control parameters of the field control output.\n\n Args:\n gain (float):\n Also known as P or Proportional in PID control.\n This controls how strongly the control output reacts to the present error.\n Note that the integral value is multiplied by the gain value.\n\n integral (float):\n Also known as I or Integral in PID control.\n This controls how strongly the control output reacts to the past error *history*\n\n ramp_rate (float):\n This value controls how quickly the present field setpoint will transition to a new setpoint.\n The ramp rate is configured in field units per second.\n\n '
if (gain is not None):
self.command(('SOURCE:FIELD:CLL:GAIN ' + str(gain)))
if (integral is not None):
self.command(('SOURCE:FIELD:CLL:INTEGRAL ' + str(integral)))
if (ramp_rate is not None):
self.command(('SOURCE:FIELD:CLL:RAMP ' + str(ramp_rate))) | @requires_firmware_version('1.1.2018091003')
def configure_field_control_pid(self, gain=None, integral=None, ramp_rate=None):
'Configures the closed loop control parameters of the field control output.\n\n Args:\n gain (float):\n Also known as P or Proportional in PID control.\n This controls how strongly the control output reacts to the present error.\n Note that the integral value is multiplied by the gain value.\n\n integral (float):\n Also known as I or Integral in PID control.\n This controls how strongly the control output reacts to the past error *history*\n\n ramp_rate (float):\n This value controls how quickly the present field setpoint will transition to a new setpoint.\n The ramp rate is configured in field units per second.\n\n '
if (gain is not None):
self.command(('SOURCE:FIELD:CLL:GAIN ' + str(gain)))
if (integral is not None):
self.command(('SOURCE:FIELD:CLL:INTEGRAL ' + str(integral)))
if (ramp_rate is not None):
self.command(('SOURCE:FIELD:CLL:RAMP ' + str(ramp_rate)))<|docstring|>Configures the closed loop control parameters of the field control output.
Args:
gain (float):
Also known as P or Proportional in PID control.
This controls how strongly the control output reacts to the present error.
Note that the integral value is multiplied by the gain value.
integral (float):
Also known as I or Integral in PID control.
This controls how strongly the control output reacts to the past error *history*
ramp_rate (float):
This value controls how quickly the present field setpoint will transition to a new setpoint.
The ramp rate is configured in field units per second.<|endoftext|> |
5f92d52066ad52bc4ae84874f0682274b4478f09e4b781b338bf94da7dbab5e3 | @requires_firmware_version('1.1.2018091003')
def get_field_control_pid(self):
'Returns the gain, integral, and ramp rate.'
pid = {'gain': float(self.query('SOURCE:FIELD:CLL:GAIN?')), 'integral': float(self.query('SOURCE:FIELD:CLL:INTEGRAL?')), 'ramp_rate': float(self.query('SOURCE:FIELD:CLL:RAMPRATE?'))}
return pid | Returns the gain, integral, and ramp rate. | lakeshore/teslameter.py | get_field_control_pid | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.1.2018091003')
def get_field_control_pid(self):
pid = {'gain': float(self.query('SOURCE:FIELD:CLL:GAIN?')), 'integral': float(self.query('SOURCE:FIELD:CLL:INTEGRAL?')), 'ramp_rate': float(self.query('SOURCE:FIELD:CLL:RAMPRATE?'))}
return pid | @requires_firmware_version('1.1.2018091003')
def get_field_control_pid(self):
pid = {'gain': float(self.query('SOURCE:FIELD:CLL:GAIN?')), 'integral': float(self.query('SOURCE:FIELD:CLL:INTEGRAL?')), 'ramp_rate': float(self.query('SOURCE:FIELD:CLL:RAMPRATE?'))}
return pid<|docstring|>Returns the gain, integral, and ramp rate.<|endoftext|> |
a1f9c97bbcf5f9454e5742ef3ee0613d2fbd14b2d6e9c4013631e45ea65deb0e | @requires_firmware_version('1.1.2018091003')
def set_field_control_setpoint(self, setpoint):
'Sets the field control setpoint value in field units.'
self.command(('SOURCE:FIELD:CLL:SETPOINT ' + str(setpoint))) | Sets the field control setpoint value in field units. | lakeshore/teslameter.py | set_field_control_setpoint | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.1.2018091003')
def set_field_control_setpoint(self, setpoint):
self.command(('SOURCE:FIELD:CLL:SETPOINT ' + str(setpoint))) | @requires_firmware_version('1.1.2018091003')
def set_field_control_setpoint(self, setpoint):
self.command(('SOURCE:FIELD:CLL:SETPOINT ' + str(setpoint)))<|docstring|>Sets the field control setpoint value in field units.<|endoftext|> |
fbbaf5a1a16695e70ccfbf90607d24745231aba6208339f27c3f21d861ff6ea6 | @requires_firmware_version('1.1.2018091003')
def get_field_control_setpoint(self):
'Returns the field control setpoint.'
return float(self.query('SOURCE:FIELD:CLL:SETPOINT?')) | Returns the field control setpoint. | lakeshore/teslameter.py | get_field_control_setpoint | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.1.2018091003')
def get_field_control_setpoint(self):
return float(self.query('SOURCE:FIELD:CLL:SETPOINT?')) | @requires_firmware_version('1.1.2018091003')
def get_field_control_setpoint(self):
return float(self.query('SOURCE:FIELD:CLL:SETPOINT?'))<|docstring|>Returns the field control setpoint.<|endoftext|> |
a29dccab65d962b5135fbf50b6c2eb4745376eb94dc4c640e44f13bd1d4f2e65 | @requires_firmware_version('1.1.2018091003')
def set_field_control_open_loop_voltage(self, output_voltage):
'Sets the field control open loop voltage.'
self.command(('SOURCE:FIELD:OPL:VOLTAGE ' + str(output_voltage))) | Sets the field control open loop voltage. | lakeshore/teslameter.py | set_field_control_open_loop_voltage | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.1.2018091003')
def set_field_control_open_loop_voltage(self, output_voltage):
self.command(('SOURCE:FIELD:OPL:VOLTAGE ' + str(output_voltage))) | @requires_firmware_version('1.1.2018091003')
def set_field_control_open_loop_voltage(self, output_voltage):
self.command(('SOURCE:FIELD:OPL:VOLTAGE ' + str(output_voltage)))<|docstring|>Sets the field control open loop voltage.<|endoftext|> |
c1fe83afe561fca91f1007227d0ca159203d76d08f57cad0aeb868ebace99dda | @requires_firmware_version('1.1.2018091003')
def get_field_control_open_loop_voltage(self):
'Returns the field control open loop voltage.'
return float(self.query('SOURCE:FIELD:OPL:VOLTAGE?')) | Returns the field control open loop voltage. | lakeshore/teslameter.py | get_field_control_open_loop_voltage | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.1.2018091003')
def get_field_control_open_loop_voltage(self):
return float(self.query('SOURCE:FIELD:OPL:VOLTAGE?')) | @requires_firmware_version('1.1.2018091003')
def get_field_control_open_loop_voltage(self):
return float(self.query('SOURCE:FIELD:OPL:VOLTAGE?'))<|docstring|>Returns the field control open loop voltage.<|endoftext|> |
2ad1bf8acd2906eb468c5081f53bffdc0edaa4d7b667eb5a46014f716073057b | @requires_firmware_version('1.4.2019061411')
def set_analog_output(self, analog_output_mode):
'Configures what signal is provided by the analog output BNC'
warnings.warn('set_analog_output will be depreciated in a future version, use set_analog_output_signal instead', PendingDeprecationWarning)
self.command(('SOURCE:AOUT ' + analog_output_mode)) | Configures what signal is provided by the analog output BNC | lakeshore/teslameter.py | set_analog_output | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.4.2019061411')
def set_analog_output(self, analog_output_mode):
warnings.warn('set_analog_output will be depreciated in a future version, use set_analog_output_signal instead', PendingDeprecationWarning)
self.command(('SOURCE:AOUT ' + analog_output_mode)) | @requires_firmware_version('1.4.2019061411')
def set_analog_output(self, analog_output_mode):
warnings.warn('set_analog_output will be depreciated in a future version, use set_analog_output_signal instead', PendingDeprecationWarning)
self.command(('SOURCE:AOUT ' + analog_output_mode))<|docstring|>Configures what signal is provided by the analog output BNC<|endoftext|> |
83f14ac91464192d297fb1fc8eda68e7d170c58edab8965896f961bebe139ba8 | @requires_firmware_version('1.6.2019092002')
def set_analog_output_signal(self, analog_output_mode):
'Configures what signal is provided by the analog output BNC\n\n Args:\n analog_output_mode (str):\n * Configures what signal is provided by the analog output BNC. Options are:\n * "OFF" (output off)\n * "XRAW" (raw amplified X channel Hall voltage)\n * "YRAW" (raw amplified Y channel Hall voltage)\n * "ZRAW" (raw amplified Z channel Hall voltage)\n * "XCOR" (Corrrected X channel field measurement)\n * "YCOR" (Corrected Y channel field measurement)\n * "ZCOR" (Corrected Z channel field measurement)\n * "MCOR" (Corrected magnitude field measurement)\n\n '
self.command(('SOURCE:AOUT ' + analog_output_mode)) | Configures what signal is provided by the analog output BNC
Args:
analog_output_mode (str):
* Configures what signal is provided by the analog output BNC. Options are:
* "OFF" (output off)
* "XRAW" (raw amplified X channel Hall voltage)
* "YRAW" (raw amplified Y channel Hall voltage)
* "ZRAW" (raw amplified Z channel Hall voltage)
* "XCOR" (Corrrected X channel field measurement)
* "YCOR" (Corrected Y channel field measurement)
* "ZCOR" (Corrected Z channel field measurement)
* "MCOR" (Corrected magnitude field measurement) | lakeshore/teslameter.py | set_analog_output_signal | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def set_analog_output_signal(self, analog_output_mode):
'Configures what signal is provided by the analog output BNC\n\n Args:\n analog_output_mode (str):\n * Configures what signal is provided by the analog output BNC. Options are:\n * "OFF" (output off)\n * "XRAW" (raw amplified X channel Hall voltage)\n * "YRAW" (raw amplified Y channel Hall voltage)\n * "ZRAW" (raw amplified Z channel Hall voltage)\n * "XCOR" (Corrrected X channel field measurement)\n * "YCOR" (Corrected Y channel field measurement)\n * "ZCOR" (Corrected Z channel field measurement)\n * "MCOR" (Corrected magnitude field measurement)\n\n '
self.command(('SOURCE:AOUT ' + analog_output_mode)) | @requires_firmware_version('1.6.2019092002')
def set_analog_output_signal(self, analog_output_mode):
'Configures what signal is provided by the analog output BNC\n\n Args:\n analog_output_mode (str):\n * Configures what signal is provided by the analog output BNC. Options are:\n * "OFF" (output off)\n * "XRAW" (raw amplified X channel Hall voltage)\n * "YRAW" (raw amplified Y channel Hall voltage)\n * "ZRAW" (raw amplified Z channel Hall voltage)\n * "XCOR" (Corrrected X channel field measurement)\n * "YCOR" (Corrected Y channel field measurement)\n * "ZCOR" (Corrected Z channel field measurement)\n * "MCOR" (Corrected magnitude field measurement)\n\n '
self.command(('SOURCE:AOUT ' + analog_output_mode))<|docstring|>Configures what signal is provided by the analog output BNC
Args:
analog_output_mode (str):
* Configures what signal is provided by the analog output BNC. Options are:
* "OFF" (output off)
* "XRAW" (raw amplified X channel Hall voltage)
* "YRAW" (raw amplified Y channel Hall voltage)
* "ZRAW" (raw amplified Z channel Hall voltage)
* "XCOR" (Corrrected X channel field measurement)
* "YCOR" (Corrected Y channel field measurement)
* "ZCOR" (Corrected Z channel field measurement)
* "MCOR" (Corrected magnitude field measurement)<|endoftext|> |
4aabebb08d2c5378bf6f4ce930cdc16d86d94ddaa6a23af75ce7d1d7b44bca9e | @requires_firmware_version('1.6.2019092002')
def configure_corrected_analog_output_scaling(self, scale_factor, baseline):
'Configures the conversion between field reading and analog output voltage.\n\n Args:\n scale_factor (float):\n Scale factor in volts per unit field.\n\n baseline (float):\n The field value at which the analog output voltage is zero.\n\n '
self.command(('SOURCE:AOUT:SFACTOR ' + str(scale_factor)), ('SOURCE:AOUT:BASELINE ' + str(baseline))) | Configures the conversion between field reading and analog output voltage.
Args:
scale_factor (float):
Scale factor in volts per unit field.
baseline (float):
The field value at which the analog output voltage is zero. | lakeshore/teslameter.py | configure_corrected_analog_output_scaling | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def configure_corrected_analog_output_scaling(self, scale_factor, baseline):
'Configures the conversion between field reading and analog output voltage.\n\n Args:\n scale_factor (float):\n Scale factor in volts per unit field.\n\n baseline (float):\n The field value at which the analog output voltage is zero.\n\n '
self.command(('SOURCE:AOUT:SFACTOR ' + str(scale_factor)), ('SOURCE:AOUT:BASELINE ' + str(baseline))) | @requires_firmware_version('1.6.2019092002')
def configure_corrected_analog_output_scaling(self, scale_factor, baseline):
'Configures the conversion between field reading and analog output voltage.\n\n Args:\n scale_factor (float):\n Scale factor in volts per unit field.\n\n baseline (float):\n The field value at which the analog output voltage is zero.\n\n '
self.command(('SOURCE:AOUT:SFACTOR ' + str(scale_factor)), ('SOURCE:AOUT:BASELINE ' + str(baseline)))<|docstring|>Configures the conversion between field reading and analog output voltage.
Args:
scale_factor (float):
Scale factor in volts per unit field.
baseline (float):
The field value at which the analog output voltage is zero.<|endoftext|> |
eb0614174f1db040c6e78a9e795699a7a87e86dd108bccaa24f7dff8dc741236 | @requires_firmware_version('1.6.2019092002')
def get_corrected_analog_output_scaling(self):
'Returns the scale factor and baseline of the corrected analog out.'
return (float(self.query('SOURCE:AOUT:SFACTOR?')), float(self.query('SOURCE:AOUT:BASELINE?'))) | Returns the scale factor and baseline of the corrected analog out. | lakeshore/teslameter.py | get_corrected_analog_output_scaling | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def get_corrected_analog_output_scaling(self):
return (float(self.query('SOURCE:AOUT:SFACTOR?')), float(self.query('SOURCE:AOUT:BASELINE?'))) | @requires_firmware_version('1.6.2019092002')
def get_corrected_analog_output_scaling(self):
return (float(self.query('SOURCE:AOUT:SFACTOR?')), float(self.query('SOURCE:AOUT:BASELINE?')))<|docstring|>Returns the scale factor and baseline of the corrected analog out.<|endoftext|> |
3ea84027f03437b1d3487a7180fd114771006f6b7cc91008195a31d41c9880c5 | def get_analog_output(self):
'Returns what signal is being provided by the analog output'
warnings.warn('get_analog_output will be depreciated in a future version, use get_analog_output_signal instead', PendingDeprecationWarning)
return self.query('SOURCE:AOUT?') | Returns what signal is being provided by the analog output | lakeshore/teslameter.py | get_analog_output | lakeshorecryotronics/python-driver | 6 | python | def get_analog_output(self):
warnings.warn('get_analog_output will be depreciated in a future version, use get_analog_output_signal instead', PendingDeprecationWarning)
return self.query('SOURCE:AOUT?') | def get_analog_output(self):
warnings.warn('get_analog_output will be depreciated in a future version, use get_analog_output_signal instead', PendingDeprecationWarning)
return self.query('SOURCE:AOUT?')<|docstring|>Returns what signal is being provided by the analog output<|endoftext|> |
9e0ccb02d7d5b8f18f90bae3790f30086fdad3b3c44e3137f795c3f30c02b5e2 | def get_analog_output_signal(self):
'Returns what signal is being provided by the analog output'
return self.query('SOURCE:AOUT?') | Returns what signal is being provided by the analog output | lakeshore/teslameter.py | get_analog_output_signal | lakeshorecryotronics/python-driver | 6 | python | def get_analog_output_signal(self):
return self.query('SOURCE:AOUT?') | def get_analog_output_signal(self):
return self.query('SOURCE:AOUT?')<|docstring|>Returns what signal is being provided by the analog output<|endoftext|> |
c73a833b1a3586b9674cabad15d7115d3408398a5bf64762e994046470906ff1 | @requires_firmware_version('1.6.2019092002')
def enable_high_frequency_filters(self):
'Applies filtering to the high frequency RMS measurements'
self.command('SENSE:FILT 1') | Applies filtering to the high frequency RMS measurements | lakeshore/teslameter.py | enable_high_frequency_filters | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def enable_high_frequency_filters(self):
self.command('SENSE:FILT 1') | @requires_firmware_version('1.6.2019092002')
def enable_high_frequency_filters(self):
self.command('SENSE:FILT 1')<|docstring|>Applies filtering to the high frequency RMS measurements<|endoftext|> |
730b3f7fb0444a6abec3dc55248c8ec9d1578d0b6b4e629dd2417a9886e3d449 | @requires_firmware_version('1.6.2019092002')
def disable_high_frequency_filters(self):
'Turns off filtering of the high frequency mode measurements'
self.command('SENSE:FILT 0') | Turns off filtering of the high frequency mode measurements | lakeshore/teslameter.py | disable_high_frequency_filters | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def disable_high_frequency_filters(self):
self.command('SENSE:FILT 0') | @requires_firmware_version('1.6.2019092002')
def disable_high_frequency_filters(self):
self.command('SENSE:FILT 0')<|docstring|>Turns off filtering of the high frequency mode measurements<|endoftext|> |
c4402e5dc70fbff0cb3de27291fb28a0cde29ab4490f3efe06f68258ec08cd89 | @requires_firmware_version('1.6.2019092002')
def set_frequency_filter_type(self, filter_type):
'Configures which filter is applied to the high frequency measurements\n\n Args:\n filter_type (str):\n * "LPASS" (low pass filter)\n * "HPASS" (high pass filter)\n * "BPASS" (band pass filter)\n '
self.command(('SENSE:FILT:TYPE ' + str(filter_type))) | Configures which filter is applied to the high frequency measurements
Args:
filter_type (str):
* "LPASS" (low pass filter)
* "HPASS" (high pass filter)
* "BPASS" (band pass filter) | lakeshore/teslameter.py | set_frequency_filter_type | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def set_frequency_filter_type(self, filter_type):
'Configures which filter is applied to the high frequency measurements\n\n Args:\n filter_type (str):\n * "LPASS" (low pass filter)\n * "HPASS" (high pass filter)\n * "BPASS" (band pass filter)\n '
self.command(('SENSE:FILT:TYPE ' + str(filter_type))) | @requires_firmware_version('1.6.2019092002')
def set_frequency_filter_type(self, filter_type):
'Configures which filter is applied to the high frequency measurements\n\n Args:\n filter_type (str):\n * "LPASS" (low pass filter)\n * "HPASS" (high pass filter)\n * "BPASS" (band pass filter)\n '
self.command(('SENSE:FILT:TYPE ' + str(filter_type)))<|docstring|>Configures which filter is applied to the high frequency measurements
Args:
filter_type (str):
* "LPASS" (low pass filter)
* "HPASS" (high pass filter)
* "BPASS" (band pass filter)<|endoftext|> |
9e3f28d5c9d2fe791634b4aa2d5c36e9c29f9dfc1882f6469a96d170bb8e1e8c | @requires_firmware_version('1.6.2019092002')
def get_frequency_filter_type(self):
'Returns the type of filter that is or will be applied to the high frequency measurements'
return self.query('SENSE:FILTER:TYPE?') | Returns the type of filter that is or will be applied to the high frequency measurements | lakeshore/teslameter.py | get_frequency_filter_type | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def get_frequency_filter_type(self):
return self.query('SENSE:FILTER:TYPE?') | @requires_firmware_version('1.6.2019092002')
def get_frequency_filter_type(self):
return self.query('SENSE:FILTER:TYPE?')<|docstring|>Returns the type of filter that is or will be applied to the high frequency measurements<|endoftext|> |
72bd70c343dff5112d5f005f333f5676c3592cc249cabfa078a784729fd2f8ce | @requires_firmware_version('1.6.2019092002')
def get_low_pass_filter_cutoff(self):
'Returns the cutoff frequency setting of the low pass filter'
return float(self.query('SENSE:FILTER:LPASS:CUTOFF?')) | Returns the cutoff frequency setting of the low pass filter | lakeshore/teslameter.py | get_low_pass_filter_cutoff | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def get_low_pass_filter_cutoff(self):
return float(self.query('SENSE:FILTER:LPASS:CUTOFF?')) | @requires_firmware_version('1.6.2019092002')
def get_low_pass_filter_cutoff(self):
return float(self.query('SENSE:FILTER:LPASS:CUTOFF?'))<|docstring|>Returns the cutoff frequency setting of the low pass filter<|endoftext|> |
96a6ff4e2017dd9f470cd157c17af36dab76cac467b3eb0a7bb387095f1dfaf3 | @requires_firmware_version('1.6.2019092002')
def set_low_pass_filter_cutoff(self, cutoff_frequency):
'Configures the low pass filter cutoff\n\n Args:\n cutoff_frequency (float)\n '
self.command(('SENSE:FILTER:LPASS:CUTOFF ' + str(cutoff_frequency))) | Configures the low pass filter cutoff
Args:
cutoff_frequency (float) | lakeshore/teslameter.py | set_low_pass_filter_cutoff | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def set_low_pass_filter_cutoff(self, cutoff_frequency):
'Configures the low pass filter cutoff\n\n Args:\n cutoff_frequency (float)\n '
self.command(('SENSE:FILTER:LPASS:CUTOFF ' + str(cutoff_frequency))) | @requires_firmware_version('1.6.2019092002')
def set_low_pass_filter_cutoff(self, cutoff_frequency):
'Configures the low pass filter cutoff\n\n Args:\n cutoff_frequency (float)\n '
self.command(('SENSE:FILTER:LPASS:CUTOFF ' + str(cutoff_frequency)))<|docstring|>Configures the low pass filter cutoff
Args:
cutoff_frequency (float)<|endoftext|> |
d9fae776d3c7cf22ca7acebb9541d5d13b3e6e644b8f4bad576afcfca303973a | @requires_firmware_version('1.6.2019092002')
def get_high_pass_filter_cutoff(self):
'Returns the cutoff frequency setting of the low pass filter'
return float(self.query('SENSE:FILTER:HPASS:CUTOFF?')) | Returns the cutoff frequency setting of the low pass filter | lakeshore/teslameter.py | get_high_pass_filter_cutoff | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def get_high_pass_filter_cutoff(self):
return float(self.query('SENSE:FILTER:HPASS:CUTOFF?')) | @requires_firmware_version('1.6.2019092002')
def get_high_pass_filter_cutoff(self):
return float(self.query('SENSE:FILTER:HPASS:CUTOFF?'))<|docstring|>Returns the cutoff frequency setting of the low pass filter<|endoftext|> |
3d6fd6b0eb702c88f0bd65491c3e5c373223d9065c4a7553e32373b91f2d6e5b | @requires_firmware_version('1.6.2019092002')
def set_high_pass_filter_cutoff(self, cutoff_frequency):
'Configures the high pass filter cutoff\n\n Args:\n cutoff_frequency (float)\n '
self.command(('SENSE:FILTER:HPASS:CUTOFF ' + str(cutoff_frequency))) | Configures the high pass filter cutoff
Args:
cutoff_frequency (float) | lakeshore/teslameter.py | set_high_pass_filter_cutoff | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def set_high_pass_filter_cutoff(self, cutoff_frequency):
'Configures the high pass filter cutoff\n\n Args:\n cutoff_frequency (float)\n '
self.command(('SENSE:FILTER:HPASS:CUTOFF ' + str(cutoff_frequency))) | @requires_firmware_version('1.6.2019092002')
def set_high_pass_filter_cutoff(self, cutoff_frequency):
'Configures the high pass filter cutoff\n\n Args:\n cutoff_frequency (float)\n '
self.command(('SENSE:FILTER:HPASS:CUTOFF ' + str(cutoff_frequency)))<|docstring|>Configures the high pass filter cutoff
Args:
cutoff_frequency (float)<|endoftext|> |
e47c1f3793b9c18815637d92f33079f6e09e762678701fc63668ebc984dd1c94 | @requires_firmware_version('1.6.2019092002')
def get_band_pass_filter_center(self):
'Returns the center of the band pass filter'
return float(self.query('SENSE:FILTER:BPASS:CENTER?')) | Returns the center of the band pass filter | lakeshore/teslameter.py | get_band_pass_filter_center | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def get_band_pass_filter_center(self):
return float(self.query('SENSE:FILTER:BPASS:CENTER?')) | @requires_firmware_version('1.6.2019092002')
def get_band_pass_filter_center(self):
return float(self.query('SENSE:FILTER:BPASS:CENTER?'))<|docstring|>Returns the center of the band pass filter<|endoftext|> |
84ffa7fbee5073840be4d7b20fd57102d65bc2366f8be6c669b8fa64eeeb85d2 | @requires_firmware_version('1.6')
def set_band_pass_filter_center(self, center_frequency):
'Configures the band pass filter parameters\n\n Args:\n center_frequency (float):\n The frequency at which the gain of the filter is 1\n '
self.command(('SENSE:FILTER:BPASS:CENTER ' + str(center_frequency))) | Configures the band pass filter parameters
Args:
center_frequency (float):
The frequency at which the gain of the filter is 1 | lakeshore/teslameter.py | set_band_pass_filter_center | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6')
def set_band_pass_filter_center(self, center_frequency):
'Configures the band pass filter parameters\n\n Args:\n center_frequency (float):\n The frequency at which the gain of the filter is 1\n '
self.command(('SENSE:FILTER:BPASS:CENTER ' + str(center_frequency))) | @requires_firmware_version('1.6')
def set_band_pass_filter_center(self, center_frequency):
'Configures the band pass filter parameters\n\n Args:\n center_frequency (float):\n The frequency at which the gain of the filter is 1\n '
self.command(('SENSE:FILTER:BPASS:CENTER ' + str(center_frequency)))<|docstring|>Configures the band pass filter parameters
Args:
center_frequency (float):
The frequency at which the gain of the filter is 1<|endoftext|> |
503cc52e360d97e63338a2434ca579b2f446431b999ba0f03a74c07e96cce5d4 | @requires_firmware_version('1.6.2019092002')
def enable_qualifier(self):
'Enables the qualifier'
self.command('SENSE:QUALIFIER 1') | Enables the qualifier | lakeshore/teslameter.py | enable_qualifier | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def enable_qualifier(self):
self.command('SENSE:QUALIFIER 1') | @requires_firmware_version('1.6.2019092002')
def enable_qualifier(self):
self.command('SENSE:QUALIFIER 1')<|docstring|>Enables the qualifier<|endoftext|> |
aba6c775276b612b80e80292efe0b49e69d49a740b3ce85e5c887f087b4cdb0a | @requires_firmware_version('1.6.2019092002')
def disable_qualifier(self):
'Disables the qualifier'
self.command('SENSE:QUALIFIER 0') | Disables the qualifier | lakeshore/teslameter.py | disable_qualifier | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def disable_qualifier(self):
self.command('SENSE:QUALIFIER 0') | @requires_firmware_version('1.6.2019092002')
def disable_qualifier(self):
self.command('SENSE:QUALIFIER 0')<|docstring|>Disables the qualifier<|endoftext|> |
d99f0353515bdf646c9ec1dcc63f6faf3039d49a4b24fd2a8f09be6685c40b2e | @requires_firmware_version('1.6.2019092002')
def is_qualifier_condition_met(self):
'Returns whether the qualifier condition is met'
return bool(int(self.query('SENSE:QUALIFIER:CONDITION?'))) | Returns whether the qualifier condition is met | lakeshore/teslameter.py | is_qualifier_condition_met | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def is_qualifier_condition_met(self):
return bool(int(self.query('SENSE:QUALIFIER:CONDITION?'))) | @requires_firmware_version('1.6.2019092002')
def is_qualifier_condition_met(self):
return bool(int(self.query('SENSE:QUALIFIER:CONDITION?')))<|docstring|>Returns whether the qualifier condition is met<|endoftext|> |
3236065bed6ad0c60827d94cb902bf6ae27792297daec182e6c2b5a2c0b21998 | @requires_firmware_version('1.6.2019092002')
def enable_qualifier_latching(self):
'Enables the qualifier condition latching'
self.command('SENSE:QUALIFIER:LATCH 1') | Enables the qualifier condition latching | lakeshore/teslameter.py | enable_qualifier_latching | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def enable_qualifier_latching(self):
self.command('SENSE:QUALIFIER:LATCH 1') | @requires_firmware_version('1.6.2019092002')
def enable_qualifier_latching(self):
self.command('SENSE:QUALIFIER:LATCH 1')<|docstring|>Enables the qualifier condition latching<|endoftext|> |
06df5a594e12c049bf840237a9d240bc434c20ae743b965cb4a2100a79ccf14f | @requires_firmware_version('1.6.2019092002')
def disable_qualifier_latching(self):
'Disables the qualifier condition latching'
self.command('SENSE:QUALIFIER:LATCH 0') | Disables the qualifier condition latching | lakeshore/teslameter.py | disable_qualifier_latching | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def disable_qualifier_latching(self):
self.command('SENSE:QUALIFIER:LATCH 0') | @requires_firmware_version('1.6.2019092002')
def disable_qualifier_latching(self):
self.command('SENSE:QUALIFIER:LATCH 0')<|docstring|>Disables the qualifier condition latching<|endoftext|> |
bf2bdf65fb4c4e031d98c2d8295f39ba1c478f9db952b99e66e404173680d954 | @requires_firmware_version('1.6.2019092002')
def get_qualifier_latching_setting(self):
'Returns whether the qualifier latches'
return self.query('SENSE:QUALIFIER:LATCH?') | Returns whether the qualifier latches | lakeshore/teslameter.py | get_qualifier_latching_setting | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def get_qualifier_latching_setting(self):
return self.query('SENSE:QUALIFIER:LATCH?') | @requires_firmware_version('1.6.2019092002')
def get_qualifier_latching_setting(self):
return self.query('SENSE:QUALIFIER:LATCH?')<|docstring|>Returns whether the qualifier latches<|endoftext|> |
8a893c74b8e5d13223ab337975e96691f7d8f78f7e60b7a1442ef32ee9c212da | @requires_firmware_version('1.6.2019092002')
def set_qualifier_latching_setting(self, latching):
'Sets whether the qualifier latches\n\n Args:\n latching (bool):\n Determines whether the qualifier latches\n '
self.command(('SENSE:QUALIFIER:LATCH ' + str(latching))) | Sets whether the qualifier latches
Args:
latching (bool):
Determines whether the qualifier latches | lakeshore/teslameter.py | set_qualifier_latching_setting | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def set_qualifier_latching_setting(self, latching):
'Sets whether the qualifier latches\n\n Args:\n latching (bool):\n Determines whether the qualifier latches\n '
self.command(('SENSE:QUALIFIER:LATCH ' + str(latching))) | @requires_firmware_version('1.6.2019092002')
def set_qualifier_latching_setting(self, latching):
'Sets whether the qualifier latches\n\n Args:\n latching (bool):\n Determines whether the qualifier latches\n '
self.command(('SENSE:QUALIFIER:LATCH ' + str(latching)))<|docstring|>Sets whether the qualifier latches
Args:
latching (bool):
Determines whether the qualifier latches<|endoftext|> |
fbd0476c246af8b87c1b50aea8493b71afc28dccf2f186330794a6f1521019e3 | @requires_firmware_version('1.6.2019092002')
def reset_qualifier_latch(self):
'Resets the condition status of the qualifier'
self.command('SENSE:QUALIFIER:LRESET') | Resets the condition status of the qualifier | lakeshore/teslameter.py | reset_qualifier_latch | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def reset_qualifier_latch(self):
self.command('SENSE:QUALIFIER:LRESET') | @requires_firmware_version('1.6.2019092002')
def reset_qualifier_latch(self):
self.command('SENSE:QUALIFIER:LRESET')<|docstring|>Resets the condition status of the qualifier<|endoftext|> |
1bc647ee39675c58e761ca06c8dfeccb58f8d5bb2d5526fe1576644cd4cac125 | @requires_firmware_version('1.6.2019092002')
def get_qualifier_configuration(self):
'Returns the threshold mode and field threshold values'
response = self.query('SENSE:QUALIFIER:THRESHOLD?')
elements = response.split(',')
mode = elements[0]
threshold_field_low = float(elements[1])
threshold = (mode, threshold_field_low)
if (len(elements) == 3):
threshold_field_upper = float(elements[2])
threshold = (mode, threshold_field_low, threshold_field_upper)
return threshold | Returns the threshold mode and field threshold values | lakeshore/teslameter.py | get_qualifier_configuration | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def get_qualifier_configuration(self):
response = self.query('SENSE:QUALIFIER:THRESHOLD?')
elements = response.split(',')
mode = elements[0]
threshold_field_low = float(elements[1])
threshold = (mode, threshold_field_low)
if (len(elements) == 3):
threshold_field_upper = float(elements[2])
threshold = (mode, threshold_field_low, threshold_field_upper)
return threshold | @requires_firmware_version('1.6.2019092002')
def get_qualifier_configuration(self):
response = self.query('SENSE:QUALIFIER:THRESHOLD?')
elements = response.split(',')
mode = elements[0]
threshold_field_low = float(elements[1])
threshold = (mode, threshold_field_low)
if (len(elements) == 3):
threshold_field_upper = float(elements[2])
threshold = (mode, threshold_field_low, threshold_field_upper)
return threshold<|docstring|>Returns the threshold mode and field threshold values<|endoftext|> |
0ce7a1e6aa3eee5d2a7f94e67d4841508e2a50f2ab2270b4f9b31a734c4c3cd5 | @requires_firmware_version('1.6.2019092002')
def configure_qualifier(self, mode, lower_field, upper_field=None):
'Sets the threshold condition of the qualifier.\n\n Args:\n mode (str):\n The type of threshold condition used by the qualifer\n * "OVER"\n * "UNDER"\n * "BETWEEN"\n * "OUTSIDE"\n * "ABSBETWEEN"\n * "ABSOUTSIDE"\n\n lower_field (float):\n The lower field value threshold used by the qualifier\n\n upper_field (float):\n The upper field value threshold used by the qualifier. Not used for OVER or UNDER\n '
if (upper_field is None):
self.command(((('SENSE:QUALIFIER:THRESHOLD ' + mode) + ',') + str(lower_field)))
else:
self.command(((((('SENSE:QUALIFIER:THRESHOLD ' + mode) + ',') + str(lower_field)) + ',') + str(upper_field))) | Sets the threshold condition of the qualifier.
Args:
mode (str):
The type of threshold condition used by the qualifer
* "OVER"
* "UNDER"
* "BETWEEN"
* "OUTSIDE"
* "ABSBETWEEN"
* "ABSOUTSIDE"
lower_field (float):
The lower field value threshold used by the qualifier
upper_field (float):
The upper field value threshold used by the qualifier. Not used for OVER or UNDER | lakeshore/teslameter.py | configure_qualifier | lakeshorecryotronics/python-driver | 6 | python | @requires_firmware_version('1.6.2019092002')
def configure_qualifier(self, mode, lower_field, upper_field=None):
'Sets the threshold condition of the qualifier.\n\n Args:\n mode (str):\n The type of threshold condition used by the qualifer\n * "OVER"\n * "UNDER"\n * "BETWEEN"\n * "OUTSIDE"\n * "ABSBETWEEN"\n * "ABSOUTSIDE"\n\n lower_field (float):\n The lower field value threshold used by the qualifier\n\n upper_field (float):\n The upper field value threshold used by the qualifier. Not used for OVER or UNDER\n '
if (upper_field is None):
self.command(((('SENSE:QUALIFIER:THRESHOLD ' + mode) + ',') + str(lower_field)))
else:
self.command(((((('SENSE:QUALIFIER:THRESHOLD ' + mode) + ',') + str(lower_field)) + ',') + str(upper_field))) | @requires_firmware_version('1.6.2019092002')
def configure_qualifier(self, mode, lower_field, upper_field=None):
'Sets the threshold condition of the qualifier.\n\n Args:\n mode (str):\n The type of threshold condition used by the qualifer\n * "OVER"\n * "UNDER"\n * "BETWEEN"\n * "OUTSIDE"\n * "ABSBETWEEN"\n * "ABSOUTSIDE"\n\n lower_field (float):\n The lower field value threshold used by the qualifier\n\n upper_field (float):\n The upper field value threshold used by the qualifier. Not used for OVER or UNDER\n '
if (upper_field is None):
self.command(((('SENSE:QUALIFIER:THRESHOLD ' + mode) + ',') + str(lower_field)))
else:
self.command(((((('SENSE:QUALIFIER:THRESHOLD ' + mode) + ',') + str(lower_field)) + ',') + str(upper_field)))<|docstring|>Sets the threshold condition of the qualifier.
Args:
mode (str):
The type of threshold condition used by the qualifer
* "OVER"
* "UNDER"
* "BETWEEN"
* "OUTSIDE"
* "ABSBETWEEN"
* "ABSOUTSIDE"
lower_field (float):
The lower field value threshold used by the qualifier
upper_field (float):
The upper field value threshold used by the qualifier. Not used for OVER or UNDER<|endoftext|> |
baeb401e250a7f3d818cb620333b7188f4850063b91b96ac515022f4926c3ff0 | def onlineThread(self):
' Thread to Handle fetching of Urls from API'
import threading
urlThread = threading.Thread(target=self.playOnline)
print('Url Thread Start ')
urlThread.start()
print('Url Thread waiting to complete ')
print('Url Thread complete ') | Thread to Handle fetching of Urls from API | Player.py | onlineThread | Ashuto7h/Q-Stream | 26 | python | def onlineThread(self):
' '
import threading
urlThread = threading.Thread(target=self.playOnline)
print('Url Thread Start ')
urlThread.start()
print('Url Thread waiting to complete ')
print('Url Thread complete ') | def onlineThread(self):
' '
import threading
urlThread = threading.Thread(target=self.playOnline)
print('Url Thread Start ')
urlThread.start()
print('Url Thread waiting to complete ')
print('Url Thread complete ')<|docstring|>Thread to Handle fetching of Urls from API<|endoftext|> |
48505cb72be89bd18598b0557622bafd353ecf76721455831e42d0af9fb3f528 | def openFile(self):
'Open File from System'
print('[ ! OPEN FILE ]')
username = getpass.getuser()
if (sys.platform == 'win32'):
path = (('C:/Users/' + username) + '/Videos/')
elif ((sys.platform == 'linux') or (sys.platform == 'Darwin')):
path = (('/home/' + username) + '/Videos/')
(fileName, _) = QFileDialog.getOpenFileName(self.video_playback, 'Select media file', path, 'Video Files (*.mp3 *.mp4 *.flv *.ts *.mts *.avi *.mkv)')
if fileName:
self.currentMedia = {'type': 'file', 'src': fileName, 'error': False}
self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(fileName)))
self.play_video() | Open File from System | Player.py | openFile | Ashuto7h/Q-Stream | 26 | python | def openFile(self):
print('[ ! OPEN FILE ]')
username = getpass.getuser()
if (sys.platform == 'win32'):
path = (('C:/Users/' + username) + '/Videos/')
elif ((sys.platform == 'linux') or (sys.platform == 'Darwin')):
path = (('/home/' + username) + '/Videos/')
(fileName, _) = QFileDialog.getOpenFileName(self.video_playback, 'Select media file', path, 'Video Files (*.mp3 *.mp4 *.flv *.ts *.mts *.avi *.mkv)')
if fileName:
self.currentMedia = {'type': 'file', 'src': fileName, 'error': False}
self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(fileName)))
self.play_video() | def openFile(self):
print('[ ! OPEN FILE ]')
username = getpass.getuser()
if (sys.platform == 'win32'):
path = (('C:/Users/' + username) + '/Videos/')
elif ((sys.platform == 'linux') or (sys.platform == 'Darwin')):
path = (('/home/' + username) + '/Videos/')
(fileName, _) = QFileDialog.getOpenFileName(self.video_playback, 'Select media file', path, 'Video Files (*.mp3 *.mp4 *.flv *.ts *.mts *.avi *.mkv)')
if fileName:
self.currentMedia = {'type': 'file', 'src': fileName, 'error': False}
self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(fileName)))
self.play_video()<|docstring|>Open File from System<|endoftext|> |
15af86728f5ad13f616c4be74faef14763fd8a14aaccca0826455f6100fd8ef4 | def play_video(self):
'Toggle between play and pause of `Button` State '
print('[ ! PLAYING VIDEO ]')
self.play_button.setEnabled(True)
if (self.mediaPlayer.state() == QMediaPlayer.PlayingState):
self.mediaPlayer.pause()
else:
self.mediaPlayer.play() | Toggle between play and pause of `Button` State | Player.py | play_video | Ashuto7h/Q-Stream | 26 | python | def play_video(self):
' '
print('[ ! PLAYING VIDEO ]')
self.play_button.setEnabled(True)
if (self.mediaPlayer.state() == QMediaPlayer.PlayingState):
self.mediaPlayer.pause()
else:
self.mediaPlayer.play() | def play_video(self):
' '
print('[ ! PLAYING VIDEO ]')
self.play_button.setEnabled(True)
if (self.mediaPlayer.state() == QMediaPlayer.PlayingState):
self.mediaPlayer.pause()
else:
self.mediaPlayer.play()<|docstring|>Toggle between play and pause of `Button` State<|endoftext|> |
8acda0fd05b3307877ddd8aec2d6c7142daa6be276f44e03d1f5e2758fb38bea | def mediaStateChanged(self, state):
'Toggle between play and pause of `Video` State '
print('[ ! CHANGING MEDIA STATE ]')
if (self.mediaPlayer.state() == QMediaPlayer.PlayingState):
self.play_button.setProperty('play', False)
self.play_button.setStyle(self.play_button.style())
else:
self.play_button.setProperty('play', True)
self.play_button.setStyle(self.play_button.style()) | Toggle between play and pause of `Video` State | Player.py | mediaStateChanged | Ashuto7h/Q-Stream | 26 | python | def mediaStateChanged(self, state):
' '
print('[ ! CHANGING MEDIA STATE ]')
if (self.mediaPlayer.state() == QMediaPlayer.PlayingState):
self.play_button.setProperty('play', False)
self.play_button.setStyle(self.play_button.style())
else:
self.play_button.setProperty('play', True)
self.play_button.setStyle(self.play_button.style()) | def mediaStateChanged(self, state):
' '
print('[ ! CHANGING MEDIA STATE ]')
if (self.mediaPlayer.state() == QMediaPlayer.PlayingState):
self.play_button.setProperty('play', False)
self.play_button.setStyle(self.play_button.style())
else:
self.play_button.setProperty('play', True)
self.play_button.setStyle(self.play_button.style())<|docstring|>Toggle between play and pause of `Video` State<|endoftext|> |
6f331d29958c77d055f646d9c54cde73302e4dd0878e0d2b6ce0c0b0d4cb0f2d | def stopplayback(self):
'To play Video from start'
print('[ ! STOP PLAYBACK VIDEO ]')
self.mediaPlayer.stop()
self.play_video() | To play Video from start | Player.py | stopplayback | Ashuto7h/Q-Stream | 26 | python | def stopplayback(self):
print('[ ! STOP PLAYBACK VIDEO ]')
self.mediaPlayer.stop()
self.play_video() | def stopplayback(self):
print('[ ! STOP PLAYBACK VIDEO ]')
self.mediaPlayer.stop()
self.play_video()<|docstring|>To play Video from start<|endoftext|> |
aa859668de86cf55ea52bddd3b9a3af4ff550a4df1db5cbec222100d3811e754 | def positionChanged(self, position):
'Set Player Video to postion fetch by slider'
print('[ ! POSITION CHANGED ]')
self.position_slider.setValue(position) | Set Player Video to postion fetch by slider | Player.py | positionChanged | Ashuto7h/Q-Stream | 26 | python | def positionChanged(self, position):
print('[ ! POSITION CHANGED ]')
self.position_slider.setValue(position) | def positionChanged(self, position):
print('[ ! POSITION CHANGED ]')
self.position_slider.setValue(position)<|docstring|>Set Player Video to postion fetch by slider<|endoftext|> |
9878291f9da3256c2d9ad489f1fcef54460ad5b51a86b34d0ea5cb73171075ff | def durationChanged(self, duration):
'handle duration lables and change whenever it changes'
print('[ ! DURATION CHANGED ]')
self.position_slider.setRange(0, duration)
self.duration_status.clear()
mtime = QtCore.QTime(0, 0, 0, 0)
time = mtime.addMSecs(self.mediaPlayer.duration())
self.duration_status.setText(time.toString()) | handle duration lables and change whenever it changes | Player.py | durationChanged | Ashuto7h/Q-Stream | 26 | python | def durationChanged(self, duration):
print('[ ! DURATION CHANGED ]')
self.position_slider.setRange(0, duration)
self.duration_status.clear()
mtime = QtCore.QTime(0, 0, 0, 0)
time = mtime.addMSecs(self.mediaPlayer.duration())
self.duration_status.setText(time.toString()) | def durationChanged(self, duration):
print('[ ! DURATION CHANGED ]')
self.position_slider.setRange(0, duration)
self.duration_status.clear()
mtime = QtCore.QTime(0, 0, 0, 0)
time = mtime.addMSecs(self.mediaPlayer.duration())
self.duration_status.setText(time.toString())<|docstring|>handle duration lables and change whenever it changes<|endoftext|> |
92f78363be77b71612b81f2a60505c53563fbda1f679abb57fbcd3f43b7b5302 | def setPosition(self, position):
'Set Video to a specific position'
print('[ ! POSITION SET ]')
self.mediaPlayer.setPosition(position) | Set Video to a specific position | Player.py | setPosition | Ashuto7h/Q-Stream | 26 | python | def setPosition(self, position):
print('[ ! POSITION SET ]')
self.mediaPlayer.setPosition(position) | def setPosition(self, position):
print('[ ! POSITION SET ]')
self.mediaPlayer.setPosition(position)<|docstring|>Set Video to a specific position<|endoftext|> |
f1a910b42cc6158690b823cf93537e92aa2c97643a220d0a7acbf6a4e47cdf52 | def setVolumePos(self, remain):
'Set Volume slider value according to volume'
print('[ ! REMANING VOLUME ]')
print(remain)
self.volumeslider.setRange(remain, 100) | Set Volume slider value according to volume | Player.py | setVolumePos | Ashuto7h/Q-Stream | 26 | python | def setVolumePos(self, remain):
print('[ ! REMANING VOLUME ]')
print(remain)
self.volumeslider.setRange(remain, 100) | def setVolumePos(self, remain):
print('[ ! REMANING VOLUME ]')
print(remain)
self.volumeslider.setRange(remain, 100)<|docstring|>Set Volume slider value according to volume<|endoftext|> |
1780135c4e80da25ee916a687e451d489ff2631d642921026d5da34e4b56b7fe | def setVolume(self, vol):
'Handle Volume Button icon and mediaPlayer volume'
print('[ ! SET VOLUME ]')
print(('set volume = ' + str(vol)))
if ((vol >= 0) and (vol <= 100)):
self.volume_percentage.setText(((' ' + str(vol)) + ' %'))
if (vol <= 0):
icon9 = QtGui.QIcon()
icon9.addPixmap(QtGui.QPixmap('icon_sets/volume/volume2.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.volume_button.setIcon(icon9)
else:
icon9 = QtGui.QIcon()
icon9.addPixmap(QtGui.QPixmap('icon_sets/volume/volume1.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.volume_button.setIcon(icon9)
self.volumeslider.setValue(vol)
self.mediaPlayer.setVolume(vol) | Handle Volume Button icon and mediaPlayer volume | Player.py | setVolume | Ashuto7h/Q-Stream | 26 | python | def setVolume(self, vol):
print('[ ! SET VOLUME ]')
print(('set volume = ' + str(vol)))
if ((vol >= 0) and (vol <= 100)):
self.volume_percentage.setText(((' ' + str(vol)) + ' %'))
if (vol <= 0):
icon9 = QtGui.QIcon()
icon9.addPixmap(QtGui.QPixmap('icon_sets/volume/volume2.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.volume_button.setIcon(icon9)
else:
icon9 = QtGui.QIcon()
icon9.addPixmap(QtGui.QPixmap('icon_sets/volume/volume1.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.volume_button.setIcon(icon9)
self.volumeslider.setValue(vol)
self.mediaPlayer.setVolume(vol) | def setVolume(self, vol):
print('[ ! SET VOLUME ]')
print(('set volume = ' + str(vol)))
if ((vol >= 0) and (vol <= 100)):
self.volume_percentage.setText(((' ' + str(vol)) + ' %'))
if (vol <= 0):
icon9 = QtGui.QIcon()
icon9.addPixmap(QtGui.QPixmap('icon_sets/volume/volume2.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.volume_button.setIcon(icon9)
else:
icon9 = QtGui.QIcon()
icon9.addPixmap(QtGui.QPixmap('icon_sets/volume/volume1.png'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.volume_button.setIcon(icon9)
self.volumeslider.setValue(vol)
self.mediaPlayer.setVolume(vol)<|docstring|>Handle Volume Button icon and mediaPlayer volume<|endoftext|> |
8e56e332402c443765896d663ece445bb215b3b4b3e01d21d2062aa300e8b2d7 | def screenshot(self):
'Capture Only screen size of player window using screen cordinates.\n Save to Default Pictures dictoary in System.\n Save in png format.\n '
print('[ ! SCREENSHOT ]')
wincen = Form.geometry()
topX = wincen.topLeft().x()
topY = wincen.topLeft().y()
geo = self.video_playback.geometry()
image = pyautogui.screenshot(region=(topX, (topY + 38), geo.width(), (geo.height() - 35)))
filename = (('screenshot' + str(uuid.uuid4())) + '.png')
username = getpass.getuser()
if (sys.platform == 'win32'):
path = ((('C:/Users/' + username) + '/Pictures/') + filename)
elif ((sys.platform == 'linux') or (sys.platform == 'Darwin')):
path = ((('/home/' + username) + '/Pictures/') + filename)
image.save(path) | Capture Only screen size of player window using screen cordinates.
Save to Default Pictures dictoary in System.
Save in png format. | Player.py | screenshot | Ashuto7h/Q-Stream | 26 | python | def screenshot(self):
'Capture Only screen size of player window using screen cordinates.\n Save to Default Pictures dictoary in System.\n Save in png format.\n '
print('[ ! SCREENSHOT ]')
wincen = Form.geometry()
topX = wincen.topLeft().x()
topY = wincen.topLeft().y()
geo = self.video_playback.geometry()
image = pyautogui.screenshot(region=(topX, (topY + 38), geo.width(), (geo.height() - 35)))
filename = (('screenshot' + str(uuid.uuid4())) + '.png')
username = getpass.getuser()
if (sys.platform == 'win32'):
path = ((('C:/Users/' + username) + '/Pictures/') + filename)
elif ((sys.platform == 'linux') or (sys.platform == 'Darwin')):
path = ((('/home/' + username) + '/Pictures/') + filename)
image.save(path) | def screenshot(self):
'Capture Only screen size of player window using screen cordinates.\n Save to Default Pictures dictoary in System.\n Save in png format.\n '
print('[ ! SCREENSHOT ]')
wincen = Form.geometry()
topX = wincen.topLeft().x()
topY = wincen.topLeft().y()
geo = self.video_playback.geometry()
image = pyautogui.screenshot(region=(topX, (topY + 38), geo.width(), (geo.height() - 35)))
filename = (('screenshot' + str(uuid.uuid4())) + '.png')
username = getpass.getuser()
if (sys.platform == 'win32'):
path = ((('C:/Users/' + username) + '/Pictures/') + filename)
elif ((sys.platform == 'linux') or (sys.platform == 'Darwin')):
path = ((('/home/' + username) + '/Pictures/') + filename)
image.save(path)<|docstring|>Capture Only screen size of player window using screen cordinates.
Save to Default Pictures dictoary in System.
Save in png format.<|endoftext|> |
258eca9c20c244c2a230e26a604bcb6bda628916d884034df759c338f79b06a3 | def EscFun(self):
'To disable FullScreen Mode'
if self.video_playback.isFullScreen():
Form.show()
self.video_playback.setFullScreen(False) | To disable FullScreen Mode | Player.py | EscFun | Ashuto7h/Q-Stream | 26 | python | def EscFun(self):
if self.video_playback.isFullScreen():
Form.show()
self.video_playback.setFullScreen(False) | def EscFun(self):
if self.video_playback.isFullScreen():
Form.show()
self.video_playback.setFullScreen(False)<|docstring|>To disable FullScreen Mode<|endoftext|> |
eb566c32318ad23913db95e399159693785a46962ce99a7b08cec93a9b98d9cc | def fullscreen_video(self):
'To get into Fullscreen Mode and Normal Mode'
if self.mediaPlayer.isVideoAvailable():
if self.video_playback.isFullScreen():
self.video_playback.setFullScreen(False)
print('[ ! Normal Screen ]')
Form.show()
else:
print('[ ! Full Screen ]')
self.video_playback.setFullScreen(True)
Form.hide() | To get into Fullscreen Mode and Normal Mode | Player.py | fullscreen_video | Ashuto7h/Q-Stream | 26 | python | def fullscreen_video(self):
if self.mediaPlayer.isVideoAvailable():
if self.video_playback.isFullScreen():
self.video_playback.setFullScreen(False)
print('[ ! Normal Screen ]')
Form.show()
else:
print('[ ! Full Screen ]')
self.video_playback.setFullScreen(True)
Form.hide() | def fullscreen_video(self):
if self.mediaPlayer.isVideoAvailable():
if self.video_playback.isFullScreen():
self.video_playback.setFullScreen(False)
print('[ ! Normal Screen ]')
Form.show()
else:
print('[ ! Full Screen ]')
self.video_playback.setFullScreen(True)
Form.hide()<|docstring|>To get into Fullscreen Mode and Normal Mode<|endoftext|> |
7161f2b35652a795139c08de271e6c7dfd3c32d7913ddf1df6f1b6bea5bfb16f | def getFormat(self):
'Remove the audio formates which are Recived by Youtube link ( if exists )'
li = list(self.streams.keys())
for q in li:
if q.startswith('audio'):
li.remove(q)
try:
li.remove('audio_opus')
except ValueError:
pass
return li | Remove the audio formates which are Recived by Youtube link ( if exists ) | Player.py | getFormat | Ashuto7h/Q-Stream | 26 | python | def getFormat(self):
li = list(self.streams.keys())
for q in li:
if q.startswith('audio'):
li.remove(q)
try:
li.remove('audio_opus')
except ValueError:
pass
return li | def getFormat(self):
li = list(self.streams.keys())
for q in li:
if q.startswith('audio'):
li.remove(q)
try:
li.remove('audio_opus')
except ValueError:
pass
return li<|docstring|>Remove the audio formates which are Recived by Youtube link ( if exists )<|endoftext|> |
6aed16bb61211409b65e29dfb61678848e27e27fee1bb9abec0004515ab207ee | def changeQuality(self, quality):
'To change Video Quality according to User need and maintain postion of video'
pos = self.mediaPlayer.position()
try:
self.mediaPlayer.setMedia(QMediaContent(QUrl(self.streams[quality])))
except KeyError:
pass
self.setPosition(pos)
self.mediaPlayer.play()
self.Quality_box.clearFocus() | To change Video Quality according to User need and maintain postion of video | Player.py | changeQuality | Ashuto7h/Q-Stream | 26 | python | def changeQuality(self, quality):
pos = self.mediaPlayer.position()
try:
self.mediaPlayer.setMedia(QMediaContent(QUrl(self.streams[quality])))
except KeyError:
pass
self.setPosition(pos)
self.mediaPlayer.play()
self.Quality_box.clearFocus() | def changeQuality(self, quality):
pos = self.mediaPlayer.position()
try:
self.mediaPlayer.setMedia(QMediaContent(QUrl(self.streams[quality])))
except KeyError:
pass
self.setPosition(pos)
self.mediaPlayer.play()
self.Quality_box.clearFocus()<|docstring|>To change Video Quality according to User need and maintain postion of video<|endoftext|> |
e11a70582b6a1aa939d1d92257d35a2ba36e08cb3db765933753b630fc0935a6 | def playlistWidget(self):
'Open Playlist Dialog Box'
from lib.playlist import Ui_Playlist
self.playlist_ui = Ui_Playlist(self.playlist)
self.playlist_ui.setupUi()
self.playlist_ui.loadData()
self.playlistTriggers()
self.playlist_ui.exec_() | Open Playlist Dialog Box | Player.py | playlistWidget | Ashuto7h/Q-Stream | 26 | python | def playlistWidget(self):
from lib.playlist import Ui_Playlist
self.playlist_ui = Ui_Playlist(self.playlist)
self.playlist_ui.setupUi()
self.playlist_ui.loadData()
self.playlistTriggers()
self.playlist_ui.exec_() | def playlistWidget(self):
from lib.playlist import Ui_Playlist
self.playlist_ui = Ui_Playlist(self.playlist)
self.playlist_ui.setupUi()
self.playlist_ui.loadData()
self.playlistTriggers()
self.playlist_ui.exec_()<|docstring|>Open Playlist Dialog Box<|endoftext|> |
497901730b447296cc53e3e0b063eba19ea1dfea155df81df4549f7bc271e9ff | @staticmethod
def handleSetting():
'Open Setting Dialog Box '
from lib.setting import SettingDialog
dlg = SettingDialog()
dlg.setWindowFlags((Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint))
dlg.exec_() | Open Setting Dialog Box | Player.py | handleSetting | Ashuto7h/Q-Stream | 26 | python | @staticmethod
def handleSetting():
' '
from lib.setting import SettingDialog
dlg = SettingDialog()
dlg.setWindowFlags((Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint))
dlg.exec_() | @staticmethod
def handleSetting():
' '
from lib.setting import SettingDialog
dlg = SettingDialog()
dlg.setWindowFlags((Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint))
dlg.exec_()<|docstring|>Open Setting Dialog Box<|endoftext|> |
012bc673f7268cf78c2c9d140f639a01bef2d4157adee6384783c4d2f9309af3 | def addQuality(self):
'Set DropDown menu of Video resolution available'
self.Quality_box.clear()
self.Quality_box.addItems(self.getFormat()) | Set DropDown menu of Video resolution available | Player.py | addQuality | Ashuto7h/Q-Stream | 26 | python | def addQuality(self):
self.Quality_box.clear()
self.Quality_box.addItems(self.getFormat()) | def addQuality(self):
self.Quality_box.clear()
self.Quality_box.addItems(self.getFormat())<|docstring|>Set DropDown menu of Video resolution available<|endoftext|> |
5ded4b30d437b73f053fe4ae69fce2c78f0e1d839659f612e8269ca92d3339b6 | def __init__(self, expected_returns, cov_matrix, weight_bounds=(0, 1), solver=None, verbose=False, solver_options=None):
'\n :param expected_returns: expected returns for each asset. Can be None if\n optimising for volatility only (but not recommended).\n :type expected_returns: pd.Series, list, np.ndarray\n :param cov_matrix: covariance of returns for each asset. This **must** be\n positive semidefinite, otherwise optimisation will fail.\n :type cov_matrix: pd.DataFrame or np.array\n :param weight_bounds: minimum and maximum weight of each asset OR single min/max pair\n if all identical, defaults to (0, 1). Must be changed to (-1, 1)\n for portfolios with shorting.\n :type weight_bounds: tuple OR tuple list, optional\n :param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`\n :type solver: str\n :param verbose: whether performance and debugging info should be printed, defaults to False\n :type verbose: bool, optional\n :param solver_options: parameters for the given solver\n :type solver_options: dict, optional\n :raises TypeError: if ``expected_returns`` is not a series, list or array\n :raises TypeError: if ``cov_matrix`` is not a dataframe or array\n '
self.cov_matrix = EfficientFrontier._validate_cov_matrix(cov_matrix)
self.expected_returns = EfficientFrontier._validate_expected_returns(expected_returns)
if isinstance(expected_returns, pd.Series):
tickers = list(expected_returns.index)
elif isinstance(cov_matrix, pd.DataFrame):
tickers = list(cov_matrix.columns)
else:
tickers = list(range(len(expected_returns)))
if ((expected_returns is not None) and (cov_matrix is not None)):
if (cov_matrix.shape != (len(expected_returns), len(expected_returns))):
raise ValueError('Covariance matrix does not match expected returns')
super().__init__(len(tickers), tickers, weight_bounds, solver=solver, verbose=verbose, solver_options=solver_options) | :param expected_returns: expected returns for each asset. Can be None if
optimising for volatility only (but not recommended).
:type expected_returns: pd.Series, list, np.ndarray
:param cov_matrix: covariance of returns for each asset. This **must** be
positive semidefinite, otherwise optimisation will fail.
:type cov_matrix: pd.DataFrame or np.array
:param weight_bounds: minimum and maximum weight of each asset OR single min/max pair
if all identical, defaults to (0, 1). Must be changed to (-1, 1)
for portfolios with shorting.
:type weight_bounds: tuple OR tuple list, optional
:param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`
:type solver: str
:param verbose: whether performance and debugging info should be printed, defaults to False
:type verbose: bool, optional
:param solver_options: parameters for the given solver
:type solver_options: dict, optional
:raises TypeError: if ``expected_returns`` is not a series, list or array
:raises TypeError: if ``cov_matrix`` is not a dataframe or array | pypfopt/efficient_frontier.py | __init__ | SeaPea1/PyPortfolioOpt | 1 | python | def __init__(self, expected_returns, cov_matrix, weight_bounds=(0, 1), solver=None, verbose=False, solver_options=None):
'\n :param expected_returns: expected returns for each asset. Can be None if\n optimising for volatility only (but not recommended).\n :type expected_returns: pd.Series, list, np.ndarray\n :param cov_matrix: covariance of returns for each asset. This **must** be\n positive semidefinite, otherwise optimisation will fail.\n :type cov_matrix: pd.DataFrame or np.array\n :param weight_bounds: minimum and maximum weight of each asset OR single min/max pair\n if all identical, defaults to (0, 1). Must be changed to (-1, 1)\n for portfolios with shorting.\n :type weight_bounds: tuple OR tuple list, optional\n :param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`\n :type solver: str\n :param verbose: whether performance and debugging info should be printed, defaults to False\n :type verbose: bool, optional\n :param solver_options: parameters for the given solver\n :type solver_options: dict, optional\n :raises TypeError: if ``expected_returns`` is not a series, list or array\n :raises TypeError: if ``cov_matrix`` is not a dataframe or array\n '
self.cov_matrix = EfficientFrontier._validate_cov_matrix(cov_matrix)
self.expected_returns = EfficientFrontier._validate_expected_returns(expected_returns)
if isinstance(expected_returns, pd.Series):
tickers = list(expected_returns.index)
elif isinstance(cov_matrix, pd.DataFrame):
tickers = list(cov_matrix.columns)
else:
tickers = list(range(len(expected_returns)))
if ((expected_returns is not None) and (cov_matrix is not None)):
if (cov_matrix.shape != (len(expected_returns), len(expected_returns))):
raise ValueError('Covariance matrix does not match expected returns')
super().__init__(len(tickers), tickers, weight_bounds, solver=solver, verbose=verbose, solver_options=solver_options) | def __init__(self, expected_returns, cov_matrix, weight_bounds=(0, 1), solver=None, verbose=False, solver_options=None):
'\n :param expected_returns: expected returns for each asset. Can be None if\n optimising for volatility only (but not recommended).\n :type expected_returns: pd.Series, list, np.ndarray\n :param cov_matrix: covariance of returns for each asset. This **must** be\n positive semidefinite, otherwise optimisation will fail.\n :type cov_matrix: pd.DataFrame or np.array\n :param weight_bounds: minimum and maximum weight of each asset OR single min/max pair\n if all identical, defaults to (0, 1). Must be changed to (-1, 1)\n for portfolios with shorting.\n :type weight_bounds: tuple OR tuple list, optional\n :param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`\n :type solver: str\n :param verbose: whether performance and debugging info should be printed, defaults to False\n :type verbose: bool, optional\n :param solver_options: parameters for the given solver\n :type solver_options: dict, optional\n :raises TypeError: if ``expected_returns`` is not a series, list or array\n :raises TypeError: if ``cov_matrix`` is not a dataframe or array\n '
self.cov_matrix = EfficientFrontier._validate_cov_matrix(cov_matrix)
self.expected_returns = EfficientFrontier._validate_expected_returns(expected_returns)
if isinstance(expected_returns, pd.Series):
tickers = list(expected_returns.index)
elif isinstance(cov_matrix, pd.DataFrame):
tickers = list(cov_matrix.columns)
else:
tickers = list(range(len(expected_returns)))
if ((expected_returns is not None) and (cov_matrix is not None)):
if (cov_matrix.shape != (len(expected_returns), len(expected_returns))):
raise ValueError('Covariance matrix does not match expected returns')
super().__init__(len(tickers), tickers, weight_bounds, solver=solver, verbose=verbose, solver_options=solver_options)<|docstring|>:param expected_returns: expected returns for each asset. Can be None if
optimising for volatility only (but not recommended).
:type expected_returns: pd.Series, list, np.ndarray
:param cov_matrix: covariance of returns for each asset. This **must** be
positive semidefinite, otherwise optimisation will fail.
:type cov_matrix: pd.DataFrame or np.array
:param weight_bounds: minimum and maximum weight of each asset OR single min/max pair
if all identical, defaults to (0, 1). Must be changed to (-1, 1)
for portfolios with shorting.
:type weight_bounds: tuple OR tuple list, optional
:param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`
:type solver: str
:param verbose: whether performance and debugging info should be printed, defaults to False
:type verbose: bool, optional
:param solver_options: parameters for the given solver
:type solver_options: dict, optional
:raises TypeError: if ``expected_returns`` is not a series, list or array
:raises TypeError: if ``cov_matrix`` is not a dataframe or array<|endoftext|> |
5c32d0e275dbfe1aeb383784d38a879c3f06cb7b1082b277ac883221d291cd7c | def _validate_returns(self, returns):
'\n Helper method to validate daily returns (needed for some efficient frontiers)\n '
if (not isinstance(returns, (pd.DataFrame, np.ndarray))):
raise TypeError('returns should be a pd.Dataframe or np.ndarray')
returns_df = pd.DataFrame(returns)
if returns_df.isnull().values.any():
warnings.warn('Removing NaNs from returns', UserWarning)
returns_df = returns_df.dropna(axis=0, how='any')
if (self.expected_returns is not None):
if (returns_df.shape[1] != len(self.expected_returns)):
raise ValueError('returns columns do not match expected_returns. Please check your tickers.')
return returns_df | Helper method to validate daily returns (needed for some efficient frontiers) | pypfopt/efficient_frontier.py | _validate_returns | SeaPea1/PyPortfolioOpt | 1 | python | def _validate_returns(self, returns):
'\n \n '
if (not isinstance(returns, (pd.DataFrame, np.ndarray))):
raise TypeError('returns should be a pd.Dataframe or np.ndarray')
returns_df = pd.DataFrame(returns)
if returns_df.isnull().values.any():
warnings.warn('Removing NaNs from returns', UserWarning)
returns_df = returns_df.dropna(axis=0, how='any')
if (self.expected_returns is not None):
if (returns_df.shape[1] != len(self.expected_returns)):
raise ValueError('returns columns do not match expected_returns. Please check your tickers.')
return returns_df | def _validate_returns(self, returns):
'\n \n '
if (not isinstance(returns, (pd.DataFrame, np.ndarray))):
raise TypeError('returns should be a pd.Dataframe or np.ndarray')
returns_df = pd.DataFrame(returns)
if returns_df.isnull().values.any():
warnings.warn('Removing NaNs from returns', UserWarning)
returns_df = returns_df.dropna(axis=0, how='any')
if (self.expected_returns is not None):
if (returns_df.shape[1] != len(self.expected_returns)):
raise ValueError('returns columns do not match expected_returns. Please check your tickers.')
return returns_df<|docstring|>Helper method to validate daily returns (needed for some efficient frontiers)<|endoftext|> |
b40ab6dad480f9f6831e2c8947658c416da3f10ea5ac496e001de8e80df3d859 | def _make_weight_sum_constraint(self, is_market_neutral):
'\n Helper method to make the weight sum constraint. If market neutral,\n validate the weights proided in the constructor.\n '
if is_market_neutral:
portfolio_possible = np.any((self._lower_bounds < 0))
if (not portfolio_possible):
warnings.warn('Market neutrality requires shorting - bounds have been amended', RuntimeWarning)
self._map_bounds_to_constraints(((- 1), 1))
del self._constraints[0]
del self._constraints[0]
self._constraints.append((cp.sum(self._w) == 0))
else:
self._constraints.append((cp.sum(self._w) == 1)) | Helper method to make the weight sum constraint. If market neutral,
validate the weights proided in the constructor. | pypfopt/efficient_frontier.py | _make_weight_sum_constraint | SeaPea1/PyPortfolioOpt | 1 | python | def _make_weight_sum_constraint(self, is_market_neutral):
'\n Helper method to make the weight sum constraint. If market neutral,\n validate the weights proided in the constructor.\n '
if is_market_neutral:
portfolio_possible = np.any((self._lower_bounds < 0))
if (not portfolio_possible):
warnings.warn('Market neutrality requires shorting - bounds have been amended', RuntimeWarning)
self._map_bounds_to_constraints(((- 1), 1))
del self._constraints[0]
del self._constraints[0]
self._constraints.append((cp.sum(self._w) == 0))
else:
self._constraints.append((cp.sum(self._w) == 1)) | def _make_weight_sum_constraint(self, is_market_neutral):
'\n Helper method to make the weight sum constraint. If market neutral,\n validate the weights proided in the constructor.\n '
if is_market_neutral:
portfolio_possible = np.any((self._lower_bounds < 0))
if (not portfolio_possible):
warnings.warn('Market neutrality requires shorting - bounds have been amended', RuntimeWarning)
self._map_bounds_to_constraints(((- 1), 1))
del self._constraints[0]
del self._constraints[0]
self._constraints.append((cp.sum(self._w) == 0))
else:
self._constraints.append((cp.sum(self._w) == 1))<|docstring|>Helper method to make the weight sum constraint. If market neutral,
validate the weights proided in the constructor.<|endoftext|> |
b2eb5b695b7661267e4ddc7479c7bb1185cf23016b2b89e4d530f2a80f2fa7f4 | def min_volatility(self):
'\n Minimise volatility.\n\n :return: asset weights for the volatility-minimising portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_variance(self._w, self.cov_matrix)
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((cp.sum(self._w) == 1))
return self._solve_cvxpy_opt_problem() | Minimise volatility.
:return: asset weights for the volatility-minimising portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | min_volatility | SeaPea1/PyPortfolioOpt | 1 | python | def min_volatility(self):
'\n Minimise volatility.\n\n :return: asset weights for the volatility-minimising portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_variance(self._w, self.cov_matrix)
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((cp.sum(self._w) == 1))
return self._solve_cvxpy_opt_problem() | def min_volatility(self):
'\n Minimise volatility.\n\n :return: asset weights for the volatility-minimising portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_variance(self._w, self.cov_matrix)
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((cp.sum(self._w) == 1))
return self._solve_cvxpy_opt_problem()<|docstring|>Minimise volatility.
:return: asset weights for the volatility-minimising portfolio
:rtype: OrderedDict<|endoftext|> |
64324c697cd0c01213472a25cfe0692992601362cf456da1589a81ad5065a31d | def _max_return(self, return_value=True):
'\n Helper method to maximise return. This should not be used to optimise a portfolio.\n\n :return: asset weights for the return-minimising portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
self._constraints.append((cp.sum(self._w) == 1))
res = self._solve_cvxpy_opt_problem()
del self._constraints[(- 1)]
if return_value:
return (- self._opt.value)
else:
return res | Helper method to maximise return. This should not be used to optimise a portfolio.
:return: asset weights for the return-minimising portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | _max_return | SeaPea1/PyPortfolioOpt | 1 | python | def _max_return(self, return_value=True):
'\n Helper method to maximise return. This should not be used to optimise a portfolio.\n\n :return: asset weights for the return-minimising portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
self._constraints.append((cp.sum(self._w) == 1))
res = self._solve_cvxpy_opt_problem()
del self._constraints[(- 1)]
if return_value:
return (- self._opt.value)
else:
return res | def _max_return(self, return_value=True):
'\n Helper method to maximise return. This should not be used to optimise a portfolio.\n\n :return: asset weights for the return-minimising portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
self._constraints.append((cp.sum(self._w) == 1))
res = self._solve_cvxpy_opt_problem()
del self._constraints[(- 1)]
if return_value:
return (- self._opt.value)
else:
return res<|docstring|>Helper method to maximise return. This should not be used to optimise a portfolio.
:return: asset weights for the return-minimising portfolio
:rtype: OrderedDict<|endoftext|> |
2a5265f2d28d65f9c8d6f3a1c4ee9fdbd3259f22904133372bddb285ccdf4454 | def max_sharpe(self, risk_free_rate=0.02):
'\n Maximise the Sharpe Ratio. The result is also referred to as the tangency portfolio,\n as it is the portfolio for which the capital market line is tangent to the efficient frontier.\n\n This is a convex optimisation problem after making a certain variable substitution. See\n `Cornuejols and Tutuncu (2006) <http://web.math.ku.dk/~rolf/CT_FinOpt.pdf>`_ for more.\n\n :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.\n The period of the risk-free rate should correspond to the\n frequency of expected returns.\n :type risk_free_rate: float, optional\n :raises ValueError: if ``risk_free_rate`` is non-numeric\n :return: asset weights for the Sharpe-maximising portfolio\n :rtype: OrderedDict\n '
if (not isinstance(risk_free_rate, (int, float))):
raise ValueError('risk_free_rate should be numeric')
self._risk_free_rate = risk_free_rate
self._objective = cp.quad_form(self._w, self.cov_matrix)
k = cp.Variable()
if (len(self._additional_objectives) > 0):
warnings.warn('max_sharpe transforms the optimisation problem so additional objectives may not work as expected.')
for obj in self._additional_objectives:
self._objective += obj
new_constraints = []
for constr in self._constraints:
if isinstance(constr, cp.constraints.nonpos.Inequality):
if isinstance(constr.args[0], cp.expressions.constants.constant.Constant):
new_constraints.append((constr.args[1] >= (constr.args[0] * k)))
else:
new_constraints.append((constr.args[0] <= (constr.args[1] * k)))
elif isinstance(constr, cp.constraints.zero.Equality):
new_constraints.append((constr.args[0] == (constr.args[1] * k)))
else:
raise TypeError('Please check that your constraints are in a suitable format')
self._constraints = ([(((self.expected_returns - risk_free_rate).T @ self._w) == 1), (cp.sum(self._w) == k), (k >= 0)] + new_constraints)
self._solve_cvxpy_opt_problem()
self.weights = ((self._w.value / k.value).round(16) + 0.0)
return self._make_output_weights() | Maximise the Sharpe Ratio. The result is also referred to as the tangency portfolio,
as it is the portfolio for which the capital market line is tangent to the efficient frontier.
This is a convex optimisation problem after making a certain variable substitution. See
`Cornuejols and Tutuncu (2006) <http://web.math.ku.dk/~rolf/CT_FinOpt.pdf>`_ for more.
:param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.
The period of the risk-free rate should correspond to the
frequency of expected returns.
:type risk_free_rate: float, optional
:raises ValueError: if ``risk_free_rate`` is non-numeric
:return: asset weights for the Sharpe-maximising portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | max_sharpe | SeaPea1/PyPortfolioOpt | 1 | python | def max_sharpe(self, risk_free_rate=0.02):
'\n Maximise the Sharpe Ratio. The result is also referred to as the tangency portfolio,\n as it is the portfolio for which the capital market line is tangent to the efficient frontier.\n\n This is a convex optimisation problem after making a certain variable substitution. See\n `Cornuejols and Tutuncu (2006) <http://web.math.ku.dk/~rolf/CT_FinOpt.pdf>`_ for more.\n\n :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.\n The period of the risk-free rate should correspond to the\n frequency of expected returns.\n :type risk_free_rate: float, optional\n :raises ValueError: if ``risk_free_rate`` is non-numeric\n :return: asset weights for the Sharpe-maximising portfolio\n :rtype: OrderedDict\n '
if (not isinstance(risk_free_rate, (int, float))):
raise ValueError('risk_free_rate should be numeric')
self._risk_free_rate = risk_free_rate
self._objective = cp.quad_form(self._w, self.cov_matrix)
k = cp.Variable()
if (len(self._additional_objectives) > 0):
warnings.warn('max_sharpe transforms the optimisation problem so additional objectives may not work as expected.')
for obj in self._additional_objectives:
self._objective += obj
new_constraints = []
for constr in self._constraints:
if isinstance(constr, cp.constraints.nonpos.Inequality):
if isinstance(constr.args[0], cp.expressions.constants.constant.Constant):
new_constraints.append((constr.args[1] >= (constr.args[0] * k)))
else:
new_constraints.append((constr.args[0] <= (constr.args[1] * k)))
elif isinstance(constr, cp.constraints.zero.Equality):
new_constraints.append((constr.args[0] == (constr.args[1] * k)))
else:
raise TypeError('Please check that your constraints are in a suitable format')
self._constraints = ([(((self.expected_returns - risk_free_rate).T @ self._w) == 1), (cp.sum(self._w) == k), (k >= 0)] + new_constraints)
self._solve_cvxpy_opt_problem()
self.weights = ((self._w.value / k.value).round(16) + 0.0)
return self._make_output_weights() | def max_sharpe(self, risk_free_rate=0.02):
'\n Maximise the Sharpe Ratio. The result is also referred to as the tangency portfolio,\n as it is the portfolio for which the capital market line is tangent to the efficient frontier.\n\n This is a convex optimisation problem after making a certain variable substitution. See\n `Cornuejols and Tutuncu (2006) <http://web.math.ku.dk/~rolf/CT_FinOpt.pdf>`_ for more.\n\n :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.\n The period of the risk-free rate should correspond to the\n frequency of expected returns.\n :type risk_free_rate: float, optional\n :raises ValueError: if ``risk_free_rate`` is non-numeric\n :return: asset weights for the Sharpe-maximising portfolio\n :rtype: OrderedDict\n '
if (not isinstance(risk_free_rate, (int, float))):
raise ValueError('risk_free_rate should be numeric')
self._risk_free_rate = risk_free_rate
self._objective = cp.quad_form(self._w, self.cov_matrix)
k = cp.Variable()
if (len(self._additional_objectives) > 0):
warnings.warn('max_sharpe transforms the optimisation problem so additional objectives may not work as expected.')
for obj in self._additional_objectives:
self._objective += obj
new_constraints = []
for constr in self._constraints:
if isinstance(constr, cp.constraints.nonpos.Inequality):
if isinstance(constr.args[0], cp.expressions.constants.constant.Constant):
new_constraints.append((constr.args[1] >= (constr.args[0] * k)))
else:
new_constraints.append((constr.args[0] <= (constr.args[1] * k)))
elif isinstance(constr, cp.constraints.zero.Equality):
new_constraints.append((constr.args[0] == (constr.args[1] * k)))
else:
raise TypeError('Please check that your constraints are in a suitable format')
self._constraints = ([(((self.expected_returns - risk_free_rate).T @ self._w) == 1), (cp.sum(self._w) == k), (k >= 0)] + new_constraints)
self._solve_cvxpy_opt_problem()
self.weights = ((self._w.value / k.value).round(16) + 0.0)
return self._make_output_weights()<|docstring|>Maximise the Sharpe Ratio. The result is also referred to as the tangency portfolio,
as it is the portfolio for which the capital market line is tangent to the efficient frontier.
This is a convex optimisation problem after making a certain variable substitution. See
`Cornuejols and Tutuncu (2006) <http://web.math.ku.dk/~rolf/CT_FinOpt.pdf>`_ for more.
:param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.
The period of the risk-free rate should correspond to the
frequency of expected returns.
:type risk_free_rate: float, optional
:raises ValueError: if ``risk_free_rate`` is non-numeric
:return: asset weights for the Sharpe-maximising portfolio
:rtype: OrderedDict<|endoftext|> |
cfac69a03a65c1f172b3c40ad2402e6d8996d4d5393356b8fda1618a21d96b0b | def max_quadratic_utility(self, risk_aversion=1, market_neutral=False):
'\n Maximise the given quadratic utility, i.e:\n\n .. math::\n\n \\max_w w^T \\mu - \\frac \\delta 2 w^T \\Sigma w\n\n :param risk_aversion: risk aversion parameter (must be greater than 0),\n defaults to 1\n :type risk_aversion: positive float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the maximum-utility portfolio\n :rtype: OrderedDict\n '
if (risk_aversion <= 0):
raise ValueError('risk aversion coefficient must be greater than zero')
self._objective = objective_functions.quadratic_utility(self._w, self.expected_returns, self.cov_matrix, risk_aversion=risk_aversion)
for obj in self._additional_objectives:
self._objective += obj
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | Maximise the given quadratic utility, i.e:
.. math::
\max_w w^T \mu - \frac \delta 2 w^T \Sigma w
:param risk_aversion: risk aversion parameter (must be greater than 0),
defaults to 1
:type risk_aversion: positive float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the maximum-utility portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | max_quadratic_utility | SeaPea1/PyPortfolioOpt | 1 | python | def max_quadratic_utility(self, risk_aversion=1, market_neutral=False):
'\n Maximise the given quadratic utility, i.e:\n\n .. math::\n\n \\max_w w^T \\mu - \\frac \\delta 2 w^T \\Sigma w\n\n :param risk_aversion: risk aversion parameter (must be greater than 0),\n defaults to 1\n :type risk_aversion: positive float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the maximum-utility portfolio\n :rtype: OrderedDict\n '
if (risk_aversion <= 0):
raise ValueError('risk aversion coefficient must be greater than zero')
self._objective = objective_functions.quadratic_utility(self._w, self.expected_returns, self.cov_matrix, risk_aversion=risk_aversion)
for obj in self._additional_objectives:
self._objective += obj
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | def max_quadratic_utility(self, risk_aversion=1, market_neutral=False):
'\n Maximise the given quadratic utility, i.e:\n\n .. math::\n\n \\max_w w^T \\mu - \\frac \\delta 2 w^T \\Sigma w\n\n :param risk_aversion: risk aversion parameter (must be greater than 0),\n defaults to 1\n :type risk_aversion: positive float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the maximum-utility portfolio\n :rtype: OrderedDict\n '
if (risk_aversion <= 0):
raise ValueError('risk aversion coefficient must be greater than zero')
self._objective = objective_functions.quadratic_utility(self._w, self.expected_returns, self.cov_matrix, risk_aversion=risk_aversion)
for obj in self._additional_objectives:
self._objective += obj
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem()<|docstring|>Maximise the given quadratic utility, i.e:
.. math::
\max_w w^T \mu - \frac \delta 2 w^T \Sigma w
:param risk_aversion: risk aversion parameter (must be greater than 0),
defaults to 1
:type risk_aversion: positive float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the maximum-utility portfolio
:rtype: OrderedDict<|endoftext|> |
2872be0f3aa392f4317a7a8dab1649897c769baee2588b50c5e0e091cad8b20c | def efficient_risk(self, target_volatility, market_neutral=False):
'\n Maximise return for a target risk. The resulting portfolio will have a volatility\n less than the target (but not guaranteed to be equal).\n\n :param target_volatility: the desired maximum volatility of the resulting portfolio.\n :type target_volatility: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :raises ValueError: if ``target_volatility`` is not a positive float\n :raises ValueError: if no portfolio can be found with volatility equal to ``target_volatility``\n :raises ValueError: if ``risk_free_rate`` is non-numeric\n :return: asset weights for the efficient risk portfolio\n :rtype: OrderedDict\n '
if ((not isinstance(target_volatility, (float, int))) or (target_volatility < 0)):
raise ValueError('target_volatility should be a positive float')
global_min_volatility = np.sqrt((1 / np.sum(np.linalg.inv(self.cov_matrix))))
if (target_volatility < global_min_volatility):
raise ValueError('The minimum volatility is {:.3f}. Please use a higher target_volatility'.format(global_min_volatility))
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
variance = objective_functions.portfolio_variance(self._w, self.cov_matrix)
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((variance <= (target_volatility ** 2)))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | Maximise return for a target risk. The resulting portfolio will have a volatility
less than the target (but not guaranteed to be equal).
:param target_volatility: the desired maximum volatility of the resulting portfolio.
:type target_volatility: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:raises ValueError: if ``target_volatility`` is not a positive float
:raises ValueError: if no portfolio can be found with volatility equal to ``target_volatility``
:raises ValueError: if ``risk_free_rate`` is non-numeric
:return: asset weights for the efficient risk portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | efficient_risk | SeaPea1/PyPortfolioOpt | 1 | python | def efficient_risk(self, target_volatility, market_neutral=False):
'\n Maximise return for a target risk. The resulting portfolio will have a volatility\n less than the target (but not guaranteed to be equal).\n\n :param target_volatility: the desired maximum volatility of the resulting portfolio.\n :type target_volatility: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :raises ValueError: if ``target_volatility`` is not a positive float\n :raises ValueError: if no portfolio can be found with volatility equal to ``target_volatility``\n :raises ValueError: if ``risk_free_rate`` is non-numeric\n :return: asset weights for the efficient risk portfolio\n :rtype: OrderedDict\n '
if ((not isinstance(target_volatility, (float, int))) or (target_volatility < 0)):
raise ValueError('target_volatility should be a positive float')
global_min_volatility = np.sqrt((1 / np.sum(np.linalg.inv(self.cov_matrix))))
if (target_volatility < global_min_volatility):
raise ValueError('The minimum volatility is {:.3f}. Please use a higher target_volatility'.format(global_min_volatility))
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
variance = objective_functions.portfolio_variance(self._w, self.cov_matrix)
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((variance <= (target_volatility ** 2)))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | def efficient_risk(self, target_volatility, market_neutral=False):
'\n Maximise return for a target risk. The resulting portfolio will have a volatility\n less than the target (but not guaranteed to be equal).\n\n :param target_volatility: the desired maximum volatility of the resulting portfolio.\n :type target_volatility: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :raises ValueError: if ``target_volatility`` is not a positive float\n :raises ValueError: if no portfolio can be found with volatility equal to ``target_volatility``\n :raises ValueError: if ``risk_free_rate`` is non-numeric\n :return: asset weights for the efficient risk portfolio\n :rtype: OrderedDict\n '
if ((not isinstance(target_volatility, (float, int))) or (target_volatility < 0)):
raise ValueError('target_volatility should be a positive float')
global_min_volatility = np.sqrt((1 / np.sum(np.linalg.inv(self.cov_matrix))))
if (target_volatility < global_min_volatility):
raise ValueError('The minimum volatility is {:.3f}. Please use a higher target_volatility'.format(global_min_volatility))
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
variance = objective_functions.portfolio_variance(self._w, self.cov_matrix)
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((variance <= (target_volatility ** 2)))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem()<|docstring|>Maximise return for a target risk. The resulting portfolio will have a volatility
less than the target (but not guaranteed to be equal).
:param target_volatility: the desired maximum volatility of the resulting portfolio.
:type target_volatility: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:raises ValueError: if ``target_volatility`` is not a positive float
:raises ValueError: if no portfolio can be found with volatility equal to ``target_volatility``
:raises ValueError: if ``risk_free_rate`` is non-numeric
:return: asset weights for the efficient risk portfolio
:rtype: OrderedDict<|endoftext|> |
7247cafe2ea8ee4266044dc8b35476915e0547a78061351bb5f74c37e9e171eb | def efficient_return(self, target_return, market_neutral=False):
"\n Calculate the 'Markowitz portfolio', minimising volatility for a given target return.\n\n :param target_return: the desired return of the resulting portfolio.\n :type target_return: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :type market_neutral: bool, optional\n :raises ValueError: if ``target_return`` is not a positive float\n :raises ValueError: if no portfolio can be found with return equal to ``target_return``\n :return: asset weights for the Markowitz portfolio\n :rtype: OrderedDict\n "
if ((not isinstance(target_return, float)) or (target_return < 0)):
raise ValueError('target_return should be a positive float')
if (target_return > self._max_return()):
raise ValueError('target_return must be lower than the maximum possible return')
self._objective = objective_functions.portfolio_variance(self._w, self.cov_matrix)
ret = objective_functions.portfolio_return(self._w, self.expected_returns, negative=False)
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((ret >= target_return))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | Calculate the 'Markowitz portfolio', minimising volatility for a given target return.
:param target_return: the desired return of the resulting portfolio.
:type target_return: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:type market_neutral: bool, optional
:raises ValueError: if ``target_return`` is not a positive float
:raises ValueError: if no portfolio can be found with return equal to ``target_return``
:return: asset weights for the Markowitz portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | efficient_return | SeaPea1/PyPortfolioOpt | 1 | python | def efficient_return(self, target_return, market_neutral=False):
"\n Calculate the 'Markowitz portfolio', minimising volatility for a given target return.\n\n :param target_return: the desired return of the resulting portfolio.\n :type target_return: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :type market_neutral: bool, optional\n :raises ValueError: if ``target_return`` is not a positive float\n :raises ValueError: if no portfolio can be found with return equal to ``target_return``\n :return: asset weights for the Markowitz portfolio\n :rtype: OrderedDict\n "
if ((not isinstance(target_return, float)) or (target_return < 0)):
raise ValueError('target_return should be a positive float')
if (target_return > self._max_return()):
raise ValueError('target_return must be lower than the maximum possible return')
self._objective = objective_functions.portfolio_variance(self._w, self.cov_matrix)
ret = objective_functions.portfolio_return(self._w, self.expected_returns, negative=False)
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((ret >= target_return))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | def efficient_return(self, target_return, market_neutral=False):
"\n Calculate the 'Markowitz portfolio', minimising volatility for a given target return.\n\n :param target_return: the desired return of the resulting portfolio.\n :type target_return: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :type market_neutral: bool, optional\n :raises ValueError: if ``target_return`` is not a positive float\n :raises ValueError: if no portfolio can be found with return equal to ``target_return``\n :return: asset weights for the Markowitz portfolio\n :rtype: OrderedDict\n "
if ((not isinstance(target_return, float)) or (target_return < 0)):
raise ValueError('target_return should be a positive float')
if (target_return > self._max_return()):
raise ValueError('target_return must be lower than the maximum possible return')
self._objective = objective_functions.portfolio_variance(self._w, self.cov_matrix)
ret = objective_functions.portfolio_return(self._w, self.expected_returns, negative=False)
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((ret >= target_return))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem()<|docstring|>Calculate the 'Markowitz portfolio', minimising volatility for a given target return.
:param target_return: the desired return of the resulting portfolio.
:type target_return: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:type market_neutral: bool, optional
:raises ValueError: if ``target_return`` is not a positive float
:raises ValueError: if no portfolio can be found with return equal to ``target_return``
:return: asset weights for the Markowitz portfolio
:rtype: OrderedDict<|endoftext|> |
ac8bc1593c39397185d1fbd7484bd85e67942126cfa4a566c65092b4893d5ea5 | def portfolio_performance(self, verbose=False, risk_free_rate=0.02):
'\n After optimising, calculate (and optionally print) the performance of the optimal\n portfolio. Currently calculates expected return, volatility, and the Sharpe ratio.\n\n :param verbose: whether performance should be printed, defaults to False\n :type verbose: bool, optional\n :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.\n The period of the risk-free rate should correspond to the\n frequency of expected returns.\n :type risk_free_rate: float, optional\n :raises ValueError: if weights have not been calcualted yet\n :return: expected return, volatility, Sharpe ratio.\n :rtype: (float, float, float)\n '
if (self._risk_free_rate is not None):
if (risk_free_rate != self._risk_free_rate):
warnings.warn('The risk_free_rate provided to portfolio_performance is different to the one used by max_sharpe. Using the previous value.', UserWarning)
risk_free_rate = self._risk_free_rate
return base_optimizer.portfolio_performance(self.weights, self.expected_returns, self.cov_matrix, verbose, risk_free_rate) | After optimising, calculate (and optionally print) the performance of the optimal
portfolio. Currently calculates expected return, volatility, and the Sharpe ratio.
:param verbose: whether performance should be printed, defaults to False
:type verbose: bool, optional
:param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.
The period of the risk-free rate should correspond to the
frequency of expected returns.
:type risk_free_rate: float, optional
:raises ValueError: if weights have not been calcualted yet
:return: expected return, volatility, Sharpe ratio.
:rtype: (float, float, float) | pypfopt/efficient_frontier.py | portfolio_performance | SeaPea1/PyPortfolioOpt | 1 | python | def portfolio_performance(self, verbose=False, risk_free_rate=0.02):
'\n After optimising, calculate (and optionally print) the performance of the optimal\n portfolio. Currently calculates expected return, volatility, and the Sharpe ratio.\n\n :param verbose: whether performance should be printed, defaults to False\n :type verbose: bool, optional\n :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.\n The period of the risk-free rate should correspond to the\n frequency of expected returns.\n :type risk_free_rate: float, optional\n :raises ValueError: if weights have not been calcualted yet\n :return: expected return, volatility, Sharpe ratio.\n :rtype: (float, float, float)\n '
if (self._risk_free_rate is not None):
if (risk_free_rate != self._risk_free_rate):
warnings.warn('The risk_free_rate provided to portfolio_performance is different to the one used by max_sharpe. Using the previous value.', UserWarning)
risk_free_rate = self._risk_free_rate
return base_optimizer.portfolio_performance(self.weights, self.expected_returns, self.cov_matrix, verbose, risk_free_rate) | def portfolio_performance(self, verbose=False, risk_free_rate=0.02):
'\n After optimising, calculate (and optionally print) the performance of the optimal\n portfolio. Currently calculates expected return, volatility, and the Sharpe ratio.\n\n :param verbose: whether performance should be printed, defaults to False\n :type verbose: bool, optional\n :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.\n The period of the risk-free rate should correspond to the\n frequency of expected returns.\n :type risk_free_rate: float, optional\n :raises ValueError: if weights have not been calcualted yet\n :return: expected return, volatility, Sharpe ratio.\n :rtype: (float, float, float)\n '
if (self._risk_free_rate is not None):
if (risk_free_rate != self._risk_free_rate):
warnings.warn('The risk_free_rate provided to portfolio_performance is different to the one used by max_sharpe. Using the previous value.', UserWarning)
risk_free_rate = self._risk_free_rate
return base_optimizer.portfolio_performance(self.weights, self.expected_returns, self.cov_matrix, verbose, risk_free_rate)<|docstring|>After optimising, calculate (and optionally print) the performance of the optimal
portfolio. Currently calculates expected return, volatility, and the Sharpe ratio.
:param verbose: whether performance should be printed, defaults to False
:type verbose: bool, optional
:param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.
The period of the risk-free rate should correspond to the
frequency of expected returns.
:type risk_free_rate: float, optional
:raises ValueError: if weights have not been calcualted yet
:return: expected return, volatility, Sharpe ratio.
:rtype: (float, float, float)<|endoftext|> |
b63492d128056b675ed1bde580bad6be66b29e6dba1f6dfe64f06c37031e2db3 | def __init__(self, expected_returns, returns, frequency=252, benchmark=0, weight_bounds=(0, 1), solver=None, verbose=False, solver_options=None):
'\n :param expected_returns: expected returns for each asset. Can be None if\n optimising for semideviation only.\n :type expected_returns: pd.Series, list, np.ndarray\n :param returns: (historic) returns for all your assets (no NaNs).\n See ``expected_returns.returns_from_prices``.\n :type returns: pd.DataFrame or np.array\n :param frequency: number of time periods in a year, defaults to 252 (the number\n of trading days in a year). This must agree with the frequency\n parameter used in your ``expected_returns``.\n :type frequency: int, optional\n :param benchmark: the return threshold to distinguish "downside" and "upside".\n This should match the frequency of your ``returns``,\n i.e this should be a benchmark daily returns if your\n ``returns`` are also daily.\n :param weight_bounds: minimum and maximum weight of each asset OR single min/max pair\n if all identical, defaults to (0, 1). Must be changed to (-1, 1)\n for portfolios with shorting.\n :type weight_bounds: tuple OR tuple list, optional\n :param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`\n :type solver: str\n :param verbose: whether performance and debugging info should be printed, defaults to False\n :type verbose: bool, optional\n :param solver_options: parameters for the given solver\n :type solver_options: dict, optional\n :raises TypeError: if ``expected_returns`` is not a series, list or array\n '
super().__init__(expected_returns=expected_returns, cov_matrix=np.zeros(((len(expected_returns),) * 2)), weight_bounds=weight_bounds, solver=solver, verbose=verbose, solver_options=solver_options)
self.returns = self._validate_returns(returns)
self.benchmark = benchmark
self.frequency = frequency
self._T = self.returns.shape[0] | :param expected_returns: expected returns for each asset. Can be None if
optimising for semideviation only.
:type expected_returns: pd.Series, list, np.ndarray
:param returns: (historic) returns for all your assets (no NaNs).
See ``expected_returns.returns_from_prices``.
:type returns: pd.DataFrame or np.array
:param frequency: number of time periods in a year, defaults to 252 (the number
of trading days in a year). This must agree with the frequency
parameter used in your ``expected_returns``.
:type frequency: int, optional
:param benchmark: the return threshold to distinguish "downside" and "upside".
This should match the frequency of your ``returns``,
i.e this should be a benchmark daily returns if your
``returns`` are also daily.
:param weight_bounds: minimum and maximum weight of each asset OR single min/max pair
if all identical, defaults to (0, 1). Must be changed to (-1, 1)
for portfolios with shorting.
:type weight_bounds: tuple OR tuple list, optional
:param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`
:type solver: str
:param verbose: whether performance and debugging info should be printed, defaults to False
:type verbose: bool, optional
:param solver_options: parameters for the given solver
:type solver_options: dict, optional
:raises TypeError: if ``expected_returns`` is not a series, list or array | pypfopt/efficient_frontier.py | __init__ | SeaPea1/PyPortfolioOpt | 1 | python | def __init__(self, expected_returns, returns, frequency=252, benchmark=0, weight_bounds=(0, 1), solver=None, verbose=False, solver_options=None):
'\n :param expected_returns: expected returns for each asset. Can be None if\n optimising for semideviation only.\n :type expected_returns: pd.Series, list, np.ndarray\n :param returns: (historic) returns for all your assets (no NaNs).\n See ``expected_returns.returns_from_prices``.\n :type returns: pd.DataFrame or np.array\n :param frequency: number of time periods in a year, defaults to 252 (the number\n of trading days in a year). This must agree with the frequency\n parameter used in your ``expected_returns``.\n :type frequency: int, optional\n :param benchmark: the return threshold to distinguish "downside" and "upside".\n This should match the frequency of your ``returns``,\n i.e this should be a benchmark daily returns if your\n ``returns`` are also daily.\n :param weight_bounds: minimum and maximum weight of each asset OR single min/max pair\n if all identical, defaults to (0, 1). Must be changed to (-1, 1)\n for portfolios with shorting.\n :type weight_bounds: tuple OR tuple list, optional\n :param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`\n :type solver: str\n :param verbose: whether performance and debugging info should be printed, defaults to False\n :type verbose: bool, optional\n :param solver_options: parameters for the given solver\n :type solver_options: dict, optional\n :raises TypeError: if ``expected_returns`` is not a series, list or array\n '
super().__init__(expected_returns=expected_returns, cov_matrix=np.zeros(((len(expected_returns),) * 2)), weight_bounds=weight_bounds, solver=solver, verbose=verbose, solver_options=solver_options)
self.returns = self._validate_returns(returns)
self.benchmark = benchmark
self.frequency = frequency
self._T = self.returns.shape[0] | def __init__(self, expected_returns, returns, frequency=252, benchmark=0, weight_bounds=(0, 1), solver=None, verbose=False, solver_options=None):
'\n :param expected_returns: expected returns for each asset. Can be None if\n optimising for semideviation only.\n :type expected_returns: pd.Series, list, np.ndarray\n :param returns: (historic) returns for all your assets (no NaNs).\n See ``expected_returns.returns_from_prices``.\n :type returns: pd.DataFrame or np.array\n :param frequency: number of time periods in a year, defaults to 252 (the number\n of trading days in a year). This must agree with the frequency\n parameter used in your ``expected_returns``.\n :type frequency: int, optional\n :param benchmark: the return threshold to distinguish "downside" and "upside".\n This should match the frequency of your ``returns``,\n i.e this should be a benchmark daily returns if your\n ``returns`` are also daily.\n :param weight_bounds: minimum and maximum weight of each asset OR single min/max pair\n if all identical, defaults to (0, 1). Must be changed to (-1, 1)\n for portfolios with shorting.\n :type weight_bounds: tuple OR tuple list, optional\n :param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`\n :type solver: str\n :param verbose: whether performance and debugging info should be printed, defaults to False\n :type verbose: bool, optional\n :param solver_options: parameters for the given solver\n :type solver_options: dict, optional\n :raises TypeError: if ``expected_returns`` is not a series, list or array\n '
super().__init__(expected_returns=expected_returns, cov_matrix=np.zeros(((len(expected_returns),) * 2)), weight_bounds=weight_bounds, solver=solver, verbose=verbose, solver_options=solver_options)
self.returns = self._validate_returns(returns)
self.benchmark = benchmark
self.frequency = frequency
self._T = self.returns.shape[0]<|docstring|>:param expected_returns: expected returns for each asset. Can be None if
optimising for semideviation only.
:type expected_returns: pd.Series, list, np.ndarray
:param returns: (historic) returns for all your assets (no NaNs).
See ``expected_returns.returns_from_prices``.
:type returns: pd.DataFrame or np.array
:param frequency: number of time periods in a year, defaults to 252 (the number
of trading days in a year). This must agree with the frequency
parameter used in your ``expected_returns``.
:type frequency: int, optional
:param benchmark: the return threshold to distinguish "downside" and "upside".
This should match the frequency of your ``returns``,
i.e this should be a benchmark daily returns if your
``returns`` are also daily.
:param weight_bounds: minimum and maximum weight of each asset OR single min/max pair
if all identical, defaults to (0, 1). Must be changed to (-1, 1)
for portfolios with shorting.
:type weight_bounds: tuple OR tuple list, optional
:param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`
:type solver: str
:param verbose: whether performance and debugging info should be printed, defaults to False
:type verbose: bool, optional
:param solver_options: parameters for the given solver
:type solver_options: dict, optional
:raises TypeError: if ``expected_returns`` is not a series, list or array<|endoftext|> |
a4c711ec05aa6132bb3d453b005d417a588633c01644cdd6ed59e90aab18b91f | def min_semivariance(self, market_neutral=False):
'\n Minimise portfolio semivariance (see docs for further explanation).\n\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the volatility-minimising portfolio\n :rtype: OrderedDict\n '
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
self._objective = cp.sum(cp.square(n))
for obj in self._additional_objectives:
self._objective += obj
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | Minimise portfolio semivariance (see docs for further explanation).
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the volatility-minimising portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | min_semivariance | SeaPea1/PyPortfolioOpt | 1 | python | def min_semivariance(self, market_neutral=False):
'\n Minimise portfolio semivariance (see docs for further explanation).\n\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the volatility-minimising portfolio\n :rtype: OrderedDict\n '
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
self._objective = cp.sum(cp.square(n))
for obj in self._additional_objectives:
self._objective += obj
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | def min_semivariance(self, market_neutral=False):
'\n Minimise portfolio semivariance (see docs for further explanation).\n\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the volatility-minimising portfolio\n :rtype: OrderedDict\n '
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
self._objective = cp.sum(cp.square(n))
for obj in self._additional_objectives:
self._objective += obj
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem()<|docstring|>Minimise portfolio semivariance (see docs for further explanation).
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the volatility-minimising portfolio
:rtype: OrderedDict<|endoftext|> |
cddeebbc8f3a0cb55039cf394d3533501e7f608dc1b57718e066de02a5e1a018 | def max_quadratic_utility(self, risk_aversion=1, market_neutral=False):
'\n Maximise the given quadratic utility, using portfolio semivariance instead\n of variance.\n\n :param risk_aversion: risk aversion parameter (must be greater than 0),\n defaults to 1\n :type risk_aversion: positive float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the maximum-utility portfolio\n :rtype: OrderedDict\n '
if (risk_aversion <= 0):
raise ValueError('risk aversion coefficient must be greater than zero')
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
mu = objective_functions.portfolio_return(self._w, self.expected_returns)
mu /= self.frequency
self._objective = (mu + ((0.5 * risk_aversion) * cp.sum(cp.square(n))))
for obj in self._additional_objectives:
self._objective += obj
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | Maximise the given quadratic utility, using portfolio semivariance instead
of variance.
:param risk_aversion: risk aversion parameter (must be greater than 0),
defaults to 1
:type risk_aversion: positive float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the maximum-utility portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | max_quadratic_utility | SeaPea1/PyPortfolioOpt | 1 | python | def max_quadratic_utility(self, risk_aversion=1, market_neutral=False):
'\n Maximise the given quadratic utility, using portfolio semivariance instead\n of variance.\n\n :param risk_aversion: risk aversion parameter (must be greater than 0),\n defaults to 1\n :type risk_aversion: positive float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the maximum-utility portfolio\n :rtype: OrderedDict\n '
if (risk_aversion <= 0):
raise ValueError('risk aversion coefficient must be greater than zero')
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
mu = objective_functions.portfolio_return(self._w, self.expected_returns)
mu /= self.frequency
self._objective = (mu + ((0.5 * risk_aversion) * cp.sum(cp.square(n))))
for obj in self._additional_objectives:
self._objective += obj
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | def max_quadratic_utility(self, risk_aversion=1, market_neutral=False):
'\n Maximise the given quadratic utility, using portfolio semivariance instead\n of variance.\n\n :param risk_aversion: risk aversion parameter (must be greater than 0),\n defaults to 1\n :type risk_aversion: positive float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the maximum-utility portfolio\n :rtype: OrderedDict\n '
if (risk_aversion <= 0):
raise ValueError('risk aversion coefficient must be greater than zero')
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
mu = objective_functions.portfolio_return(self._w, self.expected_returns)
mu /= self.frequency
self._objective = (mu + ((0.5 * risk_aversion) * cp.sum(cp.square(n))))
for obj in self._additional_objectives:
self._objective += obj
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem()<|docstring|>Maximise the given quadratic utility, using portfolio semivariance instead
of variance.
:param risk_aversion: risk aversion parameter (must be greater than 0),
defaults to 1
:type risk_aversion: positive float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the maximum-utility portfolio
:rtype: OrderedDict<|endoftext|> |
8ce6b61477618e32b58e8e4b486718f8bbca6812fca21953841ee8e635262233 | def efficient_risk(self, target_semideviation, market_neutral=False):
'\n Maximise return for a target semideviation (downside standard deviation).\n The resulting portfolio will have a semideviation less than the target\n (but not guaranteed to be equal).\n\n :param target_semideviation: the desired maximum semideviation of the resulting portfolio.\n :type target_semideviation: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the efficient risk portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
for obj in self._additional_objectives:
self._objective += obj
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
self._constraints.append(((self.frequency * cp.sum(cp.square(n))) <= (target_semideviation ** 2)))
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | Maximise return for a target semideviation (downside standard deviation).
The resulting portfolio will have a semideviation less than the target
(but not guaranteed to be equal).
:param target_semideviation: the desired maximum semideviation of the resulting portfolio.
:type target_semideviation: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the efficient risk portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | efficient_risk | SeaPea1/PyPortfolioOpt | 1 | python | def efficient_risk(self, target_semideviation, market_neutral=False):
'\n Maximise return for a target semideviation (downside standard deviation).\n The resulting portfolio will have a semideviation less than the target\n (but not guaranteed to be equal).\n\n :param target_semideviation: the desired maximum semideviation of the resulting portfolio.\n :type target_semideviation: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the efficient risk portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
for obj in self._additional_objectives:
self._objective += obj
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
self._constraints.append(((self.frequency * cp.sum(cp.square(n))) <= (target_semideviation ** 2)))
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | def efficient_risk(self, target_semideviation, market_neutral=False):
'\n Maximise return for a target semideviation (downside standard deviation).\n The resulting portfolio will have a semideviation less than the target\n (but not guaranteed to be equal).\n\n :param target_semideviation: the desired maximum semideviation of the resulting portfolio.\n :type target_semideviation: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the efficient risk portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
for obj in self._additional_objectives:
self._objective += obj
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
self._constraints.append(((self.frequency * cp.sum(cp.square(n))) <= (target_semideviation ** 2)))
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem()<|docstring|>Maximise return for a target semideviation (downside standard deviation).
The resulting portfolio will have a semideviation less than the target
(but not guaranteed to be equal).
:param target_semideviation: the desired maximum semideviation of the resulting portfolio.
:type target_semideviation: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the efficient risk portfolio
:rtype: OrderedDict<|endoftext|> |
742717c9f666d82793bd11aa421d86111cd9728e0fda2db6ec386fda37594305 | def efficient_return(self, target_return, market_neutral=False):
'\n Minimise semideviation for a given target return.\n\n :param target_return: the desired return of the resulting portfolio.\n :type target_return: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :type market_neutral: bool, optional\n :raises ValueError: if ``target_return`` is not a positive float\n :raises ValueError: if no portfolio can be found with return equal to ``target_return``\n :return: asset weights for the optimal portfolio\n :rtype: OrderedDict\n '
if ((not isinstance(target_return, float)) or (target_return < 0)):
raise ValueError('target_return should be a positive float')
if (target_return > np.abs(self.expected_returns).max()):
raise ValueError('target_return must be lower than the largest expected return')
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
self._objective = cp.sum(cp.square(n))
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((cp.sum((self._w @ self.expected_returns)) >= target_return))
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | Minimise semideviation for a given target return.
:param target_return: the desired return of the resulting portfolio.
:type target_return: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:type market_neutral: bool, optional
:raises ValueError: if ``target_return`` is not a positive float
:raises ValueError: if no portfolio can be found with return equal to ``target_return``
:return: asset weights for the optimal portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | efficient_return | SeaPea1/PyPortfolioOpt | 1 | python | def efficient_return(self, target_return, market_neutral=False):
'\n Minimise semideviation for a given target return.\n\n :param target_return: the desired return of the resulting portfolio.\n :type target_return: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :type market_neutral: bool, optional\n :raises ValueError: if ``target_return`` is not a positive float\n :raises ValueError: if no portfolio can be found with return equal to ``target_return``\n :return: asset weights for the optimal portfolio\n :rtype: OrderedDict\n '
if ((not isinstance(target_return, float)) or (target_return < 0)):
raise ValueError('target_return should be a positive float')
if (target_return > np.abs(self.expected_returns).max()):
raise ValueError('target_return must be lower than the largest expected return')
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
self._objective = cp.sum(cp.square(n))
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((cp.sum((self._w @ self.expected_returns)) >= target_return))
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | def efficient_return(self, target_return, market_neutral=False):
'\n Minimise semideviation for a given target return.\n\n :param target_return: the desired return of the resulting portfolio.\n :type target_return: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :type market_neutral: bool, optional\n :raises ValueError: if ``target_return`` is not a positive float\n :raises ValueError: if no portfolio can be found with return equal to ``target_return``\n :return: asset weights for the optimal portfolio\n :rtype: OrderedDict\n '
if ((not isinstance(target_return, float)) or (target_return < 0)):
raise ValueError('target_return should be a positive float')
if (target_return > np.abs(self.expected_returns).max()):
raise ValueError('target_return must be lower than the largest expected return')
p = cp.Variable(self._T, nonneg=True)
n = cp.Variable(self._T, nonneg=True)
self._objective = cp.sum(cp.square(n))
for obj in self._additional_objectives:
self._objective += obj
self._constraints.append((cp.sum((self._w @ self.expected_returns)) >= target_return))
B = ((self.returns.values - self.benchmark) / np.sqrt(self._T))
self._constraints.append(((((B @ self._w) - p) + n) == 0))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem()<|docstring|>Minimise semideviation for a given target return.
:param target_return: the desired return of the resulting portfolio.
:type target_return: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:type market_neutral: bool, optional
:raises ValueError: if ``target_return`` is not a positive float
:raises ValueError: if no portfolio can be found with return equal to ``target_return``
:return: asset weights for the optimal portfolio
:rtype: OrderedDict<|endoftext|> |
62d2c674dc8288175d70841b9f2bd64d348aceb6c5c345500a1a29ff7112da76 | def portfolio_performance(self, verbose=False, risk_free_rate=0.02):
'\n After optimising, calculate (and optionally print) the performance of the optimal\n portfolio, specifically: expected return, semideviation, Sortino ratio.\n\n :param verbose: whether performance should be printed, defaults to False\n :type verbose: bool, optional\n :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.\n The period of the risk-free rate should correspond to the\n frequency of expected returns.\n :type risk_free_rate: float, optional\n :raises ValueError: if weights have not been calcualted yet\n :return: expected return, semideviation, Sortino ratio.\n :rtype: (float, float, float)\n '
mu = objective_functions.portfolio_return(self.weights, self.expected_returns, negative=False)
portfolio_returns = (self.returns @ self.weights)
drops = np.fmin((portfolio_returns - self.benchmark), 0)
semivariance = ((np.sum(np.square(drops)) / self._T) * self.frequency)
semi_deviation = np.sqrt(semivariance)
sortino_ratio = ((mu - risk_free_rate) / semi_deviation)
if verbose:
print('Expected annual return: {:.1f}%'.format((100 * mu)))
print('Annual semi-deviation: {:.1f}%'.format((100 * semi_deviation)))
print('Sortino Ratio: {:.2f}'.format(sortino_ratio))
return (mu, semi_deviation, sortino_ratio) | After optimising, calculate (and optionally print) the performance of the optimal
portfolio, specifically: expected return, semideviation, Sortino ratio.
:param verbose: whether performance should be printed, defaults to False
:type verbose: bool, optional
:param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.
The period of the risk-free rate should correspond to the
frequency of expected returns.
:type risk_free_rate: float, optional
:raises ValueError: if weights have not been calcualted yet
:return: expected return, semideviation, Sortino ratio.
:rtype: (float, float, float) | pypfopt/efficient_frontier.py | portfolio_performance | SeaPea1/PyPortfolioOpt | 1 | python | def portfolio_performance(self, verbose=False, risk_free_rate=0.02):
'\n After optimising, calculate (and optionally print) the performance of the optimal\n portfolio, specifically: expected return, semideviation, Sortino ratio.\n\n :param verbose: whether performance should be printed, defaults to False\n :type verbose: bool, optional\n :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.\n The period of the risk-free rate should correspond to the\n frequency of expected returns.\n :type risk_free_rate: float, optional\n :raises ValueError: if weights have not been calcualted yet\n :return: expected return, semideviation, Sortino ratio.\n :rtype: (float, float, float)\n '
mu = objective_functions.portfolio_return(self.weights, self.expected_returns, negative=False)
portfolio_returns = (self.returns @ self.weights)
drops = np.fmin((portfolio_returns - self.benchmark), 0)
semivariance = ((np.sum(np.square(drops)) / self._T) * self.frequency)
semi_deviation = np.sqrt(semivariance)
sortino_ratio = ((mu - risk_free_rate) / semi_deviation)
if verbose:
print('Expected annual return: {:.1f}%'.format((100 * mu)))
print('Annual semi-deviation: {:.1f}%'.format((100 * semi_deviation)))
print('Sortino Ratio: {:.2f}'.format(sortino_ratio))
return (mu, semi_deviation, sortino_ratio) | def portfolio_performance(self, verbose=False, risk_free_rate=0.02):
'\n After optimising, calculate (and optionally print) the performance of the optimal\n portfolio, specifically: expected return, semideviation, Sortino ratio.\n\n :param verbose: whether performance should be printed, defaults to False\n :type verbose: bool, optional\n :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.\n The period of the risk-free rate should correspond to the\n frequency of expected returns.\n :type risk_free_rate: float, optional\n :raises ValueError: if weights have not been calcualted yet\n :return: expected return, semideviation, Sortino ratio.\n :rtype: (float, float, float)\n '
mu = objective_functions.portfolio_return(self.weights, self.expected_returns, negative=False)
portfolio_returns = (self.returns @ self.weights)
drops = np.fmin((portfolio_returns - self.benchmark), 0)
semivariance = ((np.sum(np.square(drops)) / self._T) * self.frequency)
semi_deviation = np.sqrt(semivariance)
sortino_ratio = ((mu - risk_free_rate) / semi_deviation)
if verbose:
print('Expected annual return: {:.1f}%'.format((100 * mu)))
print('Annual semi-deviation: {:.1f}%'.format((100 * semi_deviation)))
print('Sortino Ratio: {:.2f}'.format(sortino_ratio))
return (mu, semi_deviation, sortino_ratio)<|docstring|>After optimising, calculate (and optionally print) the performance of the optimal
portfolio, specifically: expected return, semideviation, Sortino ratio.
:param verbose: whether performance should be printed, defaults to False
:type verbose: bool, optional
:param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02.
The period of the risk-free rate should correspond to the
frequency of expected returns.
:type risk_free_rate: float, optional
:raises ValueError: if weights have not been calcualted yet
:return: expected return, semideviation, Sortino ratio.
:rtype: (float, float, float)<|endoftext|> |
df1a2f49c0b9577eda5e8028a83f8a59318e402e9fc08229bb77c42c9eb28178 | def __init__(self, expected_returns, returns, beta=0.95, weight_bounds=(0, 1), solver=None, verbose=False, solver_options=None):
'\n :param expected_returns: expected returns for each asset. Can be None if\n optimising for semideviation only.\n :type expected_returns: pd.Series, list, np.ndarray\n :param returns: (historic) returns for all your assets (no NaNs).\n See ``expected_returns.returns_from_prices``.\n :type returns: pd.DataFrame or np.array\n :param beta: confidence level, defauls to 0.95 (i.e expected loss on the worst (1-beta) days).\n :param weight_bounds: minimum and maximum weight of each asset OR single min/max pair\n if all identical, defaults to (0, 1). Must be changed to (-1, 1)\n for portfolios with shorting.\n :type weight_bounds: tuple OR tuple list, optional\n :param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`\n :type solver: str\n :param verbose: whether performance and debugging info should be printed, defaults to False\n :type verbose: bool, optional\n :param solver_options: parameters for the given solver\n :type solver_options: dict, optional\n :raises TypeError: if ``expected_returns`` is not a series, list or array\n '
super().__init__(expected_returns=expected_returns, cov_matrix=np.zeros(((len(expected_returns),) * 2)), weight_bounds=weight_bounds, solver=solver, verbose=verbose, solver_options=solver_options)
self.returns = self._validate_returns(returns)
self._beta = self._validate_beta(beta)
self._alpha = cp.Variable()
self._u = cp.Variable(len(self.returns)) | :param expected_returns: expected returns for each asset. Can be None if
optimising for semideviation only.
:type expected_returns: pd.Series, list, np.ndarray
:param returns: (historic) returns for all your assets (no NaNs).
See ``expected_returns.returns_from_prices``.
:type returns: pd.DataFrame or np.array
:param beta: confidence level, defauls to 0.95 (i.e expected loss on the worst (1-beta) days).
:param weight_bounds: minimum and maximum weight of each asset OR single min/max pair
if all identical, defaults to (0, 1). Must be changed to (-1, 1)
for portfolios with shorting.
:type weight_bounds: tuple OR tuple list, optional
:param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`
:type solver: str
:param verbose: whether performance and debugging info should be printed, defaults to False
:type verbose: bool, optional
:param solver_options: parameters for the given solver
:type solver_options: dict, optional
:raises TypeError: if ``expected_returns`` is not a series, list or array | pypfopt/efficient_frontier.py | __init__ | SeaPea1/PyPortfolioOpt | 1 | python | def __init__(self, expected_returns, returns, beta=0.95, weight_bounds=(0, 1), solver=None, verbose=False, solver_options=None):
'\n :param expected_returns: expected returns for each asset. Can be None if\n optimising for semideviation only.\n :type expected_returns: pd.Series, list, np.ndarray\n :param returns: (historic) returns for all your assets (no NaNs).\n See ``expected_returns.returns_from_prices``.\n :type returns: pd.DataFrame or np.array\n :param beta: confidence level, defauls to 0.95 (i.e expected loss on the worst (1-beta) days).\n :param weight_bounds: minimum and maximum weight of each asset OR single min/max pair\n if all identical, defaults to (0, 1). Must be changed to (-1, 1)\n for portfolios with shorting.\n :type weight_bounds: tuple OR tuple list, optional\n :param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`\n :type solver: str\n :param verbose: whether performance and debugging info should be printed, defaults to False\n :type verbose: bool, optional\n :param solver_options: parameters for the given solver\n :type solver_options: dict, optional\n :raises TypeError: if ``expected_returns`` is not a series, list or array\n '
super().__init__(expected_returns=expected_returns, cov_matrix=np.zeros(((len(expected_returns),) * 2)), weight_bounds=weight_bounds, solver=solver, verbose=verbose, solver_options=solver_options)
self.returns = self._validate_returns(returns)
self._beta = self._validate_beta(beta)
self._alpha = cp.Variable()
self._u = cp.Variable(len(self.returns)) | def __init__(self, expected_returns, returns, beta=0.95, weight_bounds=(0, 1), solver=None, verbose=False, solver_options=None):
'\n :param expected_returns: expected returns for each asset. Can be None if\n optimising for semideviation only.\n :type expected_returns: pd.Series, list, np.ndarray\n :param returns: (historic) returns for all your assets (no NaNs).\n See ``expected_returns.returns_from_prices``.\n :type returns: pd.DataFrame or np.array\n :param beta: confidence level, defauls to 0.95 (i.e expected loss on the worst (1-beta) days).\n :param weight_bounds: minimum and maximum weight of each asset OR single min/max pair\n if all identical, defaults to (0, 1). Must be changed to (-1, 1)\n for portfolios with shorting.\n :type weight_bounds: tuple OR tuple list, optional\n :param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`\n :type solver: str\n :param verbose: whether performance and debugging info should be printed, defaults to False\n :type verbose: bool, optional\n :param solver_options: parameters for the given solver\n :type solver_options: dict, optional\n :raises TypeError: if ``expected_returns`` is not a series, list or array\n '
super().__init__(expected_returns=expected_returns, cov_matrix=np.zeros(((len(expected_returns),) * 2)), weight_bounds=weight_bounds, solver=solver, verbose=verbose, solver_options=solver_options)
self.returns = self._validate_returns(returns)
self._beta = self._validate_beta(beta)
self._alpha = cp.Variable()
self._u = cp.Variable(len(self.returns))<|docstring|>:param expected_returns: expected returns for each asset. Can be None if
optimising for semideviation only.
:type expected_returns: pd.Series, list, np.ndarray
:param returns: (historic) returns for all your assets (no NaNs).
See ``expected_returns.returns_from_prices``.
:type returns: pd.DataFrame or np.array
:param beta: confidence level, defauls to 0.95 (i.e expected loss on the worst (1-beta) days).
:param weight_bounds: minimum and maximum weight of each asset OR single min/max pair
if all identical, defaults to (0, 1). Must be changed to (-1, 1)
for portfolios with shorting.
:type weight_bounds: tuple OR tuple list, optional
:param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()`
:type solver: str
:param verbose: whether performance and debugging info should be printed, defaults to False
:type verbose: bool, optional
:param solver_options: parameters for the given solver
:type solver_options: dict, optional
:raises TypeError: if ``expected_returns`` is not a series, list or array<|endoftext|> |
9cf1727ac19d014196cf988d22a52b0f7fa5ea129c6e6748c9c891a5d87bab2f | def min_cvar(self, market_neutral=False):
'\n Minimise portfolio CVaR (see docs for further explanation).\n\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the volatility-minimising portfolio\n :rtype: OrderedDict\n '
self._objective = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
for obj in self._additional_objectives:
self._objective += obj
self._constraints += [(self._u >= 0.0), ((((self.returns.values @ self._w) + self._alpha) + self._u) >= 0.0)]
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | Minimise portfolio CVaR (see docs for further explanation).
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the volatility-minimising portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | min_cvar | SeaPea1/PyPortfolioOpt | 1 | python | def min_cvar(self, market_neutral=False):
'\n Minimise portfolio CVaR (see docs for further explanation).\n\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the volatility-minimising portfolio\n :rtype: OrderedDict\n '
self._objective = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
for obj in self._additional_objectives:
self._objective += obj
self._constraints += [(self._u >= 0.0), ((((self.returns.values @ self._w) + self._alpha) + self._u) >= 0.0)]
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | def min_cvar(self, market_neutral=False):
'\n Minimise portfolio CVaR (see docs for further explanation).\n\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the volatility-minimising portfolio\n :rtype: OrderedDict\n '
self._objective = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
for obj in self._additional_objectives:
self._objective += obj
self._constraints += [(self._u >= 0.0), ((((self.returns.values @ self._w) + self._alpha) + self._u) >= 0.0)]
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem()<|docstring|>Minimise portfolio CVaR (see docs for further explanation).
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the volatility-minimising portfolio
:rtype: OrderedDict<|endoftext|> |
9e3eba91563e750a39ed9494ff66f5a73b279341abcb851ce6960d49fe33880f | def efficient_return(self, target_return, market_neutral=False):
'\n Minimise CVaR for a given target return.\n\n :param target_return: the desired return of the resulting portfolio.\n :type target_return: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :type market_neutral: bool, optional\n :raises ValueError: if ``target_return`` is not a positive float\n :raises ValueError: if no portfolio can be found with return equal to ``target_return``\n :return: asset weights for the optimal portfolio\n :rtype: OrderedDict\n '
self._objective = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
for obj in self._additional_objectives:
self._objective += obj
self._constraints += [(self._u >= 0.0), ((((self.returns.values @ self._w) + self._alpha) + self._u) >= 0.0)]
ret = (self.expected_returns.T @ self._w)
self._constraints.append((ret >= target_return))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | Minimise CVaR for a given target return.
:param target_return: the desired return of the resulting portfolio.
:type target_return: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:type market_neutral: bool, optional
:raises ValueError: if ``target_return`` is not a positive float
:raises ValueError: if no portfolio can be found with return equal to ``target_return``
:return: asset weights for the optimal portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | efficient_return | SeaPea1/PyPortfolioOpt | 1 | python | def efficient_return(self, target_return, market_neutral=False):
'\n Minimise CVaR for a given target return.\n\n :param target_return: the desired return of the resulting portfolio.\n :type target_return: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :type market_neutral: bool, optional\n :raises ValueError: if ``target_return`` is not a positive float\n :raises ValueError: if no portfolio can be found with return equal to ``target_return``\n :return: asset weights for the optimal portfolio\n :rtype: OrderedDict\n '
self._objective = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
for obj in self._additional_objectives:
self._objective += obj
self._constraints += [(self._u >= 0.0), ((((self.returns.values @ self._w) + self._alpha) + self._u) >= 0.0)]
ret = (self.expected_returns.T @ self._w)
self._constraints.append((ret >= target_return))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | def efficient_return(self, target_return, market_neutral=False):
'\n Minimise CVaR for a given target return.\n\n :param target_return: the desired return of the resulting portfolio.\n :type target_return: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :type market_neutral: bool, optional\n :raises ValueError: if ``target_return`` is not a positive float\n :raises ValueError: if no portfolio can be found with return equal to ``target_return``\n :return: asset weights for the optimal portfolio\n :rtype: OrderedDict\n '
self._objective = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
for obj in self._additional_objectives:
self._objective += obj
self._constraints += [(self._u >= 0.0), ((((self.returns.values @ self._w) + self._alpha) + self._u) >= 0.0)]
ret = (self.expected_returns.T @ self._w)
self._constraints.append((ret >= target_return))
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem()<|docstring|>Minimise CVaR for a given target return.
:param target_return: the desired return of the resulting portfolio.
:type target_return: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:type market_neutral: bool, optional
:raises ValueError: if ``target_return`` is not a positive float
:raises ValueError: if no portfolio can be found with return equal to ``target_return``
:return: asset weights for the optimal portfolio
:rtype: OrderedDict<|endoftext|> |
a5c6d83d3b230bde6d3ec98911262b43016728861e4d8e6962fcb65a305b36e9 | def efficient_risk(self, target_cvar, market_neutral=False):
'\n Maximise return for a target CVaR.\n The resulting portfolio will have a CVaR less than the target\n (but not guaranteed to be equal).\n\n :param target_cvar: the desired maximum semideviation of the resulting portfolio.\n :type target_cvar: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the efficient risk portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
for obj in self._additional_objectives:
self._objective += obj
cvar = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
self._constraints += [(cvar <= target_cvar), (self._u >= 0.0), ((((self.returns.values @ self._w) + self._alpha) + self._u) >= 0.0)]
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | Maximise return for a target CVaR.
The resulting portfolio will have a CVaR less than the target
(but not guaranteed to be equal).
:param target_cvar: the desired maximum semideviation of the resulting portfolio.
:type target_cvar: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the efficient risk portfolio
:rtype: OrderedDict | pypfopt/efficient_frontier.py | efficient_risk | SeaPea1/PyPortfolioOpt | 1 | python | def efficient_risk(self, target_cvar, market_neutral=False):
'\n Maximise return for a target CVaR.\n The resulting portfolio will have a CVaR less than the target\n (but not guaranteed to be equal).\n\n :param target_cvar: the desired maximum semideviation of the resulting portfolio.\n :type target_cvar: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the efficient risk portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
for obj in self._additional_objectives:
self._objective += obj
cvar = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
self._constraints += [(cvar <= target_cvar), (self._u >= 0.0), ((((self.returns.values @ self._w) + self._alpha) + self._u) >= 0.0)]
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem() | def efficient_risk(self, target_cvar, market_neutral=False):
'\n Maximise return for a target CVaR.\n The resulting portfolio will have a CVaR less than the target\n (but not guaranteed to be equal).\n\n :param target_cvar: the desired maximum semideviation of the resulting portfolio.\n :type target_cvar: float\n :param market_neutral: whether the portfolio should be market neutral (weights sum to zero),\n defaults to False. Requires negative lower weight bound.\n :param market_neutral: bool, optional\n :return: asset weights for the efficient risk portfolio\n :rtype: OrderedDict\n '
self._objective = objective_functions.portfolio_return(self._w, self.expected_returns)
for obj in self._additional_objectives:
self._objective += obj
cvar = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
self._constraints += [(cvar <= target_cvar), (self._u >= 0.0), ((((self.returns.values @ self._w) + self._alpha) + self._u) >= 0.0)]
self._make_weight_sum_constraint(market_neutral)
return self._solve_cvxpy_opt_problem()<|docstring|>Maximise return for a target CVaR.
The resulting portfolio will have a CVaR less than the target
(but not guaranteed to be equal).
:param target_cvar: the desired maximum semideviation of the resulting portfolio.
:type target_cvar: float
:param market_neutral: whether the portfolio should be market neutral (weights sum to zero),
defaults to False. Requires negative lower weight bound.
:param market_neutral: bool, optional
:return: asset weights for the efficient risk portfolio
:rtype: OrderedDict<|endoftext|> |
b60cbad95aef00be5b2bd191d406ff6168468032cbd56d3a90881459c8b32ea8 | def portfolio_performance(self, verbose=False):
'\n After optimising, calculate (and optionally print) the performance of the optimal\n portfolio, specifically: expected return, CVaR\n\n :param verbose: whether performance should be printed, defaults to False\n :type verbose: bool, optional\n :raises ValueError: if weights have not been calcualted yet\n :return: expected return, CVaR.\n :rtype: (float, float)\n '
mu = objective_functions.portfolio_return(self.weights, self.expected_returns, negative=False)
cvar = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
cvar_val = cvar.value
if verbose:
print('Expected annual return: {:.1f}%'.format((100 * mu)))
print('Conditional Value at Risk: {:.2f}%'.format((100 * cvar_val)))
return (mu, cvar_val) | After optimising, calculate (and optionally print) the performance of the optimal
portfolio, specifically: expected return, CVaR
:param verbose: whether performance should be printed, defaults to False
:type verbose: bool, optional
:raises ValueError: if weights have not been calcualted yet
:return: expected return, CVaR.
:rtype: (float, float) | pypfopt/efficient_frontier.py | portfolio_performance | SeaPea1/PyPortfolioOpt | 1 | python | def portfolio_performance(self, verbose=False):
'\n After optimising, calculate (and optionally print) the performance of the optimal\n portfolio, specifically: expected return, CVaR\n\n :param verbose: whether performance should be printed, defaults to False\n :type verbose: bool, optional\n :raises ValueError: if weights have not been calcualted yet\n :return: expected return, CVaR.\n :rtype: (float, float)\n '
mu = objective_functions.portfolio_return(self.weights, self.expected_returns, negative=False)
cvar = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
cvar_val = cvar.value
if verbose:
print('Expected annual return: {:.1f}%'.format((100 * mu)))
print('Conditional Value at Risk: {:.2f}%'.format((100 * cvar_val)))
return (mu, cvar_val) | def portfolio_performance(self, verbose=False):
'\n After optimising, calculate (and optionally print) the performance of the optimal\n portfolio, specifically: expected return, CVaR\n\n :param verbose: whether performance should be printed, defaults to False\n :type verbose: bool, optional\n :raises ValueError: if weights have not been calcualted yet\n :return: expected return, CVaR.\n :rtype: (float, float)\n '
mu = objective_functions.portfolio_return(self.weights, self.expected_returns, negative=False)
cvar = (self._alpha + ((1.0 / (len(self.returns) * (1 - self._beta))) * cp.sum(self._u)))
cvar_val = cvar.value
if verbose:
print('Expected annual return: {:.1f}%'.format((100 * mu)))
print('Conditional Value at Risk: {:.2f}%'.format((100 * cvar_val)))
return (mu, cvar_val)<|docstring|>After optimising, calculate (and optionally print) the performance of the optimal
portfolio, specifically: expected return, CVaR
:param verbose: whether performance should be printed, defaults to False
:type verbose: bool, optional
:raises ValueError: if weights have not been calcualted yet
:return: expected return, CVaR.
:rtype: (float, float)<|endoftext|> |
7a59c51d0082dc6d2fbdbdc2a2aee47841e941b17f1f00957b067883bcd83f9b | def predict(self, X_test):
'\n Assumes thats X_test has the bias festure added to it, however an assert is done\n '
assert (X_test.shape[1] == self.theta.shape[0])
predictions = X_test.dot(self.theta)
self.predictions = predictions
return predictions | Assumes thats X_test has the bias festure added to it, however an assert is done | classification/logistic.py | predict | sahitpj/MachineLearning | 2 | python | def predict(self, X_test):
'\n \n '
assert (X_test.shape[1] == self.theta.shape[0])
predictions = X_test.dot(self.theta)
self.predictions = predictions
return predictions | def predict(self, X_test):
'\n \n '
assert (X_test.shape[1] == self.theta.shape[0])
predictions = X_test.dot(self.theta)
self.predictions = predictions
return predictions<|docstring|>Assumes thats X_test has the bias festure added to it, however an assert is done<|endoftext|> |
85f4f55990ecefe52012f43403ef131006bf422540bb68264d6d7e63d5553ae2 | async def serve(app, flow: http.HTTPFlow):
'\n Serves app on flow.\n '
assert flow.reply
scope = make_scope(flow)
done = asyncio.Event()
received_body = False
async def receive():
nonlocal received_body
if (not received_body):
received_body = True
return {'type': 'http.request', 'body': flow.request.raw_content}
else:
(await done.wait())
return {'type': 'http.disconnect'}
async def send(event):
if (event['type'] == 'http.response.start'):
flow.response = http.HTTPResponse.make(event['status'], b'', event.get('headers', []))
flow.response.decode()
elif (event['type'] == 'http.response.body'):
flow.response.content += event.get('body', b'')
if (not event.get('more_body', False)):
flow.reply.ack()
else:
raise AssertionError(f"Unexpected event: {event['type']}")
try:
(await app(scope, receive, send))
if (not flow.reply.has_message):
raise RuntimeError(f'no response sent.')
except Exception as e:
ctx.log.error(f'Error in asgi app: {e}')
flow.response = http.HTTPResponse.make(500, b'ASGI Error.')
flow.reply.ack(force=True)
finally:
flow.reply.commit()
done.set() | Serves app on flow. | mitmproxy/addons/asgiapp.py | serve | liwanlei/mitmproxy | 6 | python | async def serve(app, flow: http.HTTPFlow):
'\n \n '
assert flow.reply
scope = make_scope(flow)
done = asyncio.Event()
received_body = False
async def receive():
nonlocal received_body
if (not received_body):
received_body = True
return {'type': 'http.request', 'body': flow.request.raw_content}
else:
(await done.wait())
return {'type': 'http.disconnect'}
async def send(event):
if (event['type'] == 'http.response.start'):
flow.response = http.HTTPResponse.make(event['status'], b, event.get('headers', []))
flow.response.decode()
elif (event['type'] == 'http.response.body'):
flow.response.content += event.get('body', b)
if (not event.get('more_body', False)):
flow.reply.ack()
else:
raise AssertionError(f"Unexpected event: {event['type']}")
try:
(await app(scope, receive, send))
if (not flow.reply.has_message):
raise RuntimeError(f'no response sent.')
except Exception as e:
ctx.log.error(f'Error in asgi app: {e}')
flow.response = http.HTTPResponse.make(500, b'ASGI Error.')
flow.reply.ack(force=True)
finally:
flow.reply.commit()
done.set() | async def serve(app, flow: http.HTTPFlow):
'\n \n '
assert flow.reply
scope = make_scope(flow)
done = asyncio.Event()
received_body = False
async def receive():
nonlocal received_body
if (not received_body):
received_body = True
return {'type': 'http.request', 'body': flow.request.raw_content}
else:
(await done.wait())
return {'type': 'http.disconnect'}
async def send(event):
if (event['type'] == 'http.response.start'):
flow.response = http.HTTPResponse.make(event['status'], b, event.get('headers', []))
flow.response.decode()
elif (event['type'] == 'http.response.body'):
flow.response.content += event.get('body', b)
if (not event.get('more_body', False)):
flow.reply.ack()
else:
raise AssertionError(f"Unexpected event: {event['type']}")
try:
(await app(scope, receive, send))
if (not flow.reply.has_message):
raise RuntimeError(f'no response sent.')
except Exception as e:
ctx.log.error(f'Error in asgi app: {e}')
flow.response = http.HTTPResponse.make(500, b'ASGI Error.')
flow.reply.ack(force=True)
finally:
flow.reply.commit()
done.set()<|docstring|>Serves app on flow.<|endoftext|> |
7b29502b402c809e65aa5f4760ece549a67bc8cb0ec75d94741902353f5ccc7a | def create_sample_user(**params):
'Creates sample user'
return get_user_model().objects.create_user(**params) | Creates sample user | app/tests/test_user_api.py | create_sample_user | victorfmarques/Sled | 0 | python | def create_sample_user(**params):
return get_user_model().objects.create_user(**params) | def create_sample_user(**params):
return get_user_model().objects.create_user(**params)<|docstring|>Creates sample user<|endoftext|> |
081c296e1285abdb33342e8af9f56cbaf0b0c5823b4db11fb3730003a01c4ee2 | def test_create_user_success(self):
' Test creating user successfully '
res = self.client.post(CREATE_USER_URL, self.payload)
user = get_user_model().objects.get(**res.data)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
self.assertTrue(user.check_password(self.payload['password']))
self.assertNotIn('password', res.data) | Test creating user successfully | app/tests/test_user_api.py | test_create_user_success | victorfmarques/Sled | 0 | python | def test_create_user_success(self):
' '
res = self.client.post(CREATE_USER_URL, self.payload)
user = get_user_model().objects.get(**res.data)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
self.assertTrue(user.check_password(self.payload['password']))
self.assertNotIn('password', res.data) | def test_create_user_success(self):
' '
res = self.client.post(CREATE_USER_URL, self.payload)
user = get_user_model().objects.get(**res.data)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
self.assertTrue(user.check_password(self.payload['password']))
self.assertNotIn('password', res.data)<|docstring|>Test creating user successfully<|endoftext|> |
5b4f81135376ebb13bb1eb6d15725cf94f4dd8e57b8ceae84c3226f713b61776 | def test_create_user_invalid(self):
' Test creating invalid user '
create_sample_user(**self.payload)
res = self.client.post(CREATE_USER_URL, self.payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
self.assertNotIn(self.payload['email'], res.data) | Test creating invalid user | app/tests/test_user_api.py | test_create_user_invalid | victorfmarques/Sled | 0 | python | def test_create_user_invalid(self):
' '
create_sample_user(**self.payload)
res = self.client.post(CREATE_USER_URL, self.payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
self.assertNotIn(self.payload['email'], res.data) | def test_create_user_invalid(self):
' '
create_sample_user(**self.payload)
res = self.client.post(CREATE_USER_URL, self.payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
self.assertNotIn(self.payload['email'], res.data)<|docstring|>Test creating invalid user<|endoftext|> |
ffd55e213e6ca110b0f7ff30118de84e2edb45c1821707bba8c389c02273597c | def test_create_user_blank_fields(self):
' Test creating user with blank fields '
data = {'email': '', 'password': ''}
res = self.client.post(CREATE_USER_URL, data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | Test creating user with blank fields | app/tests/test_user_api.py | test_create_user_blank_fields | victorfmarques/Sled | 0 | python | def test_create_user_blank_fields(self):
' '
data = {'email': , 'password': }
res = self.client.post(CREATE_USER_URL, data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | def test_create_user_blank_fields(self):
' '
data = {'email': , 'password': }
res = self.client.post(CREATE_USER_URL, data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)<|docstring|>Test creating user with blank fields<|endoftext|> |
8bdcf63c9fcb7409d894b057d519befa1fccfdbcb1f182a7e517a1f2bbcb92b1 | def test_create_user_password_too_short(self):
' Test creating a user with invalid password '
data = {'email': 'example@example.com', 'password': 'pass'}
res = self.client.post(CREATE_USER_URL, data)
exists = get_user_model().objects.filter(email=data['email']).exists()
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
self.assertFalse(exists) | Test creating a user with invalid password | app/tests/test_user_api.py | test_create_user_password_too_short | victorfmarques/Sled | 0 | python | def test_create_user_password_too_short(self):
' '
data = {'email': 'example@example.com', 'password': 'pass'}
res = self.client.post(CREATE_USER_URL, data)
exists = get_user_model().objects.filter(email=data['email']).exists()
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
self.assertFalse(exists) | def test_create_user_password_too_short(self):
' '
data = {'email': 'example@example.com', 'password': 'pass'}
res = self.client.post(CREATE_USER_URL, data)
exists = get_user_model().objects.filter(email=data['email']).exists()
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
self.assertFalse(exists)<|docstring|>Test creating a user with invalid password<|endoftext|> |
1ef87cbf9817f39088e1864db5cf94b9ab5b7d38c8ddfafc0669ed2eea4fd090 | def test_create_token_for_user(self):
' Test token creation for user'
payload = {'email': 'example@example.com', 'password': 'test123'}
create_sample_user(**payload)
res = self.client.post(TOKEN_URL, payload)
self.assertIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_200_OK) | Test token creation for user | app/tests/test_user_api.py | test_create_token_for_user | victorfmarques/Sled | 0 | python | def test_create_token_for_user(self):
' '
payload = {'email': 'example@example.com', 'password': 'test123'}
create_sample_user(**payload)
res = self.client.post(TOKEN_URL, payload)
self.assertIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_200_OK) | def test_create_token_for_user(self):
' '
payload = {'email': 'example@example.com', 'password': 'test123'}
create_sample_user(**payload)
res = self.client.post(TOKEN_URL, payload)
self.assertIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_200_OK)<|docstring|>Test token creation for user<|endoftext|> |
1f04e985449150296041cae8ca7ad5015685fd11a33c2b010bc89549e181c878 | def test_create_token_invalid_credentials(self):
' Test create user token with invalid credentials '
create_sample_user(email='example@example.com', password='tesetee')
payload = {'email': 'example@example.com', 'password': 'incorrectpwd'}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | Test create user token with invalid credentials | app/tests/test_user_api.py | test_create_token_invalid_credentials | victorfmarques/Sled | 0 | python | def test_create_token_invalid_credentials(self):
' '
create_sample_user(email='example@example.com', password='tesetee')
payload = {'email': 'example@example.com', 'password': 'incorrectpwd'}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | def test_create_token_invalid_credentials(self):
' '
create_sample_user(email='example@example.com', password='tesetee')
payload = {'email': 'example@example.com', 'password': 'incorrectpwd'}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)<|docstring|>Test create user token with invalid credentials<|endoftext|> |
23735dd78ad2a73d77984165535a034c5c725b31ccd6684c0fcc677997226000 | def test_create_token_no_user(self):
' Test token creation for non existing user '
payload = {'email': 'example@example.com', 'password': 'senha123'}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | Test token creation for non existing user | app/tests/test_user_api.py | test_create_token_no_user | victorfmarques/Sled | 0 | python | def test_create_token_no_user(self):
' '
payload = {'email': 'example@example.com', 'password': 'senha123'}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | def test_create_token_no_user(self):
' '
payload = {'email': 'example@example.com', 'password': 'senha123'}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)<|docstring|>Test token creation for non existing user<|endoftext|> |
8586fb219175cc5335998e82b2f791eb760cc0b1220f12486fca2f59254a027f | def test_create_token_missing_field(self):
' Test creation of token with blank fields '
res = self.client.post(TOKEN_URL, {'email': 'one', 'password': ''})
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | Test creation of token with blank fields | app/tests/test_user_api.py | test_create_token_missing_field | victorfmarques/Sled | 0 | python | def test_create_token_missing_field(self):
' '
res = self.client.post(TOKEN_URL, {'email': 'one', 'password': })
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | def test_create_token_missing_field(self):
' '
res = self.client.post(TOKEN_URL, {'email': 'one', 'password': })
self.assertNotIn('token', res.data)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)<|docstring|>Test creation of token with blank fields<|endoftext|> |
95920ae9c1479ea8702a207707802170300b8a8925bec3972dd72634bd8939e7 | def __str__(self):
'Implement this method to show a simple representation of the class'
return self.name | Implement this method to show a simple representation of the class | terseparse/types.py | __str__ | jthacker/terseparse | 1 | python | def __str__(self):
return self.name | def __str__(self):
return self.name<|docstring|>Implement this method to show a simple representation of the class<|endoftext|> |
7360b9ebabe9bd29a97fd4a4be92c200fb55f48b04374a22e0c9eb0117454d53 | def __init__(self, name, *value):
'Initialize Keywords\n Args:\n name -- keyword name\n value -- Optional value, otherwise name is used\n\n value is setup as *value to detect if the parameter is supplied, while\n still supporting None. If no value is supplied then name should be used.\n If any value is supplied (even None), then that value is used instead\n '
self.name = name
self.key = name
self.value = (name if (len(value) != 1) else value[0])
self.description = 'Matches {!r} and maps it to {!r}'.format(name, self.value) | Initialize Keywords
Args:
name -- keyword name
value -- Optional value, otherwise name is used
value is setup as *value to detect if the parameter is supplied, while
still supporting None. If no value is supplied then name should be used.
If any value is supplied (even None), then that value is used instead | terseparse/types.py | __init__ | jthacker/terseparse | 1 | python | def __init__(self, name, *value):
'Initialize Keywords\n Args:\n name -- keyword name\n value -- Optional value, otherwise name is used\n\n value is setup as *value to detect if the parameter is supplied, while\n still supporting None. If no value is supplied then name should be used.\n If any value is supplied (even None), then that value is used instead\n '
self.name = name
self.key = name
self.value = (name if (len(value) != 1) else value[0])
self.description = 'Matches {!r} and maps it to {!r}'.format(name, self.value) | def __init__(self, name, *value):
'Initialize Keywords\n Args:\n name -- keyword name\n value -- Optional value, otherwise name is used\n\n value is setup as *value to detect if the parameter is supplied, while\n still supporting None. If no value is supplied then name should be used.\n If any value is supplied (even None), then that value is used instead\n '
self.name = name
self.key = name
self.value = (name if (len(value) != 1) else value[0])
self.description = 'Matches {!r} and maps it to {!r}'.format(name, self.value)<|docstring|>Initialize Keywords
Args:
name -- keyword name
value -- Optional value, otherwise name is used
value is setup as *value to detect if the parameter is supplied, while
still supporting None. If no value is supplied then name should be used.
If any value is supplied (even None), then that value is used instead<|endoftext|> |
2f8496aff63440208706166fb3b84dfed494ad22a55c4939d4670d9cf33dbe4c | def __init__(self, validator_map):
"Create a dictonary type from a dictionary of other types\n Args:\n validator_map -- a mapping from names to types\n Examples:\n >>> Dict({'a': int, 'b': int})('a:1,b:2')\n {'a': 1, 'b': 2}\n\n >>> Dict({'a': str, 'b': int})('a:asdf b=1234')\n {'a': 'asdf', 'b': 1234}\n\n >>> Dict({'a': Int() | Keyword('', None), 'b': Int()})('a,b=1')\n {'a': None, 'b': 1}\n "
self.validators = dict(validator_map)
v_sorted = sorted(self.validators.items(), key=(lambda t: t[0]))
self.validator_descriptions = ['{}:<{}>'.format(k, v) for (k, v) in v_sorted]
self.name = 'dict({})'.format(', '.join(self.validator_descriptions))
self.description = '\nDict options: \n '
self.description += '\n '.join(self.validator_descriptions)
self.kv_regex = re.compile('[=:]+') | Create a dictonary type from a dictionary of other types
Args:
validator_map -- a mapping from names to types
Examples:
>>> Dict({'a': int, 'b': int})('a:1,b:2')
{'a': 1, 'b': 2}
>>> Dict({'a': str, 'b': int})('a:asdf b=1234')
{'a': 'asdf', 'b': 1234}
>>> Dict({'a': Int() | Keyword('', None), 'b': Int()})('a,b=1')
{'a': None, 'b': 1} | terseparse/types.py | __init__ | jthacker/terseparse | 1 | python | def __init__(self, validator_map):
"Create a dictonary type from a dictionary of other types\n Args:\n validator_map -- a mapping from names to types\n Examples:\n >>> Dict({'a': int, 'b': int})('a:1,b:2')\n {'a': 1, 'b': 2}\n\n >>> Dict({'a': str, 'b': int})('a:asdf b=1234')\n {'a': 'asdf', 'b': 1234}\n\n >>> Dict({'a': Int() | Keyword(, None), 'b': Int()})('a,b=1')\n {'a': None, 'b': 1}\n "
self.validators = dict(validator_map)
v_sorted = sorted(self.validators.items(), key=(lambda t: t[0]))
self.validator_descriptions = ['{}:<{}>'.format(k, v) for (k, v) in v_sorted]
self.name = 'dict({})'.format(', '.join(self.validator_descriptions))
self.description = '\nDict options: \n '
self.description += '\n '.join(self.validator_descriptions)
self.kv_regex = re.compile('[=:]+') | def __init__(self, validator_map):
"Create a dictonary type from a dictionary of other types\n Args:\n validator_map -- a mapping from names to types\n Examples:\n >>> Dict({'a': int, 'b': int})('a:1,b:2')\n {'a': 1, 'b': 2}\n\n >>> Dict({'a': str, 'b': int})('a:asdf b=1234')\n {'a': 'asdf', 'b': 1234}\n\n >>> Dict({'a': Int() | Keyword(, None), 'b': Int()})('a,b=1')\n {'a': None, 'b': 1}\n "
self.validators = dict(validator_map)
v_sorted = sorted(self.validators.items(), key=(lambda t: t[0]))
self.validator_descriptions = ['{}:<{}>'.format(k, v) for (k, v) in v_sorted]
self.name = 'dict({})'.format(', '.join(self.validator_descriptions))
self.description = '\nDict options: \n '
self.description += '\n '.join(self.validator_descriptions)
self.kv_regex = re.compile('[=:]+')<|docstring|>Create a dictonary type from a dictionary of other types
Args:
validator_map -- a mapping from names to types
Examples:
>>> Dict({'a': int, 'b': int})('a:1,b:2')
{'a': 1, 'b': 2}
>>> Dict({'a': str, 'b': int})('a:asdf b=1234')
{'a': 'asdf', 'b': 1234}
>>> Dict({'a': Int() | Keyword('', None), 'b': Int()})('a,b=1')
{'a': None, 'b': 1}<|endoftext|> |
8a36a22045f3c14a5c6e89749f9110c9b1cd10029bb8f37408d41ff1a1e913d2 | def __init__(self, minval=None, maxval=None):
'Create an Integer that satisfies the requirements minval <= val < maxval\n '
self.name = 'int'
self.minval = minval
self.maxval = maxval
domain = ''
if ((minval is not None) and (maxval is not None)):
domain = '{} <= val < {}'.format(minval, maxval)
elif (minval is not None):
domain = '{} <= val'.format(minval)
elif (maxval is not None):
domain = 'val < {}'.format(maxval)
self.description = ('int({})'.format(domain) if domain else 'int')
self.error_message = ('Value must satisfy: {}'.format(domain) if domain else '') | Create an Integer that satisfies the requirements minval <= val < maxval | terseparse/types.py | __init__ | jthacker/terseparse | 1 | python | def __init__(self, minval=None, maxval=None):
'\n '
self.name = 'int'
self.minval = minval
self.maxval = maxval
domain =
if ((minval is not None) and (maxval is not None)):
domain = '{} <= val < {}'.format(minval, maxval)
elif (minval is not None):
domain = '{} <= val'.format(minval)
elif (maxval is not None):
domain = 'val < {}'.format(maxval)
self.description = ('int({})'.format(domain) if domain else 'int')
self.error_message = ('Value must satisfy: {}'.format(domain) if domain else ) | def __init__(self, minval=None, maxval=None):
'\n '
self.name = 'int'
self.minval = minval
self.maxval = maxval
domain =
if ((minval is not None) and (maxval is not None)):
domain = '{} <= val < {}'.format(minval, maxval)
elif (minval is not None):
domain = '{} <= val'.format(minval)
elif (maxval is not None):
domain = 'val < {}'.format(maxval)
self.description = ('int({})'.format(domain) if domain else 'int')
self.error_message = ('Value must satisfy: {}'.format(domain) if domain else )<|docstring|>Create an Integer that satisfies the requirements minval <= val < maxval<|endoftext|> |
dceed59739b4b899454fadfd1aabf7a573f8eeb93e9fb711a076139a140a9576 | @lru_cache(maxsize=None)
def R(env):
'Return the expected rewards matrix R_{ij} = \\mathbb{E}\\left[ r \\mid s=i, a=j \\right].'
return np.einsum('sat,sato,sato->sa', env.T, env.O, env.R) | Return the expected rewards matrix R_{ij} = \mathbb{E}\left[ r \mid s=i, a=j \right]. | rl_rpsr/matrices.py | R | abaisero/rl-psr | 1 | python | @lru_cache(maxsize=None)
def R(env):
'Return the expected rewards matrix R_{ij} = \\mathbb{E}\\left[ r \\mid s=i, a=j \\right].'
return np.einsum('sat,sato,sato->sa', env.T, env.O, env.R) | @lru_cache(maxsize=None)
def R(env):
'Return the expected rewards matrix R_{ij} = \\mathbb{E}\\left[ r \\mid s=i, a=j \\right].'
return np.einsum('sat,sato,sato->sa', env.T, env.O, env.R)<|docstring|>Return the expected rewards matrix R_{ij} = \mathbb{E}\left[ r \mid s=i, a=j \right].<|endoftext|> |
642d63d0158d0841846fc86bd3f282e2aa08a05a5954419d2403f30f3a5522e7 | @lru_cache(maxsize=None)
def G(env):
"Return the generative matrix G_{ij} = \\Pr(s'=i, o \\mid s=j, a)."
return np.einsum('sat,sato->aots', env.T, env.O) | Return the generative matrix G_{ij} = \Pr(s'=i, o \mid s=j, a). | rl_rpsr/matrices.py | G | abaisero/rl-psr | 1 | python | @lru_cache(maxsize=None)
def G(env):
"Return the generative matrix G_{ij} = \\Pr(s'=i, o \\mid s=j, a)."
return np.einsum('sat,sato->aots', env.T, env.O) | @lru_cache(maxsize=None)
def G(env):
"Return the generative matrix G_{ij} = \\Pr(s'=i, o \\mid s=j, a)."
return np.einsum('sat,sato->aots', env.T, env.O)<|docstring|>Return the generative matrix G_{ij} = \Pr(s'=i, o \mid s=j, a).<|endoftext|> |
e0b7919a69c39d885c17c9374b32382cb1a9655b27639ddc05ad37d3593bd776 | @lru_cache(maxsize=None)
def D(env):
"Return the dynamics matrix D_{ij} = \\Pr(s'=i \\mid s=j, a, o)."
G_ = G(env)
with np.errstate(invalid='ignore'):
return np.nan_to_num((G_ / G_.sum(2, keepdims=True))) | Return the dynamics matrix D_{ij} = \Pr(s'=i \mid s=j, a, o). | rl_rpsr/matrices.py | D | abaisero/rl-psr | 1 | python | @lru_cache(maxsize=None)
def D(env):
"Return the dynamics matrix D_{ij} = \\Pr(s'=i \\mid s=j, a, o)."
G_ = G(env)
with np.errstate(invalid='ignore'):
return np.nan_to_num((G_ / G_.sum(2, keepdims=True))) | @lru_cache(maxsize=None)
def D(env):
"Return the dynamics matrix D_{ij} = \\Pr(s'=i \\mid s=j, a, o)."
G_ = G(env)
with np.errstate(invalid='ignore'):
return np.nan_to_num((G_ / G_.sum(2, keepdims=True)))<|docstring|>Return the dynamics matrix D_{ij} = \Pr(s'=i \mid s=j, a, o).<|endoftext|> |
9e68800c3f2a8032987e1e5877f07ff5cbadc0ead36324fd129ca1a1e78506f6 | def for_A():
" Upper case Alphabet letter 'A' pattern using Python for loop"
for row in range(6):
for col in range(5):
if (((row == 0) and ((col % 4) != 0)) or (((col % 4) == 0) and (row > 0)) or (row == 3)):
print('*', end=' ')
else:
print(' ', end=' ')
print() | Upper case Alphabet letter 'A' pattern using Python for loop | ANSPatterns/uppercase_alphabets/ualp.py | for_A | SaikumarS2611/ANSPatterns | 0 | python | def for_A():
" "
for row in range(6):
for col in range(5):
if (((row == 0) and ((col % 4) != 0)) or (((col % 4) == 0) and (row > 0)) or (row == 3)):
print('*', end=' ')
else:
print(' ', end=' ')
print() | def for_A():
" "
for row in range(6):
for col in range(5):
if (((row == 0) and ((col % 4) != 0)) or (((col % 4) == 0) and (row > 0)) or (row == 3)):
print('*', end=' ')
else:
print(' ', end=' ')
print()<|docstring|>Upper case Alphabet letter 'A' pattern using Python for loop<|endoftext|> |
667c869f411d18cd179aab58e3ab22711c7d46451a6b2f79bfa3d3b300beb8fd | def while_A():
" Upper case Alphabet letter 'A' pattern using Python while loop"
row = 0
while (row < 6):
col = 0
while (col < 5):
if (((row == 0) and ((col % 4) != 0)) or (((col % 4) == 0) and (row > 0)) or (row == 3)):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1 | Upper case Alphabet letter 'A' pattern using Python while loop | ANSPatterns/uppercase_alphabets/ualp.py | while_A | SaikumarS2611/ANSPatterns | 0 | python | def while_A():
" "
row = 0
while (row < 6):
col = 0
while (col < 5):
if (((row == 0) and ((col % 4) != 0)) or (((col % 4) == 0) and (row > 0)) or (row == 3)):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1 | def while_A():
" "
row = 0
while (row < 6):
col = 0
while (col < 5):
if (((row == 0) and ((col % 4) != 0)) or (((col % 4) == 0) and (row > 0)) or (row == 3)):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1<|docstring|>Upper case Alphabet letter 'A' pattern using Python while loop<|endoftext|> |
125eeeed190b0f56d71c486a1e53caf5b706ad711ee14790137fe7af213788e1 | def for_B():
" Upper case Alphabet letter 'B' pattern using Python for loop"
for row in range(7):
for col in range(5):
if ((col == 0) or (((row % 3) == 0) and (col < 4)) or ((col == 4) and ((row % 3) != 0))):
print('*', end=' ')
else:
print(' ', end=' ')
print() | Upper case Alphabet letter 'B' pattern using Python for loop | ANSPatterns/uppercase_alphabets/ualp.py | for_B | SaikumarS2611/ANSPatterns | 0 | python | def for_B():
" "
for row in range(7):
for col in range(5):
if ((col == 0) or (((row % 3) == 0) and (col < 4)) or ((col == 4) and ((row % 3) != 0))):
print('*', end=' ')
else:
print(' ', end=' ')
print() | def for_B():
" "
for row in range(7):
for col in range(5):
if ((col == 0) or (((row % 3) == 0) and (col < 4)) or ((col == 4) and ((row % 3) != 0))):
print('*', end=' ')
else:
print(' ', end=' ')
print()<|docstring|>Upper case Alphabet letter 'B' pattern using Python for loop<|endoftext|> |
0f25027a0b24fec90a2c141001a3c899a610350250b01b7d838713bcaa113730 | def while_B():
" Upper case Alphabet letter 'B' pattern using Python while loop"
row = 0
while (row < 7):
col = 0
while (col < 5):
if ((col == 0) or (((row % 3) == 0) and (col < 4)) or ((col == 4) and ((row % 3) != 0))):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1 | Upper case Alphabet letter 'B' pattern using Python while loop | ANSPatterns/uppercase_alphabets/ualp.py | while_B | SaikumarS2611/ANSPatterns | 0 | python | def while_B():
" "
row = 0
while (row < 7):
col = 0
while (col < 5):
if ((col == 0) or (((row % 3) == 0) and (col < 4)) or ((col == 4) and ((row % 3) != 0))):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1 | def while_B():
" "
row = 0
while (row < 7):
col = 0
while (col < 5):
if ((col == 0) or (((row % 3) == 0) and (col < 4)) or ((col == 4) and ((row % 3) != 0))):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1<|docstring|>Upper case Alphabet letter 'B' pattern using Python while loop<|endoftext|> |
cc35570ce32f85867bb87be6d3a805396e19c91461384e2b9ec4a5f1fc15d95b | def for_C():
" Upper case Alphabet letter 'C' pattern using Python for loop"
for row in range(6):
for col in range(5):
if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col == 0) and (row > 0) and (row < 5)) or ((col == 4) and (row in (1, 4)))):
print('*', end=' ')
else:
print(' ', end=' ')
print() | Upper case Alphabet letter 'C' pattern using Python for loop | ANSPatterns/uppercase_alphabets/ualp.py | for_C | SaikumarS2611/ANSPatterns | 0 | python | def for_C():
" "
for row in range(6):
for col in range(5):
if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col == 0) and (row > 0) and (row < 5)) or ((col == 4) and (row in (1, 4)))):
print('*', end=' ')
else:
print(' ', end=' ')
print() | def for_C():
" "
for row in range(6):
for col in range(5):
if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col == 0) and (row > 0) and (row < 5)) or ((col == 4) and (row in (1, 4)))):
print('*', end=' ')
else:
print(' ', end=' ')
print()<|docstring|>Upper case Alphabet letter 'C' pattern using Python for loop<|endoftext|> |
1b0875727a04581a446ccdc0385528ffec701b176a410803c28a39127d49f528 | def while_C():
" Upper case Alphabet letter 'C' pattern using Python while loop"
row = 0
while (row < 6):
col = 0
while (col < 5):
if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col == 0) and (row > 0) and (row < 5)) or ((col == 4) and (row in (1, 4)))):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1 | Upper case Alphabet letter 'C' pattern using Python while loop | ANSPatterns/uppercase_alphabets/ualp.py | while_C | SaikumarS2611/ANSPatterns | 0 | python | def while_C():
" "
row = 0
while (row < 6):
col = 0
while (col < 5):
if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col == 0) and (row > 0) and (row < 5)) or ((col == 4) and (row in (1, 4)))):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1 | def while_C():
" "
row = 0
while (row < 6):
col = 0
while (col < 5):
if (((row in (0, 5)) and (col > 0) and (col < 4)) or ((col == 0) and (row > 0) and (row < 5)) or ((col == 4) and (row in (1, 4)))):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1<|docstring|>Upper case Alphabet letter 'C' pattern using Python while loop<|endoftext|> |
aa925028fdffdd21cc317744b29f8add6ea6667ecef8a914956dd7ffef0fc080 | def for_D():
" Upper case Alphabet letter 'D' pattern using Python for loop"
for row in range(6):
for col in range(5):
if ((col == 0) or ((row in (0, 5)) and (col < 4)) or ((col == 4) and (row > 0) and (row < 5))):
print('*', end=' ')
else:
print(' ', end=' ')
print() | Upper case Alphabet letter 'D' pattern using Python for loop | ANSPatterns/uppercase_alphabets/ualp.py | for_D | SaikumarS2611/ANSPatterns | 0 | python | def for_D():
" "
for row in range(6):
for col in range(5):
if ((col == 0) or ((row in (0, 5)) and (col < 4)) or ((col == 4) and (row > 0) and (row < 5))):
print('*', end=' ')
else:
print(' ', end=' ')
print() | def for_D():
" "
for row in range(6):
for col in range(5):
if ((col == 0) or ((row in (0, 5)) and (col < 4)) or ((col == 4) and (row > 0) and (row < 5))):
print('*', end=' ')
else:
print(' ', end=' ')
print()<|docstring|>Upper case Alphabet letter 'D' pattern using Python for loop<|endoftext|> |
25a2c41a87b10eca6adf871b6de035f6e3ae8ed1da1147e722c77675c79cfb2a | def while_D():
" Upper case Alphabet letter 'D' pattern using Python while loop"
row = 0
while (row < 6):
col = 0
while (col < 5):
if ((col == 0) or ((row in (0, 5)) and (col < 4)) or ((col == 4) and (row > 0) and (row < 5))):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1 | Upper case Alphabet letter 'D' pattern using Python while loop | ANSPatterns/uppercase_alphabets/ualp.py | while_D | SaikumarS2611/ANSPatterns | 0 | python | def while_D():
" "
row = 0
while (row < 6):
col = 0
while (col < 5):
if ((col == 0) or ((row in (0, 5)) and (col < 4)) or ((col == 4) and (row > 0) and (row < 5))):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1 | def while_D():
" "
row = 0
while (row < 6):
col = 0
while (col < 5):
if ((col == 0) or ((row in (0, 5)) and (col < 4)) or ((col == 4) and (row > 0) and (row < 5))):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
print()
row += 1<|docstring|>Upper case Alphabet letter 'D' pattern using Python while loop<|endoftext|> |
dbabb6c9913e7509f5fc489baa1865743bc5205e4d6dc252ff685b15430010ec | def for_E():
" Upper case Alphabet letter 'E' pattern using Python for loop"
for row in range(7):
for col in range(4):
if ((col == 0) or ((row % 3) == 0)):
print('*', end=' ')
else:
print(' ', end=' ')
print() | Upper case Alphabet letter 'E' pattern using Python for loop | ANSPatterns/uppercase_alphabets/ualp.py | for_E | SaikumarS2611/ANSPatterns | 0 | python | def for_E():
" "
for row in range(7):
for col in range(4):
if ((col == 0) or ((row % 3) == 0)):
print('*', end=' ')
else:
print(' ', end=' ')
print() | def for_E():
" "
for row in range(7):
for col in range(4):
if ((col == 0) or ((row % 3) == 0)):
print('*', end=' ')
else:
print(' ', end=' ')
print()<|docstring|>Upper case Alphabet letter 'E' pattern using Python for loop<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.