Python:为列表中的每个元素分配百分比

时间:2017-05-08 18:10:05

标签: python list iteration

我有一个基于简单移动平均线购买股票的算法,但我仍然试图将一个百分比分配给一个动态列表。

例如,允许算法在第一周购买四个股票,因此创建一个包含四个元素的列表:["apple", "google", "tesla", "AMD"]

下周它会购买六只股票,并创建一个包含六只股票的清单:["apple", "google", "tesla", "AMD", "intel", "qualcomm"]

我想要做的是为列表中的每个元素动态分配百分比,该百分比等于100%。

因此,在第一周,Apple将被分配50%,Google将被分配为25%,Tesla将被分配为15%,而AMD将被分配为10%。

在第二周,苹果可能被分配50%,谷歌25%,特斯拉16.5%,AMD 5%,英特尔2.5%,高通1%。

在最终结果中,我想给算法一个数字列表,并为每个元素指定一个百分比从高开始到结束低但仍然等于100%。

这是我目前的代码:

from quantopian.pipeline.factors import VWAP
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.filters.morningstar import Q1500US
import numpy as np
import pandas as pd
import math

def initialize(context):
    """
    Called once at the start of the algorithm.
    """   

    # Sets default slippage and commission fees to simulate real trading.
    set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.00))
    set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
    set_asset_restrictions(security_lists.restrict_leveraged_etfs)

    # Creates a function that runs at the beginning of each week.
    schedule_function(start_of_week, date_rules.week_start(), time_rules.market_open(hours=1))

    # Rebalance every day, 1 hour after market open.
    schedule_function(my_rebalance, date_rules.week_end(), time_rules.market_open(hours=1))

    # Record tracking variables at the end of each day.
    schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())

    #Creates a function that runs at the beginning of everyday.
    schedule_function(start_of_day, date_rules.every_day(), time_rules.market_open(hours=1.5))

    # Create our dynamic stock selector.
    pipe = Pipeline()
    attach_pipeline(pipe, name='my_pipeline')

    # Construct Volume Factor.
    vwap = VWAP(inputs=[USEquityPricing.close, USEquityPricing.volume], window_length=14)

    prices_under_5 = (vwap < 5)

    pipe.set_screen(prices_under_5)

    context.df_long = pd.DataFrame(None, columns=list("ABC"))
    context.df_short = pd.DataFrame(None, columns=list("ABC"))
    context.long_list = []
    context.short_list = []

def start_of_week(context, data):
    """
    Called at the begining of every week before market open.
    """
    context.df_long = pd.DataFrame(None, columns=list("AB"))
    context.df_short = pd.DataFrame(None, columns=list("AB"))
    context.long_list = []
    context.short_list = []

    context.output = pipeline_output('my_pipeline')

    # These are the securities that we are interested in trading each day.
    context.security_list = context.output.sort_index(axis=0, ascending=True, kind='quicksort')
    context.security_list = context.security_list.index


    for security in context.security_list:

        # Gets Simple Moving Average for 7 days and 100 days
        price_hist_8 = data.history(security, 'price', 7, '1d')
        mavg8 = price_hist_8.mean()
        price_hist_14 = data.history(security, 'price', 100, '1d')
        mavg14 = price_hist_14.mean()
        current_vol = data.current(securrity, "volume")


        if mavg8 > mavg14:
            #Calculate percent increase of volume
            current_vol = data.current(security, "volume")
            hist_vol = data.history(security, "volume", 10, "1d")
            difference_increase_vol = current_vol - hist_vol
            percent_increase_vol = (difference_increase_vol / hist_vol) * 100
            percent_increase_vol = percent_increase_vol[0]

            if perecent_increase_vol >= 0:
                context.df_long_tbd = pd.DataFrame([[security, mavg8]], columns=list("AB"))
                frames = [context.df_long, context.df_long_tbd]
                context.df_long = pd.concat(frames)





# Sorts all of the stocks in the "long" Data Frame from steepest incline in simple moving average over 8 days. The "final_long_list" contains all of the top stocks' names.
result_long = context.df_long.sort_values(by=["B", "A"], ascending=False)
context.long_final_list = result_long["A"]

# Total amout of stocks that the algorithim is allowed to buy will be determined on total portfolial value.
# If the total portfolial value is $100,000, the algorithim is only allowed to look at 
port_val = context.portfolio.portfolio_value
allowed_to_purchase = round(sqrt(port_val)/10)

for stock in context.long_final_list[:allowed_to_purchase]:
    if data.can_trade(stock):

让我们说“allowed_to_purchase”等于10.现在,我想将每个股票分配到我的context.long_final_list的前十位,从高位开始到低位,等于100%。

是否有简单的解决方案或内置功能? “context.long_final_list”是一个pandas数据框,pandas有没有函数?

1 个答案:

答案 0 :(得分:0)

解决了!如果我将所有股票价值添加到总单个期限中,然后将总期限除以每个股票的价值。

例如在我的Pandas Data Frame context.long_final_list:

A       B
Apple   150
Google  600
AMD     12


#Counter
n = 0

#For every stock price in my pandas data frame add it's value to n. 
#n will equal the total price of all the stocks.
for stock in context.long_final_list["B"]:
    n = n+stock

#Now, to assign percentages to divide the stock by n.

Apple_percent = apple/n